code
stringlengths
1
2.08M
language
stringclasses
1 value
var tinymce = null, tinyMCEPopup, tinyMCE, wpImage; tinyMCEPopup = { init: function() { var t = this, w, ti; // Find window & API w = t.getWin(); tinymce = w.tinymce; tinyMCE = w.tinyMCE; t.editor = tinymce.EditorManager.activeEditor; t.params = t.editor.windowManager.params; t.features = t.editor.windowManager.features; // Setup local DOM t.dom = t.editor.windowManager.createInstance('tinymce.dom.DOMUtils', document); t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window); }, getWin : function() { return (!window.frameElement && window.dialogArguments) || opener || parent || top; }, getParam : function(n, dv) { return this.editor.getParam(n, dv); }, close : function() { var t = this; // To avoid domain relaxing issue in Opera function close() { t.editor.windowManager.close(window); tinymce = tinyMCE = t.editor = t.params = t.dom = t.dom.doc = null; // Cleanup }; if (tinymce.isOpera) t.getWin().setTimeout(close, 0); else close(); }, execCommand : function(cmd, ui, val, a) { a = a || {}; a.skip_focus = 1; this.restoreSelection(); return this.editor.execCommand(cmd, ui, val, a); }, storeSelection : function() { this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark(1); }, restoreSelection : function() { var t = tinyMCEPopup; if ( tinymce.isIE ) t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark); } } tinyMCEPopup.init(); wpImage = { preInit : function() { // import colors stylesheet from parent var ed = tinyMCEPopup.editor, win = tinyMCEPopup.getWin(), styles = win.document.styleSheets, url, i; for ( i = 0; i < styles.length; i++ ) { url = styles.item(i).href; if ( url && url.indexOf('colors') != -1 ) { document.getElementsByTagName('head')[0].appendChild( ed.dom.create('link', {rel:'stylesheet', href: url}) ); break; } } }, I : function(e) { return document.getElementById(e); }, current : '', link : '', link_rel : '', target_value : '', current_size_sel : 's100', width : '', height : '', align : '', img_alt : '', setTabs : function(tab) { var t = this; if ( 'current' == tab.className ) return false; t.I('div_advanced').style.display = ( 'tab_advanced' == tab.id ) ? 'block' : 'none'; t.I('div_basic').style.display = ( 'tab_basic' == tab.id ) ? 'block' : 'none'; t.I('tab_basic').className = t.I('tab_advanced').className = ''; tab.className = 'current'; return false; }, img_seturl : function(u) { var t = this, rel = t.I('link_rel').value; if ( 'current' == u ) { t.I('link_href').value = t.current; t.I('link_rel').value = t.link_rel; } else { t.I('link_href').value = t.link; if ( rel ) { rel = rel.replace( /attachment|wp-att-[0-9]+/gi, '' ); t.I('link_rel').value = tinymce.trim(rel); } } }, imgAlignCls : function(v) { var t = this, cls = t.I('img_classes').value; t.I('img_demo').className = t.align = v; cls = cls.replace( /align[^ "']+/gi, '' ); cls += (' ' + v); cls = cls.replace( /\s+/g, ' ' ).replace( /^\s/, '' ); if ( 'aligncenter' == v ) { t.I('hspace').value = ''; t.updateStyle('hspace'); } t.I('img_classes').value = cls; }, showSize : function(el) { var t = this, demo = t.I('img_demo'), w = t.width, h = t.height, id = el.id || 's100', size; size = parseInt(id.substring(1)) / 200; demo.width = Math.round(w * size); demo.height = Math.round(h * size); t.showSizeClear(); el.style.borderColor = '#A3A3A3'; el.style.backgroundColor = '#E5E5E5'; }, showSizeSet : function() { var t = this, s130, s120, s110; if ( (t.width * 1.3) > parseInt(t.preloadImg.width) ) { s130 = t.I('s130'), s120 = t.I('s120'), s110 = t.I('s110'); s130.onclick = s120.onclick = s110.onclick = null; s130.onmouseover = s120.onmouseover = s110.onmouseover = null; s130.style.color = s120.style.color = s110.style.color = '#aaa'; } }, showSizeRem : function() { var t = this, demo = t.I('img_demo'), f = document.forms[0]; demo.width = Math.round(f.width.value * 0.5); demo.height = Math.round(f.height.value * 0.5); t.showSizeClear(); t.I(t.current_size_sel).style.borderColor = '#A3A3A3'; t.I(t.current_size_sel).style.backgroundColor = '#E5E5E5'; return false; }, showSizeClear : function() { var divs = this.I('img_size').getElementsByTagName('div'), i; for ( i = 0; i < divs.length; i++ ) { divs[i].style.borderColor = '#f1f1f1'; divs[i].style.backgroundColor = '#f1f1f1'; } }, imgEditSize : function(el) { var t = this, f = document.forms[0], W, H, w, h, id; if ( ! t.preloadImg || ! t.preloadImg.width || ! t.preloadImg.height ) return; W = parseInt(t.preloadImg.width), H = parseInt(t.preloadImg.height), w = t.width || W, h = t.height || H, id = el.id || 's100'; size = parseInt(id.substring(1)) / 100; w = Math.round(w * size); h = Math.round(h * size); f.width.value = Math.min(W, w); f.height.value = Math.min(H, h); t.current_size_sel = id; t.demoSetSize(); }, demoSetSize : function(img) { var demo = this.I('img_demo'), f = document.forms[0]; demo.width = f.width.value ? Math.round(f.width.value * 0.5) : ''; demo.height = f.height.value ? Math.round(f.height.value * 0.5) : ''; }, demoSetStyle : function() { var f = document.forms[0], demo = this.I('img_demo'), dom = tinyMCEPopup.editor.dom; if (demo) { dom.setAttrib(demo, 'style', f.img_style.value); dom.setStyle(demo, 'width', ''); dom.setStyle(demo, 'height', ''); } }, origSize : function() { var t = this, f = document.forms[0], el = t.I('s100'); f.width.value = t.width = t.preloadImg.width; f.height.value = t.height = t.preloadImg.height; t.showSizeSet(); t.demoSetSize(); t.showSize(el); }, init : function() { var ed = tinyMCEPopup.editor, h; h = document.body.innerHTML; document.body.innerHTML = ed.translate(h); window.setTimeout( function(){wpImage.setup();}, 500 ); }, setup : function() { var t = this, c, el, link, fname, f = document.forms[0], ed = tinyMCEPopup.editor, d = t.I('img_demo'), dom = tinyMCEPopup.dom, DL, DD, caption = '', dlc, pa; document.dir = tinyMCEPopup.editor.getParam('directionality',''); if ( tinyMCEPopup.editor.getParam('wpeditimage_disable_captions', false) ) t.I('cap_field').style.display = 'none'; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; f.img_src.value = d.src = link = ed.dom.getAttrib(el, 'src'); ed.dom.setStyle(el, 'float', ''); t.getImageData(); c = ed.dom.getAttrib(el, 'class'); if ( DL = dom.getParent(el, 'dl') ) { dlc = ed.dom.getAttrib(DL, 'class'); dlc = dlc.match(/align[^ "']+/i); if ( dlc && ! dom.hasClass(el, dlc) ) { c += ' '+dlc; tinymce.trim(c); } DD = ed.dom.select('dd.wp-caption-dd', DL); if ( DD && DD[0] ) caption = ed.serializer.serialize(DD[0]).replace(/^<p>/, '').replace(/<\/p>$/, ''); } f.img_cap_text.value = caption; f.img_title.value = ed.dom.getAttrib(el, 'title'); f.img_alt.value = ed.dom.getAttrib(el, 'alt'); f.border.value = ed.dom.getAttrib(el, 'border'); f.vspace.value = ed.dom.getAttrib(el, 'vspace'); f.hspace.value = ed.dom.getAttrib(el, 'hspace'); f.align.value = ed.dom.getAttrib(el, 'align'); f.width.value = t.width = ed.dom.getAttrib(el, 'width'); f.height.value = t.height = ed.dom.getAttrib(el, 'height'); f.img_classes.value = c; f.img_style.value = ed.dom.getAttrib(el, 'style'); // Move attribs to styles if ( dom.getAttrib(el, 'hspace') ) t.updateStyle('hspace'); if ( dom.getAttrib(el, 'border') ) t.updateStyle('border'); if ( dom.getAttrib(el, 'vspace') ) t.updateStyle('vspace'); if ( pa = ed.dom.getParent(el, 'A') ) { f.link_href.value = t.current = ed.dom.getAttrib(pa, 'href'); f.link_title.value = ed.dom.getAttrib(pa, 'title'); f.link_rel.value = t.link_rel = ed.dom.getAttrib(pa, 'rel'); f.link_style.value = ed.dom.getAttrib(pa, 'style'); t.target_value = ed.dom.getAttrib(pa, 'target'); f.link_classes.value = ed.dom.getAttrib(pa, 'class'); } f.link_target.checked = ( t.target_value && t.target_value == '_blank' ) ? 'checked' : ''; fname = link.substring( link.lastIndexOf('/') ); fname = fname.replace(/-[0-9]{2,4}x[0-9]{2,4}/, '' ); t.link = link.substring( 0, link.lastIndexOf('/') ) + fname; if ( c.indexOf('alignleft') != -1 ) { t.I('alignleft').checked = "checked"; d.className = t.align = "alignleft"; } else if ( c.indexOf('aligncenter') != -1 ) { t.I('aligncenter').checked = "checked"; d.className = t.align = "aligncenter"; } else if ( c.indexOf('alignright') != -1 ) { t.I('alignright').checked = "checked"; d.className = t.align = "alignright"; } else if ( c.indexOf('alignnone') != -1 ) { t.I('alignnone').checked = "checked"; d.className = t.align = "alignnone"; } if ( t.width && t.preloadImg.width ) t.showSizeSet(); document.body.style.display = ''; }, remove : function() { var ed = tinyMCEPopup.editor, p, el; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') ) ed.dom.remove(p); else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 ) ed.dom.remove(p); else ed.dom.remove(el); ed.execCommand('mceRepaint'); tinyMCEPopup.close(); return; }, update : function() { var t = this, f = document.forms[0], ed = tinyMCEPopup.editor, el, b, fixSafari = null, DL, P, A, DIV, do_caption = null, img_class = f.img_classes.value, html, id, cap_id = '', cap, DT, DD, cap_width, div_cls, lnk = '', pa, aa, caption; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; if (f.img_src.value === '') { t.remove(); return; } if ( f.img_cap_text.value != '' && f.width.value != '' ) { do_caption = 1; img_class = img_class.replace( /align[^ "']+\s?/gi, '' ); } A = ed.dom.getParent(el, 'a'); P = ed.dom.getParent(el, 'p'); DL = ed.dom.getParent(el, 'dl'); DIV = ed.dom.getParent(el, 'div'); tinyMCEPopup.execCommand("mceBeginUndoLevel"); if ( f.width.value != el.width || f.height.value != el.height ) img_class = img_class.replace(/size-[^ "']+/, ''); ed.dom.setAttribs(el, { src : f.img_src.value, title : f.img_title.value, alt : f.img_alt.value, width : f.width.value, height : f.height.value, style : f.img_style.value, 'class' : img_class }); if ( f.link_href.value ) { // Create new anchor elements if ( A == null ) { if ( ! f.link_href.value.match(/https?:\/\//i) ) f.link_href.value = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.link_href.value); ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if ( ed.dom.getAttrib(n, 'href') == '#mce_temp_url#' ) { ed.dom.setAttribs(n, { href : f.link_href.value, title : f.link_title.value, rel : f.link_rel.value, target : (f.link_target.checked == true) ? '_blank' : '', 'class' : f.link_classes.value, style : f.link_style.value }); } }); } else { ed.dom.setAttribs(A, { href : f.link_href.value, title : f.link_title.value, rel : f.link_rel.value, target : (f.link_target.checked == true) ? '_blank' : '', 'class' : f.link_classes.value, style : f.link_style.value }); } } if ( do_caption ) { cap_width = 10 + parseInt(f.width.value); div_cls = (t.align == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp'; caption = f.img_cap_text.value; caption = caption.replace(/\r\n|\r/g, '\n').replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){ return a.replace(/[\r\n\t]+/, ' '); }); caption = caption.replace(/\s*\n\s*/g, '<br />'); if ( DL ) { ed.dom.setAttribs(DL, { 'class' : 'wp-caption '+t.align, style : 'width: '+cap_width+'px;' }); if ( DIV ) ed.dom.setAttrib(DIV, 'class', div_cls); if ( (DT = ed.dom.getParent(el, 'dt')) && (DD = DT.nextSibling) && ed.dom.hasClass(DD, 'wp-caption-dd') ) ed.dom.setHTML(DD, caption); } else { if ( (id = f.img_classes.value.match( /wp-image-([0-9]{1,6})/ )) && id[1] ) cap_id = 'attachment_'+id[1]; if ( f.link_href.value && (lnk = ed.dom.getParent(el, 'a')) ) { if ( lnk.childNodes.length == 1 ) { html = ed.dom.getOuterHTML(lnk); } else { html = ed.dom.getOuterHTML(lnk); html = html.match(/<a [^>]+>/i); html = html+ed.dom.getOuterHTML(el)+'</a>'; } } else { html = ed.dom.getOuterHTML(el); } html = '<dl id="'+cap_id+'" class="wp-caption '+t.align+'" style="width: '+cap_width+ 'px"><dt class="wp-caption-dt">'+html+'</dt><dd class="wp-caption-dd">'+caption+'</dd></dl>'; cap = ed.dom.create('div', {'class': div_cls}, html); if ( P ) { P.parentNode.insertBefore(cap, P); if ( P.childNodes.length == 1 ) ed.dom.remove(P); else if ( lnk && lnk.childNodes.length == 1 ) ed.dom.remove(lnk); else ed.dom.remove(el); } else if ( pa = ed.dom.getParent(el, 'TD,TH,LI') ) { pa.appendChild(cap); if ( lnk && lnk.childNodes.length == 1 ) ed.dom.remove(lnk); else ed.dom.remove(el); } } } else { if ( DL && DIV ) { if ( f.link_href.value && (aa = ed.dom.getParent(el, 'a')) ) html = ed.dom.getOuterHTML(aa); else html = ed.dom.getOuterHTML(el); P = ed.dom.create('p', {}, html); DIV.parentNode.insertBefore(P, DIV); ed.dom.remove(DIV); } } if ( f.img_classes.value.indexOf('aligncenter') != -1 ) { if ( P && ( ! P.style || P.style.textAlign != 'center' ) ) ed.dom.setStyle(P, 'textAlign', 'center'); } else { if ( P && P.style && P.style.textAlign == 'center' ) ed.dom.setStyle(P, 'textAlign', ''); } if ( ! f.link_href.value && A ) { b = ed.selection.getBookmark(); ed.dom.remove(A, 1); ed.selection.moveToBookmark(b); } tinyMCEPopup.execCommand("mceEndUndoLevel"); ed.execCommand('mceRepaint'); tinyMCEPopup.close(); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, v, f = document.forms[0], img = dom.create('img', {style : f.img_style.value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = f.align.value; if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = '0'; else img.style.border = v + 'px solid black'; } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge f.img_style.value = dom.serializeStyle(dom.parseStyle(img.style.cssText)); this.demoSetStyle(); } }, checkVal : function(f) { if ( f.value == '' ) { // if ( f.id == 'width' ) f.value = this.width || this.preloadImg.width; // if ( f.id == 'height' ) f.value = this.height || this.preloadImg.height; if ( f.id == 'img_src' ) f.value = this.I('img_demo').src || this.preloadImg.src; } }, resetImageData : function() { var f = document.forms[0]; f.width.value = f.height.value = ''; }, updateImageData : function() { var f = document.forms[0], t = wpImage, w = f.width.value, h = f.height.value; if ( !w && h ) w = f.width.value = t.width = Math.round( t.preloadImg.width / (t.preloadImg.height / h) ); else if ( w && !h ) h = f.height.value = t.height = Math.round( t.preloadImg.height / (t.preloadImg.width / w) ); if ( !w ) f.width.value = t.width = t.preloadImg.width; if ( !h ) f.height.value = t.height = t.preloadImg.height; t.showSizeSet(); t.demoSetSize(); if ( f.img_style.value ) t.demoSetStyle(); }, getImageData : function() { var t = wpImage, f = document.forms[0]; t.preloadImg = new Image(); t.preloadImg.onload = t.updateImageData; t.preloadImg.onerror = t.resetImageData; t.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.img_src.value); } }; window.onload = function(){wpImage.init();} wpImage.preInit();
JavaScript
(function() { tinymce.create('tinymce.plugins.wpEditImage', { url: '', editor: {}, init: function(ed, url) { var t = this, mouse = {}; t.url = url; t.editor = ed; t._createButtons(); ed.addCommand('WP_EditImage', t._editImage); ed.onInit.add(function(ed) { ed.dom.events.add(ed.getBody(), 'mousedown', function(e) { var parent; if ( e.target.nodeName == 'IMG' && ( parent = ed.dom.getParent(e.target, 'div.mceTemp') ) ) { if ( tinymce.isGecko ) ed.selection.select(parent); else if ( tinymce.isWebKit ) ed.dom.events.prevent(e); } }); // when pressing Return inside a caption move the caret to a new parapraph under it ed.dom.events.add(ed.getBody(), 'keydown', function(e) { var n, DL, DIV, P, content; if ( e.keyCode == 13 ) { n = ed.selection.getNode(); DL = ed.dom.getParent(n, 'dl.wp-caption'); if ( DL ) DIV = ed.dom.getParent(DL, 'div.mceTemp'); if ( DIV ) { ed.dom.events.cancel(e); P = ed.dom.create('p', {}, '\uFEFF'); ed.dom.insertAfter( P, DIV ); ed.selection.setCursorLocation(P, 0); return false; } } }); // iOS6 doesn't show the buttons properly on click, show them on 'touchstart' if ( 'ontouchstart' in window ) { ed.dom.events.add(ed.getBody(), 'touchstart', function(e){ t._showButtons(e); }); } }); // resize the caption <dl> when the image is soft-resized by the user ed.onMouseUp.add(function(ed, e) { if ( tinymce.isWebKit || tinymce.isOpera ) return; if ( mouse.x && (e.clientX != mouse.x || e.clientY != mouse.y) ) { var n = ed.selection.getNode(); if ( 'IMG' == n.nodeName ) { window.setTimeout(function(){ var DL = ed.dom.getParent(n, 'dl.wp-caption'), width; if ( n.width != mouse.img_w || n.height != mouse.img_h ) n.className = n.className.replace(/size-[^ "']+/, ''); if ( DL ) { width = ed.dom.getAttrib(n, 'width') || n.width; width = parseInt(width, 10); ed.dom.setStyle(DL, 'width', 10 + width); ed.execCommand('mceRepaint'); } }, 100); } } mouse = {}; }); // show editimage buttons ed.onMouseDown.add(function(ed, e){ t._showButtons(e); }); ed.onBeforeSetContent.add(function(ed, o) { o.content = ed.wpSetImgCaption(o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = ed.wpGetImgCaption(o.content); }); ed.wpSetImgCaption = function(content) { return t._do_shcode(content); }; ed.wpGetImgCaption = function(content) { return t._get_shcode(content); }; // When inserting content, if the caret is inside a caption create new paragraph under // and move the caret there ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { var node, p; if ( cmd == 'mceInsertContent' ) { node = ed.dom.getParent(ed.selection.getNode(), 'div.mceTemp'); if ( !node ) return; p = ed.dom.create('p'); ed.dom.insertAfter( p, node ); ed.selection.setCursorLocation(p, 0); } }); }, _do_shcode : function(content) { return content.replace(/(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?/g, function(a,b,c){ var id, cls, w, cap, div_cls, img, trim = tinymce.trim; id = b.match(/id=['"]([^'"]*)['"] ?/); if ( id ) b = b.replace(id[0], ''); cls = b.match(/align=['"]([^'"]*)['"] ?/); if ( cls ) b = b.replace(cls[0], ''); w = b.match(/width=['"]([0-9]*)['"] ?/); if ( w ) b = b.replace(w[0], ''); c = trim(c); img = c.match(/((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i); if ( img && img[2] ) { cap = trim( img[2] ); img = trim( img[1] ); } else { // old captions shortcode style cap = trim(b).replace(/caption=['"]/, '').replace(/['"]$/, ''); img = c; } id = ( id && id[1] ) ? id[1] : ''; cls = ( cls && cls[1] ) ? cls[1] : 'alignnone'; w = ( w && w[1] ) ? w[1] : ''; if ( !w || !cap ) return c; div_cls = 'mceTemp'; if ( cls == 'aligncenter' ) div_cls += ' mceIEcenter'; return '<div class="'+div_cls+'"><dl id="'+id+'" class="wp-caption '+cls+'" style="width: '+( 10 + parseInt(w) )+ 'px"><dt class="wp-caption-dt">'+img+'</dt><dd class="wp-caption-dd">'+cap+'</dd></dl></div>'; }); }, _get_shcode : function(content) { return content.replace(/<div (?:id="attachment_|class="mceTemp)[^>]*>([\s\S]+?)<\/div>/g, function(a, b){ var ret = b.replace(/<dl ([^>]+)>\s*<dt [^>]+>([\s\S]+?)<\/dt>\s*<dd [^>]+>([\s\S]*?)<\/dd>\s*<\/dl>/gi, function(a,b,c,cap){ var id, cls, w; w = c.match(/width="([0-9]*)"/); w = ( w && w[1] ) ? w[1] : ''; if ( !w || !cap ) return c; id = b.match(/id="([^"]*)"/); id = ( id && id[1] ) ? id[1] : ''; cls = b.match(/class="([^"]*)"/); cls = ( cls && cls[1] ) ? cls[1] : ''; cls = cls.match(/align[a-z]+/) || 'alignnone'; cap = cap.replace(/\r\n|\r/g, '\n').replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){ // no line breaks inside HTML tags return a.replace(/[\r\n\t]+/, ' '); }); // convert remaining line breaks to <br> cap = cap.replace(/\s*\n\s*/g, '<br />'); return '[caption id="'+id+'" align="'+cls+'" width="'+w+'"]'+c+' '+cap+'[/caption]'; }); if ( ret.indexOf('[caption') !== 0 ) { // the caption html seems brocken, try to find the image that may be wrapped in a link // and may be followed by <p> with the caption text. ret = b.replace(/[\s\S]*?((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)(<p>[\s\S]*<\/p>)?[\s\S]*/gi, '<p>$1</p>$2'); } return ret; }); }, _createButtons : function() { var t = this, ed = tinymce.activeEditor, DOM = tinymce.DOM, editButton, dellButton, isRetina; if ( DOM.get('wp_editbtns') ) return; isRetina = ( window.devicePixelRatio && window.devicePixelRatio > 1 ) || // WebKit, Opera ( window.matchMedia && window.matchMedia('(min-resolution:130dpi)').matches ); // Firefox, IE10, Opera DOM.add(document.body, 'div', { id : 'wp_editbtns', style : 'display:none;' }); editButton = DOM.add('wp_editbtns', 'img', { src : isRetina ? t.url+'/img/image-2x.png' : t.url+'/img/image.png', id : 'wp_editimgbtn', width : '24', height : '24', title : ed.getLang('wpeditimage.edit_img') }); tinymce.dom.Event.add(editButton, 'mousedown', function(e) { t._editImage(); ed.plugins.wordpress._hideButtons(); }); dellButton = DOM.add('wp_editbtns', 'img', { src : isRetina ? t.url+'/img/delete-2x.png' : t.url+'/img/delete.png', id : 'wp_delimgbtn', width : '24', height : '24', title : ed.getLang('wpeditimage.del_img') }); tinymce.dom.Event.add(dellButton, 'mousedown', function(e) { var ed = tinymce.activeEditor, el = ed.selection.getNode(), parent; if ( el.nodeName == 'IMG' && ed.dom.getAttrib(el, 'class').indexOf('mceItem') == -1 ) { if ( (parent = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(parent, 'mceTemp') ) { ed.dom.remove(parent); } else { if ( el.parentNode.nodeName == 'A' && el.parentNode.childNodes.length == 1 ) el = el.parentNode; if ( el.parentNode.nodeName == 'P' && el.parentNode.childNodes.length == 1 ) el = el.parentNode; ed.dom.remove(el); } ed.execCommand('mceRepaint'); return false; } ed.plugins.wordpress._hideButtons(); }); }, _editImage : function() { var ed = tinymce.activeEditor, url = this.url, el = ed.selection.getNode(), vp, H, W, cls = el.className; if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 || el.nodeName != 'IMG' ) return; vp = tinymce.DOM.getViewPort(); H = 680 < (vp.h - 70) ? 680 : vp.h - 70; W = 650 < vp.w ? 650 : vp.w; ed.windowManager.open({ file: url + '/editimage.html', width: W+'px', height: H+'px', inline: true }); }, _showButtons : function(e) { var ed = this.editor, target = e.target; if ( target.nodeName != 'IMG' ) { if ( target.firstChild && target.firstChild.nodeName == 'IMG' && target.childNodes.length == 1 ) { target = target.firstChild; } else { ed.plugins.wordpress._hideButtons(); return; } } if ( ed.dom.getAttrib(target, 'class').indexOf('mceItem') == -1 ) { mouse = { x: e.clientX, y: e.clientY, img_w: target.clientWidth, img_h: target.clientHeight }; if ( e.type == 'touchstart' ) { ed.selection.select(target); ed.dom.events.cancel(e); } ed.plugins.wordpress._hideButtons(); ed.plugins.wordpress._showButtons(target, 'wp_editbtns'); } }, getInfo : function() { return { longname : 'Edit Image', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); tinymce.PluginManager.add('wpeditimage', tinymce.plugins.wpEditImage); })();
JavaScript
tinyMCEPopup.requireLangPack(); var PasteTextDialog = { init : function() { this.resize(); }, insert : function() { var h = tinyMCEPopup.dom.encode(document.getElementById('content').value), lines; // Convert linebreaks into paragraphs if (document.getElementById('linebreaks').checked) { lines = h.split(/\r?\n/); if (lines.length > 1) { h = ''; tinymce.each(lines, function(row) { h += '<p>' + row + '</p>'; }); } } tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('content'); el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } }; tinyMCEPopup.onInit.add(PasteTextDialog.init, PasteTextDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var PasteWordDialog = { init : function() { var ed = tinyMCEPopup.editor, el = document.getElementById('iframecontainer'), ifr, doc, css, cssHTML = ''; // Create iframe el.innerHTML = '<iframe id="iframe" src="javascript:\'\';" frameBorder="0" style="border: 1px solid gray"></iframe>'; ifr = document.getElementById('iframe'); doc = ifr.contentWindow.document; // Force absolute CSS urls css = [ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css")]; css = css.concat(tinymce.explode(ed.settings.content_css) || []); tinymce.each(css, function(u) { cssHTML += '<link href="' + ed.documentBaseURI.toAbsolute('' + u) + '" rel="stylesheet" type="text/css" />'; }); // Write content into iframe doc.open(); doc.write('<html><head>' + cssHTML + '</head><body class="mceContentBody" spellcheck="false"></body></html>'); doc.close(); doc.designMode = 'on'; this.resize(); window.setTimeout(function() { ifr.contentWindow.focus(); }, 10); }, insert : function() { var h = document.getElementById('iframe').contentWindow.document.body.innerHTML; tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h, wordContent : true}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('iframe'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } } }; tinyMCEPopup.onInit.add(PasteWordDialog.init, PasteWordDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each, defs = { paste_auto_cleanup_on_paste : true, paste_enable_default_filters : true, paste_block_drop : false, paste_retain_style_properties : "none", paste_strip_class_attributes : "mso", paste_remove_spans : false, paste_remove_styles : false, paste_remove_styles_if_webkit : true, paste_convert_middot_lists : true, paste_convert_headers_to_strong : false, paste_dialog_width : "450", paste_dialog_height : "400", paste_max_consecutive_linebreaks: 2, paste_text_use_dialog : false, paste_text_sticky : false, paste_text_sticky_default : false, paste_text_notifyalways : false, paste_text_linebreaktype : "combined", paste_text_replacements : [ [/\u2026/g, "..."], [/[\x93\x94\u201c\u201d]/g, '"'], [/[\x60\x91\x92\u2018\u2019]/g, "'"] ] }; function getParam(ed, name) { return ed.getParam(name, defs[name]); } tinymce.create('tinymce.plugins.PastePlugin', { init : function(ed, url) { var t = this; t.editor = ed; t.url = url; // Setup plugin events t.onPreProcess = new tinymce.util.Dispatcher(t); t.onPostProcess = new tinymce.util.Dispatcher(t); // Register default handlers t.onPreProcess.add(t._preProcess); t.onPostProcess.add(t._postProcess); // Register optional preprocess handler t.onPreProcess.add(function(pl, o) { ed.execCallback('paste_preprocess', pl, o); }); // Register optional postprocess t.onPostProcess.add(function(pl, o) { ed.execCallback('paste_postprocess', pl, o); }); ed.onKeyDown.addToTop(function(ed, e) { // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) return false; // Stop other listeners }); // Initialize plain text flag ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default'); // This function executes the process handlers and inserts the contents // force_rich overrides plain text mode set by user, important for pasting with execCommand function process(o, force_rich) { var dom = ed.dom, rng; // Execute pre process handlers t.onPreProcess.dispatch(t, o); // Create DOM structure o.node = dom.create('div', 0, o.content); // If pasting inside the same element and the contents is only one block // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element if (tinymce.isGecko) { rng = ed.selection.getRng(true); if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) { // Is only one block node and it doesn't contain word stuff if (o.node.childNodes.length === 1 && /^(p|h[1-6]|pre)$/i.test(o.node.firstChild.nodeName) && o.content.indexOf('__MCE_ITEM__') === -1) dom.remove(o.node.firstChild, true); } } // Execute post process handlers t.onPostProcess.dispatch(t, o); // Serialize content o.content = ed.serializer.serialize(o.node, {getInner : 1, forced_root_block : ''}); // Plain text option active? if ((!force_rich) && (ed.pasteAsPlainText)) { t._insertPlainText(o.content); if (!getParam(ed, "paste_text_sticky")) { ed.pasteAsPlainText = false; ed.controlManager.setActive("pastetext", false); } } else { t._insert(o.content); } } // Add command for external usage ed.addCommand('mceInsertClipboardContent', function(u, o) { process(o, true); }); if (!getParam(ed, "paste_text_use_dialog")) { ed.addCommand('mcePasteText', function(u, v) { var cookie = tinymce.util.Cookie; ed.pasteAsPlainText = !ed.pasteAsPlainText; ed.controlManager.setActive('pastetext', ed.pasteAsPlainText); if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) { if (getParam(ed, "paste_text_sticky")) { ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky')); } else { ed.windowManager.alert(ed.translate('paste.plaintext_mode')); } if (!getParam(ed, "paste_text_notifyalways")) { cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31)) } } }); } ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'}); ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'}); // This function grabs the contents from the clipboard by adding a // hidden div and placing the caret inside it and after the browser paste // is done it grabs that contents and processes that function grabContent(e) { var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent; // Check if browser supports direct plaintext access if (e.clipboardData || dom.doc.dataTransfer) { textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text'); if (ed.pasteAsPlainText) { e.preventDefault(); process({content : dom.encode(textContent).replace(/\r?\n/g, '<br />')}); return; } } if (dom.get('_mcePaste')) return; // Create container to paste into n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF'); // If contentEditable mode we need to find out the position of the closest element if (body != ed.getDoc().body) posY = dom.getPos(ed.selection.getStart(), body).y; else posY = body.scrollTop + dom.getViewPort(ed.getWin()).y; // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles // If also needs to be in view on IE or the paste would fail dom.setStyles(n, { position : 'absolute', left : tinymce.isGecko ? -40 : 0, // Need to move it out of site on Gecko since it will othewise display a ghost resize rect for the div top : posY - 25, width : 1, height : 1, overflow : 'hidden' }); if (tinymce.isIE) { // Store away the old range oldRng = sel.getRng(); // Select the container rng = dom.doc.body.createTextRange(); rng.moveToElementText(n); rng.execCommand('Paste'); // Remove container dom.remove(n); // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due // to IE security settings so we pass the junk though better than nothing right if (n.innerHTML === '\uFEFF\uFEFF') { ed.execCommand('mcePasteWord'); e.preventDefault(); return; } // Restore the old range and clear the contents before pasting sel.setRng(oldRng); sel.setContent(''); // For some odd reason we need to detach the the mceInsertContent call from the paste event // It's like IE has a reference to the parent element that you paste in and the selection gets messed up // when it tries to restore the selection setTimeout(function() { // Process contents process({content : n.innerHTML}); }, 0); // Block the real paste event return tinymce.dom.Event.cancel(e); } else { function block(e) { e.preventDefault(); }; // Block mousedown and click to prevent selection change dom.bind(ed.getDoc(), 'mousedown', block); dom.bind(ed.getDoc(), 'keydown', block); or = ed.selection.getRng(); // Move select contents inside DIV n = n.firstChild; rng = ed.getDoc().createRange(); rng.setStart(n, 0); rng.setEnd(n, 2); sel.setRng(rng); // Wait a while and grab the pasted contents window.setTimeout(function() { var h = '', nl; // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit if (!dom.select('div.mcePaste > div.mcePaste').length) { nl = dom.select('div.mcePaste'); // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string each(nl, function(n) { var child = n.firstChild; // WebKit inserts a DIV container with lots of odd styles if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) { dom.remove(child, 1); } // Remove apply style spans each(dom.select('span.Apple-style-span', n), function(n) { dom.remove(n, 1); }); // Remove bogus br elements each(dom.select('br[data-mce-bogus]', n), function(n) { dom.remove(n); }); // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV if (n.parentNode.className != 'mcePaste') h += n.innerHTML; }); } else { // Found WebKit weirdness so force the content into paragraphs this seems to happen when you paste plain text from Nodepad etc // So this logic will replace double enter with paragraphs and single enter with br so it kind of looks the same h = '<p>' + dom.encode(textContent).replace(/\r?\n\r?\n/g, '</p><p>').replace(/\r?\n/g, '<br />') + '</p>'; } // Remove the nodes each(dom.select('div.mcePaste'), function(n) { dom.remove(n); }); // Restore the old selection if (or) sel.setRng(or); process({content : h}); // Unblock events ones we got the contents dom.unbind(ed.getDoc(), 'mousedown', block); dom.unbind(ed.getDoc(), 'keydown', block); }, 0); } } // Check if we should use the new auto process method if (getParam(ed, "paste_auto_cleanup_on_paste")) { // Is it's Opera or older FF use key handler if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) { ed.onKeyDown.addToTop(function(ed, e) { if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) grabContent(e); }); } else { // Grab contents on paste event on Gecko and WebKit ed.onPaste.addToTop(function(ed, e) { return grabContent(e); }); } } ed.onInit.add(function() { ed.controlManager.setActive("pastetext", ed.pasteAsPlainText); // Block all drag/drop events if (getParam(ed, "paste_block_drop")) { ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) { e.preventDefault(); e.stopPropagation(); return false; }); } }); // Add legacy support t._legacySupport(); }, getInfo : function() { return { longname : 'Paste text/word', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _preProcess : function(pl, o) { var ed = this.editor, h = o.content, grep = tinymce.grep, explode = tinymce.explode, trim = tinymce.trim, len, stripClass; //console.log('Before preprocess:' + o.content); function process(items) { each(items, function(v) { // Remove or replace if (v.constructor == RegExp) h = h.replace(v, ''); else h = h.replace(v[0], v[1]); }); } if (ed.settings.paste_enable_default_filters == false) { return; } // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser if (tinymce.isIE && document.documentMode >= 9 && /<(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)/.test(o.content)) { // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser process([[/(?:<br>&nbsp;[\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]); // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break process([ [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s [/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR ]); } // Detect Word content and process it more aggressive if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) { o.wordContent = true; // Mark the pasted contents as word specific content //console.log('Word contents detected.'); // Process away some basic content process([ /^\s*(&nbsp;)+/gi, // &nbsp; entities at the start of contents /(&nbsp;|<br[^>]*>)+\s*$/gi // &nbsp; entities at the end of contents ]); if (getParam(ed, "paste_convert_headers_to_strong")) { h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>"); } if (getParam(ed, "paste_convert_middot_lists")) { process([ [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF) ]); } process([ // Word comments like conditional comments etc /<!--[\s\S]+?-->/gi, // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, // Convert <s> into <strike> for line-though [/<(\/?)s>/gi, "<$1strike>"], // Replace nsbp entites to char since it's easier to handle [/&nbsp;/gi, "\u00a0"] ]); // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag. // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot. do { len = h.length; h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1"); } while (len != h.length); // Remove all spans if no styles is to be retained if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) { h = h.replace(/<\/?span[^>]*>/gi, ""); } else { // We're keeping styles, so at least clean them up. // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx process([ // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function(str, spaces) { return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ""; } ], // Examine all styles: delete junk, transform some, and keep the rest [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi, function(str, tag, style) { var n = [], i = 0, s = explode(trim(style).replace(/&quot;/gi, "'"), ";"); // Examine each style definition within the tag's style attribute each(s, function(v) { var name, value, parts = explode(v, ":"); function ensureUnits(v) { return v + ((v !== "0") && (/\d$/.test(v)))? "px" : ""; } if (parts.length == 2) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); // Translate certain MS Office styles into their CSS equivalents switch (name) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value); return; case "horiz-align": n[i++] = "text-align:" + value; return; case "vert-align": n[i++] = "vertical-align:" + value; return; case "font-color": case "mso-foreground": n[i++] = "color:" + value; return; case "mso-background": case "mso-highlight": n[i++] = "background:" + value; return; case "mso-default-height": n[i++] = "min-height:" + ensureUnits(value); return; case "mso-default-width": n[i++] = "min-width:" + ensureUnits(value); return; case "mso-padding-between-alt": n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value); return; case "text-line-through": if ((value == "single") || (value == "double")) { n[i++] = "text-decoration:line-through"; } return; case "mso-zero-height": if (value == "yes") { n[i++] = "display:none"; } return; } // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) { return; } // If it reached this point, it must be a valid CSS style n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case } }); // If style attribute contained any valid styles the re-write it; otherwise delete style attribute. if (i > 0) { return tag + ' style="' + n.join(';') + '"'; } else { return tag; } } ] ]); } } // Replace headers with <strong> if (getParam(ed, "paste_convert_headers_to_strong")) { process([ [/<h[1-6][^>]*>/gi, "<p><strong>"], [/<\/h[1-6][^>]*>/gi, "</strong></p>"] ]); } process([ // Copy paste from Java like Open Office will produce this junk on FF [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, ''] ]); // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso"). // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation. stripClass = getParam(ed, "paste_strip_class_attributes"); if (stripClass !== "none") { function removeClasses(match, g1) { if (stripClass === "all") return ''; var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "), function(v) { return (/^(?!mso)/i.test(v)); } ); return cls.length ? ' class="' + cls.join(" ") + '"' : ''; }; h = h.replace(/ class="([^"]+)"/gi, removeClasses); h = h.replace(/ class=([\-\w]+)/gi, removeClasses); } // Remove spans option if (getParam(ed, "paste_remove_spans")) { h = h.replace(/<\/?span[^>]*>/gi, ""); } //console.log('After preprocess:' + h); o.content = h; }, /** * Various post process items. */ _postProcess : function(pl, o) { var t = this, ed = t.editor, dom = ed.dom, styleProps; if (ed.settings.paste_enable_default_filters == false) { return; } if (o.wordContent) { // Remove named anchors or TOC links each(dom.select('a', o.node), function(a) { if (!a.href || a.href.indexOf('#_Toc') != -1) dom.remove(a, 1); }); if (getParam(ed, "paste_convert_middot_lists")) { t._convertLists(pl, o); } // Process styles styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties // Process only if a string was specified and not equal to "all" or "*" if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) { styleProps = tinymce.explode(styleProps.replace(/^none$/i, "")); // Retains some style properties each(dom.select('*', o.node), function(el) { var newStyle = {}, npc = 0, i, sp, sv; // Store a subset of the existing styles if (styleProps) { for (i = 0; i < styleProps.length; i++) { sp = styleProps[i]; sv = dom.getStyle(el, sp); if (sv) { newStyle[sp] = sv; npc++; } } } // Remove all of the existing styles dom.setAttrib(el, 'style', ''); if (styleProps && npc > 0) dom.setStyles(el, newStyle); // Add back the stored subset of styles else // Remove empty span tags that do not have class attributes if (el.nodeName == 'SPAN' && !el.className) dom.remove(el, true); }); } } // Remove all style information or only specifically on WebKit to avoid the style bug on that browser if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) { each(dom.select('*[style]', o.node), function(el) { el.removeAttribute('style'); el.removeAttribute('data-mce-style'); }); } else { if (tinymce.isWebKit) { // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." /> // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles each(dom.select('*', o.node), function(el) { el.removeAttribute('data-mce-style'); }); } } }, /** * Converts the most common bullet and number formats in Office into a real semantic UL/LI list. */ _convertLists : function(pl, o) { var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html; // Convert middot lists into real semantic lists each(dom.select('p', o.node), function(p) { var sib, val = '', type, html, idx, parents; // Get text node value at beginning of paragraph for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling) val += sib.nodeValue; val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0'); // Detect unordered lists look for bullets if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val)) type = 'ul'; // Detect ordered lists 1., a. or ixv. if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val)) type = 'ol'; // Check if node value matches the list pattern: o&nbsp;&nbsp; if (type) { margin = parseFloat(p.style.marginLeft || 0); if (margin > lastMargin) levels.push(margin); if (!listElm || type != lastType) { listElm = dom.create(type); dom.insertAfter(listElm, p); } else { // Nested list element if (margin > lastMargin) { listElm = li.appendChild(dom.create(type)); } else if (margin < lastMargin) { // Find parent level based on margin value idx = tinymce.inArray(levels, margin); parents = dom.getParents(listElm.parentNode, type); listElm = parents[parents.length - 1 - idx] || listElm; } } // Remove middot or number spans if they exists each(dom.select('span', p), function(span) { var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, ''); // Remove span with the middot or the number if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html)) dom.remove(span); else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html)) dom.remove(span); }); html = p.innerHTML; // Remove middot/list items if (type == 'ul') html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, ''); else html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, ''); // Create li and add paragraph data into the new li li = listElm.appendChild(dom.create('li', 0, html)); dom.remove(p); lastMargin = margin; lastType = type; } else listElm = lastMargin = 0; // End list element }); // Remove any left over makers html = o.node.innerHTML; if (html.indexOf('__MCE_ITEM__') != -1) o.node.innerHTML = html.replace(/__MCE_ITEM__/g, ''); }, /** * Inserts the specified contents at the caret position. */ _insert : function(h, skip_undo) { var ed = this.editor, r = ed.selection.getRng(); // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells. if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer) ed.getDoc().execCommand('Delete', false, null); ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo}); }, /** * Instead of the old plain text method which tried to re-create a paste operation, the * new approach adds a plain text mode toggle switch that changes the behavior of paste. * This function is passed the same input that the regular paste plugin produces. * It performs additional scrubbing and produces (and inserts) the plain text. * This approach leverages all of the great existing functionality in the paste * plugin, and requires minimal changes to add the new functionality. * Speednet - June 2009 */ _insertPlainText : function(content) { var ed = this.editor, linebr = getParam(ed, "paste_text_linebreaktype"), rl = getParam(ed, "paste_text_replacements"), is = tinymce.is; function process(items) { each(items, function(v) { if (v.constructor == RegExp) content = content.replace(v, ""); else content = content.replace(v[0], v[1]); }); }; if ((typeof(content) === "string") && (content.length > 0)) { // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(content)) { process([ /[\n\r]+/g ]); } else { // Otherwise just get rid of carriage returns (only need linefeeds) process([ /\r+/g ]); } process([ [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"], // Block tags get a blank line after them [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags [/&nbsp;/gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*) [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"] // Cool little RegExp deletes whitespace around linebreak chars. ]); var maxLinebreaks = Number(getParam(ed, "paste_max_consecutive_linebreaks")); if (maxLinebreaks > -1) { var maxLinebreaksRegex = new RegExp("\n{" + (maxLinebreaks + 1) + ",}", "g"); var linebreakReplacement = ""; while (linebreakReplacement.length < maxLinebreaks) { linebreakReplacement += "\n"; } process([ [maxLinebreaksRegex, linebreakReplacement] // Limit max consecutive linebreaks ]); } content = ed.dom.decode(tinymce.html.Entities.encodeRaw(content)); // Perform default or custom replacements if (is(rl, "array")) { process(rl); } else if (is(rl, "string")) { process(new RegExp(rl, "gi")); } // Treat paragraphs as specified in the config if (linebr == "none") { // Convert all line breaks to space process([ [/\n+/g, " "] ]); } else if (linebr == "br") { // Convert all line breaks to <br /> process([ [/\n/g, "<br />"] ]); } else if (linebr == "p") { // Convert all line breaks to <p>...</p> process([ [/\n+/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'] ]); } else { // defaults to "combined" // Convert single line breaks to <br /> and double line breaks to <p>...</p> process([ [/\n\n/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'], [/\n/g, "<br />"] ]); } ed.execCommand('mceInsertContent', false, content); } }, /** * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine. */ _legacySupport : function() { var t = this, ed = t.editor; // Register command(s) for backwards compatibility ed.addCommand("mcePasteWord", function() { ed.windowManager.open({ file: t.url + "/pasteword.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline: 1 }); }); if (getParam(ed, "paste_text_use_dialog")) { ed.addCommand("mcePasteText", function() { ed.windowManager.open({ file : t.url + "/pastetext.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline : 1 }); }); } // Register button for backwards compatibility ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"}); } }); // Register plugin tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin); })();
JavaScript
(function() { tinymce.create('tinymce.plugins.wpLink', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished its initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var disabled = true; // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('WP_Link', function() { if ( disabled ) return; ed.windowManager.open({ id : 'wp-link', width : 480, height : "auto", wpDialog : true, title : ed.getLang('advlink.link_desc') }, { plugin_url : url // Plugin absolute URL }); }); // Register example button ed.addButton('link', { title : 'advanced.link_desc', cmd : 'WP_Link' }); ed.onNodeChange.add(function(ed, cm, n, co) { disabled = co && n.nodeName != 'A'; }); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'WordPress Link Dialog', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('wplink', tinymce.plugins.wpLink); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, explode = tinymce.explode; tinymce.create('tinymce.plugins.TabFocusPlugin', { init : function(ed, url) { function tabCancel(ed, e) { if (e.keyCode === 9) return Event.cancel(e); } function tabHandler(ed, e) { var x, i, f, el, v; function find(d) { el = DOM.select(':input:enabled,*[tabindex]:not(iframe)'); function canSelectRecursive(e) { return e.nodeName==="BODY" || (e.type != 'hidden' && !(e.style.display == "none") && !(e.style.visibility == "hidden") && canSelectRecursive(e.parentNode)); } function canSelectInOldIe(el) { return el.attributes["tabIndex"].specified || el.nodeName == "INPUT" || el.nodeName == "TEXTAREA"; } function isOldIe() { return tinymce.isIE6 || tinymce.isIE7; } function canSelect(el) { return ((!isOldIe() || canSelectInOldIe(el))) && el.getAttribute("tabindex") != '-1' && canSelectRecursive(el); } each(el, function(e, i) { if (e.id == ed.id) { x = i; return false; } }); if (d > 0) { for (i = x + 1; i < el.length; i++) { if (canSelect(el[i])) return el[i]; } } else { for (i = x - 1; i >= 0; i--) { if (canSelect(el[i])) return el[i]; } } return null; } if (e.keyCode === 9) { v = explode(ed.getParam('tab_focus', ed.getParam('tabfocus_elements', ':prev,:next'))); if (v.length == 1) { v[1] = v[0]; v[0] = ':prev'; } // Find element to focus if (e.shiftKey) { if (v[0] == ':prev') el = find(-1); else el = DOM.get(v[0]); } else { if (v[1] == ':next') el = find(1); else el = DOM.get(v[1]); } if (el) { if (el.id && (ed = tinymce.get(el.id || el.name))) ed.focus(); else window.setTimeout(function() { if (!tinymce.isWebKit) window.focus(); el.focus(); }, 10); return Event.cancel(e); } } } ed.onKeyUp.add(tabCancel); if (tinymce.isGecko) { ed.onKeyPress.add(tabHandler); ed.onKeyDown.add(tabCancel); } else ed.onKeyDown.add(tabHandler); }, getInfo : function() { return { longname : 'Tabfocus', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('tabfocus', tinymce.plugins.TabFocusPlugin); })();
JavaScript
/** * WordPress plugin. */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.WordPress', { init : function(ed, url) { var t = this, tbId = ed.getParam('wordpress_adv_toolbar', 'toolbar2'), last = 0, moreHTML, nextpageHTML, closeOnClick, mod_key, style; moreHTML = '<img src="' + url + '/img/trans.gif" class="mce-wp-more mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mce-wp-nextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; if ( getUserSetting('hidetb', '0') == '1' ) ed.settings.wordpress_adv_hidden = 0; // Hides the specified toolbar and resizes the iframe ed.onPostRender.add(function() { var adv_toolbar = ed.controlManager.get(tbId); if ( ed.getParam('wordpress_adv_hidden', 1) && adv_toolbar ) { DOM.hide(adv_toolbar.id); t._resizeIframe(ed, tbId, 28); } }); // Register commands ed.addCommand('WP_More', function() { ed.execCommand('mceInsertContent', 0, moreHTML); }); ed.addCommand('WP_Page', function() { ed.execCommand('mceInsertContent', 0, nextpageHTML); }); ed.addCommand('WP_Help', function() { ed.windowManager.open({ url : tinymce.baseURL + '/wp-mce-help.php', width : 450, height : 420, inline : 1 }); }); ed.addCommand('WP_Adv', function() { var cm = ed.controlManager, id = cm.get(tbId).id; if ( 'undefined' == id ) return; if ( DOM.isHidden(id) ) { cm.setActive('wp_adv', 1); DOM.show(id); t._resizeIframe(ed, tbId, -28); ed.settings.wordpress_adv_hidden = 0; setUserSetting('hidetb', '1'); } else { cm.setActive('wp_adv', 0); DOM.hide(id); t._resizeIframe(ed, tbId, 28); ed.settings.wordpress_adv_hidden = 1; setUserSetting('hidetb', '0'); } }); ed.addCommand('WP_Medialib', function() { if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) wp.media.editor.open( ed.id ); }); // Register buttons ed.addButton('wp_more', { title : 'wordpress.wp_more_desc', cmd : 'WP_More' }); ed.addButton('wp_page', { title : 'wordpress.wp_page_desc', image : url + '/img/page.gif', cmd : 'WP_Page' }); ed.addButton('wp_help', { title : 'wordpress.wp_help_desc', cmd : 'WP_Help' }); ed.addButton('wp_adv', { title : 'wordpress.wp_adv_desc', cmd : 'WP_Adv' }); // Add Media button ed.addButton('add_media', { title : 'wordpress.add_media', image : url + '/img/image.gif', cmd : 'WP_Medialib' }); // Add Media buttons to fullscreen and handle align buttons for image captions ed.onBeforeExecCommand.add(function(ed, cmd, ui, val, o) { var DOM = tinymce.DOM, n, DL, DIV, cls, a, align; if ( 'mceFullScreen' == cmd ) { if ( 'mce_fullscreen' != ed.id && DOM.select('a.thickbox').length ) ed.settings.theme_advanced_buttons1 += ',|,add_media'; } if ( 'JustifyLeft' == cmd || 'JustifyRight' == cmd || 'JustifyCenter' == cmd ) { n = ed.selection.getNode(); if ( n.nodeName == 'IMG' ) { align = cmd.substr(7).toLowerCase(); a = 'align' + align; DL = ed.dom.getParent(n, 'dl.wp-caption'); DIV = ed.dom.getParent(n, 'div.mceTemp'); if ( DL && DIV ) { cls = ed.dom.hasClass(DL, a) ? 'alignnone' : a; DL.className = DL.className.replace(/align[^ '"]+\s?/g, ''); ed.dom.addClass(DL, cls); if (cls == 'aligncenter') ed.dom.addClass(DIV, 'mceIEcenter'); else ed.dom.removeClass(DIV, 'mceIEcenter'); o.terminate = true; ed.execCommand('mceRepaint'); } else { if ( ed.dom.hasClass(n, a) ) ed.dom.addClass(n, 'alignnone'); else ed.dom.removeClass(n, 'alignnone'); } } } if ( tinymce.isWebKit && ( 'InsertUnorderedList' == cmd || 'InsertOrderedList' == cmd ) ) { if ( !style ) style = ed.dom.create('style', {'type': 'text/css'}, '#tinymce,#tinymce span,#tinymce li,#tinymce li>span,#tinymce p,#tinymce p>span{font:medium sans-serif;color:#000;line-height:normal;}'); ed.getDoc().head.appendChild( style ); } }); ed.onExecCommand.add( function( ed, cmd, ui, val ) { if ( tinymce.isWebKit && style && ( 'InsertUnorderedList' == cmd || 'InsertOrderedList' == cmd ) ) ed.dom.remove( style ); }); ed.onInit.add(function(ed) { var bodyClass = ed.getParam('body_class', ''), body = ed.getBody(); // add body classes if ( bodyClass ) bodyClass = bodyClass.split(' '); else bodyClass = []; if ( ed.getParam('directionality', '') == 'rtl' ) bodyClass.push('rtl'); if ( tinymce.isIE9 ) bodyClass.push('ie9'); else if ( tinymce.isIE8 ) bodyClass.push('ie8'); else if ( tinymce.isIE7 ) bodyClass.push('ie7'); if ( ed.id != 'wp_mce_fullscreen' && ed.id != 'mce_fullscreen' ) bodyClass.push('wp-editor'); else if ( ed.id == 'mce_fullscreen' ) bodyClass.push('mce-fullscreen'); tinymce.each( bodyClass, function(cls){ if ( cls ) ed.dom.addClass(body, cls); }); // make sure these run last ed.onNodeChange.add( function(ed, cm, e) { var DL; if ( e.nodeName == 'IMG' ) { DL = ed.dom.getParent(e, 'dl.wp-caption'); } else if ( e.nodeName == 'DIV' && ed.dom.hasClass(e, 'mceTemp') ) { DL = e.firstChild; if ( ! ed.dom.hasClass(DL, 'wp-caption') ) DL = false; } if ( DL ) { if ( ed.dom.hasClass(DL, 'alignleft') ) cm.setActive('justifyleft', 1); else if ( ed.dom.hasClass(DL, 'alignright') ) cm.setActive('justifyright', 1); else if ( ed.dom.hasClass(DL, 'aligncenter') ) cm.setActive('justifycenter', 1); } }); // remove invalid parent paragraphs when pasting HTML and/or switching to the HTML editor and back ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)( [^>]*)?>/gi, '<$1$2>'); o.content = o.content.replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)>\s*<\/p>/gi, '</$1>'); } }); }); // Word count if ( 'undefined' != typeof(jQuery) ) { ed.onKeyUp.add(function(ed, e) { var k = e.keyCode || e.charCode; if ( k == last ) return; if ( 13 == k || 8 == last || 46 == last ) jQuery(document).triggerHandler('wpcountwords', [ ed.getContent({format : 'raw'}) ]); last = k; }); }; // keep empty paragraphs :( ed.onSaveContent.addToTop(function(ed, o) { o.content = o.content.replace(/<p>(<br ?\/?>|\u00a0|\uFEFF)?<\/p>/g, '<p>&nbsp;</p>'); }); // Fix bug in iOS Safari where it's impossible to type after a touchstart event on the parent document. // Happens after zooming in or out while the keyboard is open. See #25131. if ( tinymce.isIOS5 ) { ed.onKeyDown.add( function() { if ( document.activeElement == document.body ) { ed.getWin().focus(); } }); } ed.onSaveContent.add(function(ed, o) { // If editor is hidden, we just want the textarea's value to be saved if ( ed.isHidden() ) o.content = o.element.value; else if ( ed.getParam('wpautop', true) && typeof(switchEditors) == 'object' ) o.content = switchEditors.pre_wpautop(o.content); }); /* disable for now ed.onBeforeSetContent.add(function(ed, o) { o.content = t._setEmbed(o.content); }); ed.onPostProcess.add(function(ed, o) { if ( o.get ) o.content = t._getEmbed(o.content); }); */ // Add listeners to handle more break t._handleMoreBreak(ed, url); // Add custom shortcuts mod_key = 'alt+shift'; // if ( tinymce.isGecko ) // disable for mow, too many shortcuts conflicts // mod_key = 'ctrl+alt'; ed.addShortcut(mod_key + '+c', 'justifycenter_desc', 'JustifyCenter'); ed.addShortcut(mod_key + '+r', 'justifyright_desc', 'JustifyRight'); ed.addShortcut(mod_key + '+l', 'justifyleft_desc', 'JustifyLeft'); ed.addShortcut(mod_key + '+j', 'justifyfull_desc', 'JustifyFull'); ed.addShortcut(mod_key + '+q', 'blockquote_desc', 'mceBlockQuote'); ed.addShortcut(mod_key + '+u', 'bullist_desc', 'InsertUnorderedList'); ed.addShortcut(mod_key + '+o', 'numlist_desc', 'InsertOrderedList'); ed.addShortcut(mod_key + '+n', 'spellchecker.desc', 'mceSpellCheck'); ed.addShortcut(mod_key + '+a', 'link_desc', 'WP_Link'); ed.addShortcut(mod_key + '+s', 'unlink_desc', 'unlink'); ed.addShortcut(mod_key + '+m', 'image_desc', 'WP_Medialib'); ed.addShortcut(mod_key + '+z', 'wordpress.wp_adv_desc', 'WP_Adv'); ed.addShortcut(mod_key + '+t', 'wordpress.wp_more_desc', 'WP_More'); ed.addShortcut(mod_key + '+d', 'striketrough_desc', 'Strikethrough'); ed.addShortcut(mod_key + '+h', 'help_desc', 'WP_Help'); ed.addShortcut(mod_key + '+p', 'wordpress.wp_page_desc', 'WP_Page'); ed.addShortcut('ctrl+s', 'save_desc', function(){if('function'==typeof autosave)autosave();}); if ( /\bwpfullscreen\b/.test(ed.settings.plugins) ) ed.addShortcut(mod_key + '+w', 'wordpress.wp_fullscreen_desc', 'wpFullScreen'); else if ( /\bfullscreen\b/.test(ed.settings.plugins) ) ed.addShortcut(mod_key + '+g', 'fullscreen.desc', 'mceFullScreen'); // popup buttons for images and the gallery ed.onInit.add(function(ed) { tinymce.dom.Event.add(ed.getWin(), 'scroll', function(e) { ed.plugins.wordpress._hideButtons(); }); tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) { ed.plugins.wordpress._hideButtons(); }); }); ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { ed.plugins.wordpress._hideButtons(); }); ed.onSaveContent.add(function(ed, o) { ed.plugins.wordpress._hideButtons(); }); ed.onMouseDown.add(function(ed, e) { if ( e.target.nodeName != 'IMG' ) ed.plugins.wordpress._hideButtons(); }); ed.onKeyDown.add(function(ed, e){ if ( e.which == tinymce.VK.DELETE || e.which == tinymce.VK.BACKSPACE ) ed.plugins.wordpress._hideButtons(); }); closeOnClick = function(e){ var id; if ( e.target.id == 'mceModalBlocker' || e.target.className == 'ui-widget-overlay' ) { for ( id in ed.windowManager.windows ) { ed.windowManager.close(null, id); } } } // close popups when clicking on the background tinymce.dom.Event.remove(document.body, 'click', closeOnClick); tinymce.dom.Event.add(document.body, 'click', closeOnClick); }, getInfo : function() { return { longname : 'WordPress Plugin', author : 'WordPress', // add Moxiecode? authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '3.0' }; }, // Internal functions _setEmbed : function(c) { return c.replace(/\[embed\]([\s\S]+?)\[\/embed\][\s\u00a0]*/g, function(a,b){ return '<img width="300" height="200" src="' + tinymce.baseURL + '/plugins/wordpress/img/trans.gif" class="wp-oembed mceItemNoResize" alt="'+b+'" title="'+b+'" />'; }); }, _getEmbed : function(c) { return c.replace(/<img[^>]+>/g, function(a) { if ( a.indexOf('class="wp-oembed') != -1 ) { var u = a.match(/alt="([^\"]+)"/); if ( u[1] ) a = '[embed]' + u[1] + '[/embed]'; } return a; }); }, _showButtons : function(n, id) { var ed = tinyMCE.activeEditor, p1, p2, vp, DOM = tinymce.DOM, X, Y; vp = ed.dom.getViewPort(ed.getWin()); p1 = DOM.getPos(ed.getContentAreaContainer()); p2 = ed.dom.getPos(n); X = Math.max(p2.x - vp.x, 0) + p1.x; Y = Math.max(p2.y - vp.y, 0) + p1.y; DOM.setStyles(id, { 'top' : Y+5+'px', 'left' : X+5+'px', 'display' : 'block' }); }, _hideButtons : function() { var DOM = tinymce.DOM; DOM.hide( DOM.select('#wp_editbtns, #wp_gallerybtns') ); }, // Resizes the iframe by a relative height value _resizeIframe : function(ed, tb_id, dy) { var ifr = ed.getContentAreaContainer().firstChild; DOM.setStyle(ifr, 'height', ifr.clientHeight + dy); // Resize iframe ed.theme.deltaHeight += dy; // For resize cookie }, _handleMoreBreak : function(ed, url) { var moreHTML, nextpageHTML; moreHTML = '<img src="' + url + '/img/trans.gif" alt="$1" class="mce-wp-more mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mce-wp-nextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; // Display morebreak instead if img in element path ed.onPostRender.add(function() { if (ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.node.nodeName == 'IMG') { if ( ed.dom.hasClass(o.node, 'mce-wp-more') ) o.name = 'wpmore'; if ( ed.dom.hasClass(o.node, 'mce-wp-nextpage') ) o.name = 'wppage'; } }); } }); // Replace morebreak with images ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<!--more(.*?)-->/g, moreHTML); o.content = o.content.replace(/<!--nextpage-->/g, nextpageHTML); } }); // Replace images with morebreak ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = o.content.replace(/<img[^>]+>/g, function(im) { if (im.indexOf('class="mce-wp-more') !== -1) { var m, moretext = (m = im.match(/alt="(.*?)"/)) ? m[1] : ''; im = '<!--more'+moretext+'-->'; } if (im.indexOf('class="mce-wp-nextpage') !== -1) im = '<!--nextpage-->'; return im; }); }); // Set active buttons if user selected pagebreak or more break ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('wp_page', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mce-wp-nextpage')); cm.setActive('wp_more', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mce-wp-more')); }); } }); // Register plugin tinymce.PluginManager.add('wordpress', tinymce.plugins.WordPress); })();
JavaScript
/** * WordPress View plugin. */ (function() { var VK = tinymce.VK, TreeWalker = tinymce.dom.TreeWalker, selected; tinymce.create('tinymce.plugins.wpView', { init : function( editor, url ) { var wpView = this; // Check if the `wp.mce` API exists. if ( typeof wp === 'undefined' || ! wp.mce ) return; editor.onPreInit.add( function( editor ) { // Add elements so we can set `contenteditable` to false. editor.schema.addValidElements('div[*],span[*]'); }); // When the editor's content changes, scan the new content for // matching view patterns, and transform the matches into // view wrappers. Since the editor's DOM is outdated at this point, // we'll wait to render the views. editor.onBeforeSetContent.add( function( editor, o ) { if ( ! o.content ) return; o.content = wp.mce.view.toViews( o.content ); }); // When the editor's content has been updated and the DOM has been // processed, render the views in the document. editor.onSetContent.add( function( editor, o ) { wp.mce.view.render( editor.getDoc() ); }); editor.onInit.add( function( editor ) { // When a view is selected, ensure content that is being pasted // or inserted is added to a text node (instead of the view). editor.selection.onBeforeSetContent.add( function( selection, o ) { var view = wpView.getParentView( selection.getNode() ), walker, target; // If the selection is not within a view, bail. if ( ! view ) return; // If there are no additional nodes or the next node is a // view, create a text node after the current view. if ( ! view.nextSibling || wpView.isView( view.nextSibling ) ) { target = editor.getDoc().createTextNode(''); editor.dom.insertAfter( target, view ); // Otherwise, find the next text node. } else { walker = new TreeWalker( view.nextSibling, view.nextSibling ); target = walker.next(); } // Select the `target` text node. selection.select( target ); selection.collapse( true ); }); // When the selection's content changes, scan any new content // for matching views and immediately render them. // // Runs on paste and on inserting nodes/html. editor.selection.onSetContent.add( function( selection, o ) { if ( ! o.context ) return; var node = selection.getNode(); if ( ! node.innerHTML ) return; node.innerHTML = wp.mce.view.toViews( node.innerHTML ); wp.mce.view.render( node ); }); }); // When the editor's contents are being accessed as a string, // transform any views back to their text representations. editor.onPostProcess.add( function( editor, o ) { if ( ( ! o.get && ! o.save ) || ! o.content ) return; o.content = wp.mce.view.toText( o.content ); }); // Triggers when the selection is changed. // Add the event handler to the top of the stack. editor.onNodeChange.addToTop( function( editor, controlManager, node, collapsed, o ) { var view = wpView.getParentView( node ); // Update the selected view. if ( view ) { wpView.select( view ); // Prevent the selection from propagating to other plugins. return false; // If we've clicked off of the selected view, deselect it. } else { wpView.deselect(); } }); editor.onKeyDown.addToTop( function( editor, event ) { var keyCode = event.keyCode, view, instance; // If a view isn't selected, let the event go on its merry way. if ( ! selected ) return; // If the caret is not within the selected view, deselect the // view and bail. view = wpView.getParentView( editor.selection.getNode() ); if ( view !== selected ) { wpView.deselect(); return; } // If delete or backspace is pressed, delete the view. if ( keyCode === VK.DELETE || keyCode === VK.BACKSPACE ) { if ( (instance = wp.mce.view.instance( selected )) ) { instance.remove(); wpView.deselect(); } } // Let keypresses that involve the command or control keys through. // Also, let any of the F# keys through. if ( event.metaKey || event.ctrlKey || ( keyCode >= 112 && keyCode <= 123 ) ) return; event.preventDefault(); }); }, getParentView : function( node ) { while ( node ) { if ( this.isView( node ) ) return node; node = node.parentNode; } }, isView : function( node ) { return (/(?:^|\s)wp-view-wrap(?:\s|$)/).test( node.className ); }, select : function( view ) { if ( view === selected ) return; this.deselect(); selected = view; wp.mce.view.select( selected ); }, deselect : function() { if ( selected ) wp.mce.view.deselect( selected ); selected = null; }, getInfo : function() { return { longname : 'WordPress Views', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '1.0' }; } }); // Register plugin tinymce.PluginManager.add( 'wpview', tinymce.plugins.wpView ); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Directionality', { init : function(ed, url) { var t = this; t.editor = ed; function setDir(dir) { var dom = ed.dom, curDir, blocks = ed.selection.getSelectedBlocks(); if (blocks.length) { curDir = dom.getAttrib(blocks[0], "dir"); tinymce.each(blocks, function(block) { // Add dir to block if the parent block doesn't already have that dir if (!dom.getParent(block.parentNode, "*[dir='" + dir + "']", dom.getRoot())) { if (curDir != dir) { dom.setAttrib(block, "dir", dir); } else { dom.setAttrib(block, "dir", null); } } }); ed.nodeChanged(); } } ed.addCommand('mceDirectionLTR', function() { setDir("ltr"); }); ed.addCommand('mceDirectionRTL', function() { setDir("rtl"); }); ed.addButton('ltr', {title : 'directionality.ltr_desc', cmd : 'mceDirectionLTR'}); ed.addButton('rtl', {title : 'directionality.rtl_desc', cmd : 'mceDirectionRTL'}); ed.onNodeChange.add(t._nodeChange, t); }, getInfo : function() { return { longname : 'Directionality', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/directionality', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var dom = ed.dom, dir; n = dom.getParent(n, dom.isBlock); if (!n) { cm.setDisabled('ltr', 1); cm.setDisabled('rtl', 1); return; } dir = dom.getAttrib(n, 'dir'); cm.setActive('ltr', dir == "ltr"); cm.setDisabled('ltr', 0); cm.setActive('rtl', dir == "rtl"); cm.setDisabled('rtl', 0); } }); // Register plugin tinymce.PluginManager.add('directionality', tinymce.plugins.Directionality); })();
JavaScript
tinyMCEPopup.requireLangPack(); function init() { var ed, tcont; tinyMCEPopup.resizeToInnerSize(); ed = tinyMCEPopup.editor; // Give FF some time window.setTimeout(insertHelpIFrame, 10); tcont = document.getElementById('plugintablecontainer'); document.getElementById('plugins_tab').style.display = 'none'; var html = ""; html += '<table id="plugintable">'; html += '<thead>'; html += '<tr>'; html += '<td>' + ed.getLang('advanced_dlg.about_plugin') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_author') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_version') + '</td>'; html += '</tr>'; html += '</thead>'; html += '<tbody>'; tinymce.each(ed.plugins, function(p, n) { var info; if (!p.getInfo) return; html += '<tr>'; info = p.getInfo(); if (info.infourl != null && info.infourl != '') html += '<td width="50%" title="' + n + '"><a href="' + info.infourl + '" target="_blank">' + info.longname + '</a></td>'; else html += '<td width="50%" title="' + n + '">' + info.longname + '</td>'; if (info.authorurl != null && info.authorurl != '') html += '<td width="35%"><a href="' + info.authorurl + '" target="_blank">' + info.author + '</a></td>'; else html += '<td width="35%">' + info.author + '</td>'; html += '<td width="15%">' + info.version + '</td>'; html += '</tr>'; document.getElementById('plugins_tab').style.display = ''; }); html += '</tbody>'; html += '</table>'; tcont.innerHTML = html; tinyMCEPopup.dom.get('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion; tinyMCEPopup.dom.get('date').innerHTML = tinymce.releaseDate; } function insertHelpIFrame() { var html; if (tinyMCEPopup.getParam('docs_url')) { html = '<iframe width="100%" height="300" src="' + tinyMCEPopup.editor.baseURI.toAbsolute(tinyMCEPopup.getParam('docs_url')) + '"></iframe>'; document.getElementById('iframecontainer').innerHTML = html; document.getElementById('help_tab').style.display = 'block'; document.getElementById('help_tab').setAttribute("aria-hidden", "false"); } } tinyMCEPopup.onInit.add(init);
JavaScript
tinyMCEPopup.requireLangPack(); var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false; var colors = [ "#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033", "#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099", "#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff", "#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033", "#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399", "#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff", "#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333", "#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399", "#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff", "#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633", "#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699", "#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff", "#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633", "#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999", "#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff", "#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933", "#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999", "#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff", "#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33", "#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99", "#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff", "#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33", "#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99", "#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff", "#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33", "#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99", "#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff" ]; var named = { '#F0F8FF':'Alice Blue','#FAEBD7':'Antique White','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige', '#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'Blanched Almond','#0000FF':'Blue','#8A2BE2':'Blue Violet','#A52A2A':'Brown', '#DEB887':'Burly Wood','#5F9EA0':'Cadet Blue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'Cornflower Blue', '#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'Dark Blue','#008B8B':'Dark Cyan','#B8860B':'Dark Golden Rod', '#A9A9A9':'Dark Gray','#A9A9A9':'Dark Grey','#006400':'Dark Green','#BDB76B':'Dark Khaki','#8B008B':'Dark Magenta','#556B2F':'Dark Olive Green', '#FF8C00':'Darkorange','#9932CC':'Dark Orchid','#8B0000':'Dark Red','#E9967A':'Dark Salmon','#8FBC8F':'Dark Sea Green','#483D8B':'Dark Slate Blue', '#2F4F4F':'Dark Slate Gray','#2F4F4F':'Dark Slate Grey','#00CED1':'Dark Turquoise','#9400D3':'Dark Violet','#FF1493':'Deep Pink','#00BFFF':'Deep Sky Blue', '#696969':'Dim Gray','#696969':'Dim Grey','#1E90FF':'Dodger Blue','#B22222':'Fire Brick','#FFFAF0':'Floral White','#228B22':'Forest Green', '#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'Ghost White','#FFD700':'Gold','#DAA520':'Golden Rod','#808080':'Gray','#808080':'Grey', '#008000':'Green','#ADFF2F':'Green Yellow','#F0FFF0':'Honey Dew','#FF69B4':'Hot Pink','#CD5C5C':'Indian Red','#4B0082':'Indigo','#FFFFF0':'Ivory', '#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'Lavender Blush','#7CFC00':'Lawn Green','#FFFACD':'Lemon Chiffon','#ADD8E6':'Light Blue', '#F08080':'Light Coral','#E0FFFF':'Light Cyan','#FAFAD2':'Light Golden Rod Yellow','#D3D3D3':'Light Gray','#D3D3D3':'Light Grey','#90EE90':'Light Green', '#FFB6C1':'Light Pink','#FFA07A':'Light Salmon','#20B2AA':'Light Sea Green','#87CEFA':'Light Sky Blue','#778899':'Light Slate Gray','#778899':'Light Slate Grey', '#B0C4DE':'Light Steel Blue','#FFFFE0':'Light Yellow','#00FF00':'Lime','#32CD32':'Lime Green','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon', '#66CDAA':'Medium Aqua Marine','#0000CD':'Medium Blue','#BA55D3':'Medium Orchid','#9370D8':'Medium Purple','#3CB371':'Medium Sea Green','#7B68EE':'Medium Slate Blue', '#00FA9A':'Medium Spring Green','#48D1CC':'Medium Turquoise','#C71585':'Medium Violet Red','#191970':'Midnight Blue','#F5FFFA':'Mint Cream','#FFE4E1':'Misty Rose','#FFE4B5':'Moccasin', '#FFDEAD':'Navajo White','#000080':'Navy','#FDF5E6':'Old Lace','#808000':'Olive','#6B8E23':'Olive Drab','#FFA500':'Orange','#FF4500':'Orange Red','#DA70D6':'Orchid', '#EEE8AA':'Pale Golden Rod','#98FB98':'Pale Green','#AFEEEE':'Pale Turquoise','#D87093':'Pale Violet Red','#FFEFD5':'Papaya Whip','#FFDAB9':'Peach Puff', '#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'Powder Blue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'Rosy Brown','#4169E1':'Royal Blue', '#8B4513':'Saddle Brown','#FA8072':'Salmon','#F4A460':'Sandy Brown','#2E8B57':'Sea Green','#FFF5EE':'Sea Shell','#A0522D':'Sienna','#C0C0C0':'Silver', '#87CEEB':'Sky Blue','#6A5ACD':'Slate Blue','#708090':'Slate Gray','#708090':'Slate Grey','#FFFAFA':'Snow','#00FF7F':'Spring Green', '#4682B4':'Steel Blue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet', '#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'White Smoke','#FFFF00':'Yellow','#9ACD32':'Yellow Green' }; var namedLookup = {}; function init() { var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color')), key, value; tinyMCEPopup.resizeToInnerSize(); generatePicker(); generateWebColors(); generateNamedColors(); if (inputColor) { changeFinalColor(inputColor); col = convertHexToRGB(inputColor); if (col) updateLight(col.r, col.g, col.b); } for (key in named) { value = named[key]; namedLookup[value.replace(/\s+/, '').toLowerCase()] = key.replace(/#/, '').toLowerCase(); } } function toHexColor(color) { var matches, red, green, blue, toInt = parseInt; function hex(value) { value = parseInt(value).toString(16); return value.length > 1 ? value : '0' + value; // Padd with leading zero }; color = tinymce.trim(color); color = color.replace(/^[#]/, '').toLowerCase(); // remove leading '#' color = namedLookup[color] || color; matches = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/.exec(color); if (matches) { red = toInt(matches[1]); green = toInt(matches[2]); blue = toInt(matches[3]); } else { matches = /^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(color); if (matches) { red = toInt(matches[1], 16); green = toInt(matches[2], 16); blue = toInt(matches[3], 16); } else { matches = /^([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color); if (matches) { red = toInt(matches[1] + matches[1], 16); green = toInt(matches[2] + matches[2], 16); blue = toInt(matches[3] + matches[3], 16); } else { return ''; } } } return '#' + hex(red) + hex(green) + hex(blue); } function insertAction() { var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func'); var hexColor = toHexColor(color); if (hexColor === '') { var text = tinyMCEPopup.editor.getLang('advanced_dlg.invalid_color_value'); tinyMCEPopup.alert(text + ': ' + color); } else { tinyMCEPopup.restoreSelection(); if (f) f(hexColor); tinyMCEPopup.close(); } } function showColor(color, name) { if (name) document.getElementById("colorname").innerHTML = name; document.getElementById("preview").style.backgroundColor = color; document.getElementById("color").value = color.toUpperCase(); } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); if (!col) return col; var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return {r : r, g : g, b : b}; } return null; } function generatePicker() { var el = document.getElementById('light'), h = '', i; for (i = 0; i < detail; i++){ h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"' + ' onclick="changeFinalColor(this.style.backgroundColor)"' + ' onmousedown="isMouseDown = true; return false;"' + ' onmouseup="isMouseDown = false;"' + ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"' + ' onmouseover="isMouseOver = true;"' + ' onmouseout="isMouseOver = false;"' + '></div>'; } el.innerHTML = h; } function generateWebColors() { var el = document.getElementById('webcolors'), h = '', i; if (el.className == 'generated') return; // TODO: VoiceOver doesn't seem to support legend as a label referenced by labelledby. h += '<div role="listbox" aria-labelledby="webcolors_title" tabindex="0"><table role="presentation" border="0" cellspacing="1" cellpadding="0">' + '<tr>'; for (i=0; i<colors.length; i++) { h += '<td bgcolor="' + colors[i] + '" width="10" height="10">' + '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="web_colors_' + i + '" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="web_colors_' + i + '">' + colors[i].toUpperCase() + '</span>'; h += '</a></td>'; if ((i+1) % 18 == 0) h += '</tr><tr>'; } h += '</table></div>'; el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el.firstChild); } function paintCanvas(el) { tinyMCEPopup.getWin().tinymce.each(tinyMCEPopup.dom.select('canvas.mceColorSwatch', el), function(canvas) { var context; if (canvas.getContext && (context = canvas.getContext("2d"))) { context.fillStyle = canvas.getAttribute('data-color'); context.fillRect(0, 0, 10, 10); } }); } function generateNamedColors() { var el = document.getElementById('namedcolors'), h = '', n, v, i = 0; if (el.className == 'generated') return; for (n in named) { v = named[n]; h += '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="named_colors_' + i + '" onfocus="showColor(\'' + n + '\',\'' + v + '\');" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="named_colors_' + i + '">' + v + '</span>'; h += '</a>'; i++; } el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el); } function enableKeyboardNavigation(el) { tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: el, items: tinyMCEPopup.dom.select('a', el) }, tinyMCEPopup.dom); } function dechex(n) { return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16); } function computeColor(e) { var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB, pos = tinyMCEPopup.dom.getPos(e.target); x = e.offsetX ? e.offsetX : (e.target ? e.clientX - pos.x : 0); y = e.offsetY ? e.offsetY : (e.target ? e.clientY - pos.y : 0); partWidth = document.getElementById('colors').width / 6; partDetail = detail / 2; imHeight = document.getElementById('colors').height; r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255; g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth); b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth); coef = (imHeight - y) / imHeight; r = 128 + (r - 128) * coef; g = 128 + (g - 128) * coef; b = 128 + (b - 128) * coef; changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b)); updateLight(r, g, b); } function updateLight(r, g, b) { var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color; for (i=0; i<detail; i++) { if ((i>=0) && (i<partDetail)) { finalCoef = i / partDetail; finalR = dechex(255 - (255 - r) * finalCoef); finalG = dechex(255 - (255 - g) * finalCoef); finalB = dechex(255 - (255 - b) * finalCoef); } else { finalCoef = 2 - i / partDetail; finalR = dechex(r * finalCoef); finalG = dechex(g * finalCoef); finalB = dechex(b * finalCoef); } color = finalR + finalG + finalB; setCol('gs' + i, '#'+color); } } function changeFinalColor(color) { if (color.indexOf('#') == -1) color = convertRGBToHex(color); setCol('preview', color); document.getElementById('color').value = color; } function setCol(e, c) { try { document.getElementById(e).style.backgroundColor = c; } catch (ex) { // Ignore IE warning } } tinyMCEPopup.onInit.add(init);
JavaScript
tinyMCEPopup.requireLangPack(); var AnchorDialog = { init : function(ed) { var action, elm, f = document.forms[0]; this.editor = ed; elm = ed.dom.getParent(ed.selection.getNode(), 'A'); v = ed.dom.getAttrib(elm, 'name') || ed.dom.getAttrib(elm, 'id'); if (v) { this.action = 'update'; f.anchorName.value = v; } f.insert.value = ed.getLang(elm ? 'update' : 'insert'); }, update : function() { var ed = this.editor, elm, name = document.forms[0].anchorName.value, attribName; if (!name || !/^[a-z][a-z0-9\-\_:\.]*$/i.test(name)) { tinyMCEPopup.alert('advanced_dlg.anchor_invalid'); return; } tinyMCEPopup.restoreSelection(); if (this.action != 'update') ed.selection.collapse(1); var aRule = ed.schema.getElementRule('a'); if (!aRule || aRule.attributes.name) { attribName = 'name'; } else { attribName = 'id'; } elm = ed.dom.getParent(ed.selection.getNode(), 'A'); if (elm) { elm.setAttribute(attribName, name); elm[attribName] = name; ed.undoManager.add(); } else { // create with zero-sized nbsp so that in Webkit where anchor is on last line by itself caret cannot be placed after it var attrs = {'class' : 'mceItemAnchor'}; attrs[attribName] = name; ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('a', attrs, '\uFEFF')); ed.nodeChanged(); } tinyMCEPopup.close(); } }; tinyMCEPopup.onInit.add(AnchorDialog.init, AnchorDialog);
JavaScript
/** * charmap.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ tinyMCEPopup.requireLangPack(); var charmap = [ ['&nbsp;', '&#160;', true, 'no-break space'], ['&amp;', '&#38;', true, 'ampersand'], ['&quot;', '&#34;', true, 'quotation mark'], // finance ['&cent;', '&#162;', true, 'cent sign'], ['&euro;', '&#8364;', true, 'euro sign'], ['&pound;', '&#163;', true, 'pound sign'], ['&yen;', '&#165;', true, 'yen sign'], // signs ['&copy;', '&#169;', true, 'copyright sign'], ['&reg;', '&#174;', true, 'registered sign'], ['&trade;', '&#8482;', true, 'trade mark sign'], ['&permil;', '&#8240;', true, 'per mille sign'], ['&micro;', '&#181;', true, 'micro sign'], ['&middot;', '&#183;', true, 'middle dot'], ['&bull;', '&#8226;', true, 'bullet'], ['&hellip;', '&#8230;', true, 'three dot leader'], ['&prime;', '&#8242;', true, 'minutes / feet'], ['&Prime;', '&#8243;', true, 'seconds / inches'], ['&sect;', '&#167;', true, 'section sign'], ['&para;', '&#182;', true, 'paragraph sign'], ['&szlig;', '&#223;', true, 'sharp s / ess-zed'], // quotations ['&lsaquo;', '&#8249;', true, 'single left-pointing angle quotation mark'], ['&rsaquo;', '&#8250;', true, 'single right-pointing angle quotation mark'], ['&laquo;', '&#171;', true, 'left pointing guillemet'], ['&raquo;', '&#187;', true, 'right pointing guillemet'], ['&lsquo;', '&#8216;', true, 'left single quotation mark'], ['&rsquo;', '&#8217;', true, 'right single quotation mark'], ['&ldquo;', '&#8220;', true, 'left double quotation mark'], ['&rdquo;', '&#8221;', true, 'right double quotation mark'], ['&sbquo;', '&#8218;', true, 'single low-9 quotation mark'], ['&bdquo;', '&#8222;', true, 'double low-9 quotation mark'], ['&lt;', '&#60;', true, 'less-than sign'], ['&gt;', '&#62;', true, 'greater-than sign'], ['&le;', '&#8804;', true, 'less-than or equal to'], ['&ge;', '&#8805;', true, 'greater-than or equal to'], ['&ndash;', '&#8211;', true, 'en dash'], ['&mdash;', '&#8212;', true, 'em dash'], ['&macr;', '&#175;', true, 'macron'], ['&oline;', '&#8254;', true, 'overline'], ['&curren;', '&#164;', true, 'currency sign'], ['&brvbar;', '&#166;', true, 'broken bar'], ['&uml;', '&#168;', true, 'diaeresis'], ['&iexcl;', '&#161;', true, 'inverted exclamation mark'], ['&iquest;', '&#191;', true, 'turned question mark'], ['&circ;', '&#710;', true, 'circumflex accent'], ['&tilde;', '&#732;', true, 'small tilde'], ['&deg;', '&#176;', true, 'degree sign'], ['&minus;', '&#8722;', true, 'minus sign'], ['&plusmn;', '&#177;', true, 'plus-minus sign'], ['&divide;', '&#247;', true, 'division sign'], ['&frasl;', '&#8260;', true, 'fraction slash'], ['&times;', '&#215;', true, 'multiplication sign'], ['&sup1;', '&#185;', true, 'superscript one'], ['&sup2;', '&#178;', true, 'superscript two'], ['&sup3;', '&#179;', true, 'superscript three'], ['&frac14;', '&#188;', true, 'fraction one quarter'], ['&frac12;', '&#189;', true, 'fraction one half'], ['&frac34;', '&#190;', true, 'fraction three quarters'], // math / logical ['&fnof;', '&#402;', true, 'function / florin'], ['&int;', '&#8747;', true, 'integral'], ['&sum;', '&#8721;', true, 'n-ary sumation'], ['&infin;', '&#8734;', true, 'infinity'], ['&radic;', '&#8730;', true, 'square root'], ['&sim;', '&#8764;', false,'similar to'], ['&cong;', '&#8773;', false,'approximately equal to'], ['&asymp;', '&#8776;', true, 'almost equal to'], ['&ne;', '&#8800;', true, 'not equal to'], ['&equiv;', '&#8801;', true, 'identical to'], ['&isin;', '&#8712;', false,'element of'], ['&notin;', '&#8713;', false,'not an element of'], ['&ni;', '&#8715;', false,'contains as member'], ['&prod;', '&#8719;', true, 'n-ary product'], ['&and;', '&#8743;', false,'logical and'], ['&or;', '&#8744;', false,'logical or'], ['&not;', '&#172;', true, 'not sign'], ['&cap;', '&#8745;', true, 'intersection'], ['&cup;', '&#8746;', false,'union'], ['&part;', '&#8706;', true, 'partial differential'], ['&forall;', '&#8704;', false,'for all'], ['&exist;', '&#8707;', false,'there exists'], ['&empty;', '&#8709;', false,'diameter'], ['&nabla;', '&#8711;', false,'backward difference'], ['&lowast;', '&#8727;', false,'asterisk operator'], ['&prop;', '&#8733;', false,'proportional to'], ['&ang;', '&#8736;', false,'angle'], // undefined ['&acute;', '&#180;', true, 'acute accent'], ['&cedil;', '&#184;', true, 'cedilla'], ['&ordf;', '&#170;', true, 'feminine ordinal indicator'], ['&ordm;', '&#186;', true, 'masculine ordinal indicator'], ['&dagger;', '&#8224;', true, 'dagger'], ['&Dagger;', '&#8225;', true, 'double dagger'], // alphabetical special chars ['&Agrave;', '&#192;', true, 'A - grave'], ['&Aacute;', '&#193;', true, 'A - acute'], ['&Acirc;', '&#194;', true, 'A - circumflex'], ['&Atilde;', '&#195;', true, 'A - tilde'], ['&Auml;', '&#196;', true, 'A - diaeresis'], ['&Aring;', '&#197;', true, 'A - ring above'], ['&AElig;', '&#198;', true, 'ligature AE'], ['&Ccedil;', '&#199;', true, 'C - cedilla'], ['&Egrave;', '&#200;', true, 'E - grave'], ['&Eacute;', '&#201;', true, 'E - acute'], ['&Ecirc;', '&#202;', true, 'E - circumflex'], ['&Euml;', '&#203;', true, 'E - diaeresis'], ['&Igrave;', '&#204;', true, 'I - grave'], ['&Iacute;', '&#205;', true, 'I - acute'], ['&Icirc;', '&#206;', true, 'I - circumflex'], ['&Iuml;', '&#207;', true, 'I - diaeresis'], ['&ETH;', '&#208;', true, 'ETH'], ['&Ntilde;', '&#209;', true, 'N - tilde'], ['&Ograve;', '&#210;', true, 'O - grave'], ['&Oacute;', '&#211;', true, 'O - acute'], ['&Ocirc;', '&#212;', true, 'O - circumflex'], ['&Otilde;', '&#213;', true, 'O - tilde'], ['&Ouml;', '&#214;', true, 'O - diaeresis'], ['&Oslash;', '&#216;', true, 'O - slash'], ['&OElig;', '&#338;', true, 'ligature OE'], ['&Scaron;', '&#352;', true, 'S - caron'], ['&Ugrave;', '&#217;', true, 'U - grave'], ['&Uacute;', '&#218;', true, 'U - acute'], ['&Ucirc;', '&#219;', true, 'U - circumflex'], ['&Uuml;', '&#220;', true, 'U - diaeresis'], ['&Yacute;', '&#221;', true, 'Y - acute'], ['&Yuml;', '&#376;', true, 'Y - diaeresis'], ['&THORN;', '&#222;', true, 'THORN'], ['&agrave;', '&#224;', true, 'a - grave'], ['&aacute;', '&#225;', true, 'a - acute'], ['&acirc;', '&#226;', true, 'a - circumflex'], ['&atilde;', '&#227;', true, 'a - tilde'], ['&auml;', '&#228;', true, 'a - diaeresis'], ['&aring;', '&#229;', true, 'a - ring above'], ['&aelig;', '&#230;', true, 'ligature ae'], ['&ccedil;', '&#231;', true, 'c - cedilla'], ['&egrave;', '&#232;', true, 'e - grave'], ['&eacute;', '&#233;', true, 'e - acute'], ['&ecirc;', '&#234;', true, 'e - circumflex'], ['&euml;', '&#235;', true, 'e - diaeresis'], ['&igrave;', '&#236;', true, 'i - grave'], ['&iacute;', '&#237;', true, 'i - acute'], ['&icirc;', '&#238;', true, 'i - circumflex'], ['&iuml;', '&#239;', true, 'i - diaeresis'], ['&eth;', '&#240;', true, 'eth'], ['&ntilde;', '&#241;', true, 'n - tilde'], ['&ograve;', '&#242;', true, 'o - grave'], ['&oacute;', '&#243;', true, 'o - acute'], ['&ocirc;', '&#244;', true, 'o - circumflex'], ['&otilde;', '&#245;', true, 'o - tilde'], ['&ouml;', '&#246;', true, 'o - diaeresis'], ['&oslash;', '&#248;', true, 'o slash'], ['&oelig;', '&#339;', true, 'ligature oe'], ['&scaron;', '&#353;', true, 's - caron'], ['&ugrave;', '&#249;', true, 'u - grave'], ['&uacute;', '&#250;', true, 'u - acute'], ['&ucirc;', '&#251;', true, 'u - circumflex'], ['&uuml;', '&#252;', true, 'u - diaeresis'], ['&yacute;', '&#253;', true, 'y - acute'], ['&thorn;', '&#254;', true, 'thorn'], ['&yuml;', '&#255;', true, 'y - diaeresis'], ['&Alpha;', '&#913;', true, 'Alpha'], ['&Beta;', '&#914;', true, 'Beta'], ['&Gamma;', '&#915;', true, 'Gamma'], ['&Delta;', '&#916;', true, 'Delta'], ['&Epsilon;', '&#917;', true, 'Epsilon'], ['&Zeta;', '&#918;', true, 'Zeta'], ['&Eta;', '&#919;', true, 'Eta'], ['&Theta;', '&#920;', true, 'Theta'], ['&Iota;', '&#921;', true, 'Iota'], ['&Kappa;', '&#922;', true, 'Kappa'], ['&Lambda;', '&#923;', true, 'Lambda'], ['&Mu;', '&#924;', true, 'Mu'], ['&Nu;', '&#925;', true, 'Nu'], ['&Xi;', '&#926;', true, 'Xi'], ['&Omicron;', '&#927;', true, 'Omicron'], ['&Pi;', '&#928;', true, 'Pi'], ['&Rho;', '&#929;', true, 'Rho'], ['&Sigma;', '&#931;', true, 'Sigma'], ['&Tau;', '&#932;', true, 'Tau'], ['&Upsilon;', '&#933;', true, 'Upsilon'], ['&Phi;', '&#934;', true, 'Phi'], ['&Chi;', '&#935;', true, 'Chi'], ['&Psi;', '&#936;', true, 'Psi'], ['&Omega;', '&#937;', true, 'Omega'], ['&alpha;', '&#945;', true, 'alpha'], ['&beta;', '&#946;', true, 'beta'], ['&gamma;', '&#947;', true, 'gamma'], ['&delta;', '&#948;', true, 'delta'], ['&epsilon;', '&#949;', true, 'epsilon'], ['&zeta;', '&#950;', true, 'zeta'], ['&eta;', '&#951;', true, 'eta'], ['&theta;', '&#952;', true, 'theta'], ['&iota;', '&#953;', true, 'iota'], ['&kappa;', '&#954;', true, 'kappa'], ['&lambda;', '&#955;', true, 'lambda'], ['&mu;', '&#956;', true, 'mu'], ['&nu;', '&#957;', true, 'nu'], ['&xi;', '&#958;', true, 'xi'], ['&omicron;', '&#959;', true, 'omicron'], ['&pi;', '&#960;', true, 'pi'], ['&rho;', '&#961;', true, 'rho'], ['&sigmaf;', '&#962;', true, 'final sigma'], ['&sigma;', '&#963;', true, 'sigma'], ['&tau;', '&#964;', true, 'tau'], ['&upsilon;', '&#965;', true, 'upsilon'], ['&phi;', '&#966;', true, 'phi'], ['&chi;', '&#967;', true, 'chi'], ['&psi;', '&#968;', true, 'psi'], ['&omega;', '&#969;', true, 'omega'], // symbols ['&alefsym;', '&#8501;', false,'alef symbol'], ['&piv;', '&#982;', false,'pi symbol'], ['&real;', '&#8476;', false,'real part symbol'], ['&thetasym;','&#977;', false,'theta symbol'], ['&upsih;', '&#978;', false,'upsilon - hook symbol'], ['&weierp;', '&#8472;', false,'Weierstrass p'], ['&image;', '&#8465;', false,'imaginary part'], // arrows ['&larr;', '&#8592;', true, 'leftwards arrow'], ['&uarr;', '&#8593;', true, 'upwards arrow'], ['&rarr;', '&#8594;', true, 'rightwards arrow'], ['&darr;', '&#8595;', true, 'downwards arrow'], ['&harr;', '&#8596;', true, 'left right arrow'], ['&crarr;', '&#8629;', false,'carriage return'], ['&lArr;', '&#8656;', false,'leftwards double arrow'], ['&uArr;', '&#8657;', false,'upwards double arrow'], ['&rArr;', '&#8658;', false,'rightwards double arrow'], ['&dArr;', '&#8659;', false,'downwards double arrow'], ['&hArr;', '&#8660;', false,'left right double arrow'], ['&there4;', '&#8756;', false,'therefore'], ['&sub;', '&#8834;', false,'subset of'], ['&sup;', '&#8835;', false,'superset of'], ['&nsub;', '&#8836;', false,'not a subset of'], ['&sube;', '&#8838;', false,'subset of or equal to'], ['&supe;', '&#8839;', false,'superset of or equal to'], ['&oplus;', '&#8853;', false,'circled plus'], ['&otimes;', '&#8855;', false,'circled times'], ['&perp;', '&#8869;', false,'perpendicular'], ['&sdot;', '&#8901;', false,'dot operator'], ['&lceil;', '&#8968;', false,'left ceiling'], ['&rceil;', '&#8969;', false,'right ceiling'], ['&lfloor;', '&#8970;', false,'left floor'], ['&rfloor;', '&#8971;', false,'right floor'], ['&lang;', '&#9001;', false,'left-pointing angle bracket'], ['&rang;', '&#9002;', false,'right-pointing angle bracket'], ['&loz;', '&#9674;', true, 'lozenge'], ['&spades;', '&#9824;', true, 'black spade suit'], ['&clubs;', '&#9827;', true, 'black club suit'], ['&hearts;', '&#9829;', true, 'black heart suit'], ['&diams;', '&#9830;', true, 'black diamond suit'], ['&ensp;', '&#8194;', false,'en space'], ['&emsp;', '&#8195;', false,'em space'], ['&thinsp;', '&#8201;', false,'thin space'], ['&zwnj;', '&#8204;', false,'zero width non-joiner'], ['&zwj;', '&#8205;', false,'zero width joiner'], ['&lrm;', '&#8206;', false,'left-to-right mark'], ['&rlm;', '&#8207;', false,'right-to-left mark'], ['&shy;', '&#173;', false,'soft hyphen'] ]; tinyMCEPopup.onInit.add(function() { tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML()); addKeyboardNavigation(); }); function addKeyboardNavigation(){ var tableElm, cells, settings; cells = tinyMCEPopup.dom.select("a.charmaplink", "charmapgroup"); settings ={ root: "charmapgroup", items: cells }; cells[0].tabindex=0; tinyMCEPopup.dom.addClass(cells[0], "mceFocus"); if (tinymce.isGecko) { cells[0].focus(); } else { setTimeout(function(){ cells[0].focus(); }, 100); } tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', settings, tinyMCEPopup.dom); } function renderCharMapHTML() { var charsPerRow = 20, tdWidth=20, tdHeight=20, i; var html = '<div id="charmapgroup" aria-labelledby="charmap_label" tabindex="0" role="listbox">'+ '<table role="presentation" border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) + '"><tr height="' + tdHeight + '">'; var cols=-1; for (i=0; i<charmap.length; i++) { var previewCharFn; if (charmap[i][2]==true) { cols++; previewCharFn = 'previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');'; html += '' + '<td class="charmap">' + '<a class="charmaplink" role="button" onmouseover="'+previewCharFn+'" onfocus="'+previewCharFn+'" href="javascript:void(0)" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onclick="return false;" onmousedown="return false;" title="' + charmap[i][3] + ' '+ tinyMCEPopup.editor.translate("advanced_dlg.charmap_usage")+'">' + charmap[i][1] + '</a></td>'; if ((cols+1) % charsPerRow == 0) html += '</tr><tr height="' + tdHeight + '">'; } } if (cols % charsPerRow > 0) { var padd = charsPerRow - (cols % charsPerRow); for (var i=0; i<padd-1; i++) html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap">&nbsp;</td>'; } html += '</tr></table></div>'; html = html.replace(/<tr height="20"><\/tr>/g, ''); return html; } function insertChar(chr) { tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';'); // Refocus in window if (tinyMCEPopup.isWindow) window.focus(); tinyMCEPopup.editor.focus(); tinyMCEPopup.close(); } function previewChar(codeA, codeB, codeN) { var elmA = document.getElementById('codeA'); var elmB = document.getElementById('codeB'); var elmV = document.getElementById('codeV'); var elmN = document.getElementById('codeN'); if (codeA=='#160;') { elmV.innerHTML = '__'; } else { elmV.innerHTML = '&' + codeA; } elmB.innerHTML = '&amp;' + codeA; elmA.innerHTML = '&amp;' + codeB; elmN.innerHTML = codeN; }
JavaScript
tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(onLoadInit); function saveContent() { tinyMCEPopup.editor.setContent(document.getElementById('htmlSource').value, {source_view : true}); tinyMCEPopup.close(); } function onLoadInit() { tinyMCEPopup.resizeToInnerSize(); // Remove Gecko spellchecking if (tinymce.isGecko) document.body.spellcheck = tinyMCEPopup.editor.getParam("gecko_spellcheck"); document.getElementById('htmlSource').value = tinyMCEPopup.editor.getContent({source_view : true}); if (tinyMCEPopup.editor.getParam("theme_advanced_source_editor_wrap", true)) { turnWrapOn(); document.getElementById('wraped').checked = true; } resizeInputs(); } function setWrap(val) { var v, n, s = document.getElementById('htmlSource'); s.wrap = val; if (!tinymce.isIE) { v = s.value; n = s.cloneNode(false); n.setAttribute("wrap", val); s.parentNode.replaceChild(n, s); n.value = v; } } function setWhiteSpaceCss(value) { var el = document.getElementById('htmlSource'); tinymce.DOM.setStyle(el, 'white-space', value); } function turnWrapOff() { if (tinymce.isWebKit) { setWhiteSpaceCss('pre'); } else { setWrap('off'); } } function turnWrapOn() { if (tinymce.isWebKit) { setWhiteSpaceCss('pre-wrap'); } else { setWrap('soft'); } } function toggleWordWrap(elm) { if (elm.checked) { turnWrapOn(); } else { turnWrapOff(); } } function resizeInputs() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('htmlSource'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 65) + 'px'; } }
JavaScript
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '180px'; e = ed.selection.getNode(); this.fillFileList('image_list', tinyMCEPopup.getParam('external_image_list', 'tinyMCEImageList')); if (e.nodeName == 'IMG') { f.src.value = ed.dom.getAttrib(e, 'src'); f.alt.value = ed.dom.getAttrib(e, 'alt'); f.border.value = this.getAttrib(e, 'border'); f.vspace.value = this.getAttrib(e, 'vspace'); f.hspace.value = this.getAttrib(e, 'hspace'); f.width.value = ed.dom.getAttrib(e, 'width'); f.height.value = ed.dom.getAttrib(e, 'height'); f.insert.value = ed.getLang('update'); this.styleVal = ed.dom.getAttrib(e, 'style'); selectByValue(f, 'image_list', f.src.value); selectByValue(f, 'align', this.getAttrib(e, 'align')); this.updateStyle(); } }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = typeof(l) === 'function' ? l() : window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, update : function() { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el; tinyMCEPopup.restoreSelection(); if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (!ed.settings.inline_styles) { args = tinymce.extend(args, { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }); } else args.style = this.styleVal; tinymce.extend(args, { src : f.src.value.replace(/ /g, '%20'), alt : f.alt.value, width : f.width.value, height : f.height.value }); el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); tinyMCEPopup.editor.execCommand('mceRepaint'); tinyMCEPopup.editor.focus(); } else { tinymce.each(args, function(value, name) { if (value === "") { delete args[name]; } }); ed.execCommand('mceInsertContent', false, tinyMCEPopup.editor.dom.createHTML('img', args), {skip_undo : 1}); ed.undoManager.add(); } tinyMCEPopup.close(); }, updateStyle : function() { var dom = tinyMCEPopup.dom, st = {}, v, f = document.forms[0]; if (tinyMCEPopup.editor.settings.inline_styles) { tinymce.each(tinyMCEPopup.dom.parseStyle(this.styleVal), function(value, key) { st[key] = value; }); // Handle align v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') { st['float'] = v; delete st['vertical-align']; } else { st['vertical-align'] = v; delete st['float']; } } else { delete st['float']; delete st['vertical-align']; } // Handle border v = f.border.value; if (v || v == '0') { if (v == '0') st['border'] = '0'; else st['border'] = v + 'px solid black'; } else delete st['border']; // Handle hspace v = f.hspace.value; if (v) { delete st['margin']; st['margin-left'] = v + 'px'; st['margin-right'] = v + 'px'; } else { delete st['margin-left']; delete st['margin-right']; } // Handle vspace v = f.vspace.value; if (v) { delete st['margin']; st['margin-top'] = v + 'px'; st['margin-bottom'] = v + 'px'; } else { delete st['margin-top']; delete st['margin-bottom']; } // Merge st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st), 'img'); this.styleVal = dom.serializeStyle(st, 'img'); } }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, resetImageData : function() { var f = document.forms[0]; f.width.value = f.height.value = ""; }, updateImageData : function() { var f = document.forms[0], t = ImageDialog; if (f.width.value == "") f.width.value = t.preloadImg.width; if (f.height.value == "") f.height.value = t.preloadImg.height; }, getImageData : function() { var f = document.forms[0]; this.preloadImg = new Image(); this.preloadImg.onload = this.updateImageData; this.preloadImg.onerror = this.resetImageData; this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var LinkDialog = { preInit : function() { var url; if (url = tinyMCEPopup.getParam("external_link_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser', 'href', 'file', 'theme_advanced_link'); if (isVisible('hrefbrowser')) document.getElementById('href').style.width = '180px'; this.fillClassList('class_list'); this.fillFileList('link_list', 'tinyMCELinkList'); this.fillTargetList('target_list'); if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) { f.href.value = ed.dom.getAttrib(e, 'href'); f.linktitle.value = ed.dom.getAttrib(e, 'title'); f.insert.value = ed.getLang('update'); selectByValue(f, 'link_list', f.href.value); selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target')); selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class')); } }, update : function() { var f = document.forms[0], ed = tinyMCEPopup.editor, e, b, href = f.href.value.replace(/ /g, '%20'); tinyMCEPopup.restoreSelection(); e = ed.dom.getParent(ed.selection.getNode(), 'A'); // Remove element if there is no href if (!f.href.value) { if (e) { b = ed.selection.getBookmark(); ed.dom.remove(e, 1); ed.selection.moveToBookmark(b); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); return; } } // Create new anchor elements if (e == null) { ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { e = n; ed.dom.setAttribs(e, { href : href, title : f.linktitle.value, target : f.target_list ? getSelectValue(f, "target_list") : null, 'class' : f.class_list ? getSelectValue(f, "class_list") : null }); } }); } else { ed.dom.setAttribs(e, { href : href, title : f.linktitle.value }); if (f.target_list) { ed.dom.setAttrib(e, 'target', getSelectValue(f, "target_list")); } if (f.class_list) { ed.dom.setAttrib(e, 'class', getSelectValue(f, "class_list")); } } // Don't move caret if selection was image if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') { ed.focus(); ed.selection.select(e); ed.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); }, checkPrefix : function(n) { if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_email'))) n.value = 'mailto:' + n.value; if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_external'))) n.value = 'http://' + n.value; }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillTargetList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_same'), '_self'); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_blank'), '_blank'); if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) { tinymce.each(v.split(','), function(v) { v = v.split('='); lst.options[lst.options.length] = new Option(v[0], v[1]); }); } } }; LinkDialog.preInit(); tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog);
JavaScript
/** * editor_template_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, Cookie = tinymce.util.Cookie, lastExtID, explode = tinymce.explode; // Generates a preview for a format function getPreviewCss(ed, fmt) { var name, previewElm, dom = ed.dom, previewCss = '', parentFontSize, previewStylesName; previewStyles = ed.settings.preview_styles; // No preview forced if (previewStyles === false) return ''; // Default preview if (!previewStyles) previewStyles = 'font-family font-size font-weight text-decoration text-transform color background-color'; // Removes any variables since these can't be previewed function removeVars(val) { return val.replace(/%(\w+)/g, ''); }; // Create block/inline element to use for preview name = fmt.block || fmt.inline || 'span'; previewElm = dom.create(name); // Add format styles to preview element each(fmt.styles, function(value, name) { value = removeVars(value); if (value) dom.setStyle(previewElm, name, value); }); // Add attributes to preview element each(fmt.attributes, function(value, name) { value = removeVars(value); if (value) dom.setAttrib(previewElm, name, value); }); // Add classes to preview element each(fmt.classes, function(value) { value = removeVars(value); if (!dom.hasClass(previewElm, value)) dom.addClass(previewElm, value); }); // Add the previewElm outside the visual area dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF}); ed.getBody().appendChild(previewElm); // Get parent container font size so we can compute px values out of em/% for older IE:s parentFontSize = dom.getStyle(ed.getBody(), 'fontSize', true); parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; each(previewStyles.split(' '), function(name) { var value = dom.getStyle(previewElm, name, true); // If background is transparent then check if the body has a background color we can use if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { value = dom.getStyle(ed.getBody(), name, true); // Ignore white since it's the default color, not the nicest fix if (dom.toHex(value).toLowerCase() == '#ffffff') { return; } } // Old IE won't calculate the font size so we need to do that manually if (name == 'font-size') { if (/em|%$/.test(value)) { if (parentFontSize === 0) { return; } // Convert font size from em/% to px value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1); value = (value * parentFontSize) + 'px'; } } previewCss += name + ':' + value + ';'; }); dom.remove(previewElm); return previewCss; }; // Tell it to load theme specific language pack(s) tinymce.ThemeManager.requireLangPack('advanced'); tinymce.create('tinymce.themes.AdvancedTheme', { sizes : [8, 10, 12, 14, 18, 24, 36], // Control name lookup, format: title, command controls : { bold : ['bold_desc', 'Bold'], italic : ['italic_desc', 'Italic'], underline : ['underline_desc', 'Underline'], strikethrough : ['striketrough_desc', 'Strikethrough'], justifyleft : ['justifyleft_desc', 'JustifyLeft'], justifycenter : ['justifycenter_desc', 'JustifyCenter'], justifyright : ['justifyright_desc', 'JustifyRight'], justifyfull : ['justifyfull_desc', 'JustifyFull'], bullist : ['bullist_desc', 'InsertUnorderedList'], numlist : ['numlist_desc', 'InsertOrderedList'], outdent : ['outdent_desc', 'Outdent'], indent : ['indent_desc', 'Indent'], cut : ['cut_desc', 'Cut'], copy : ['copy_desc', 'Copy'], paste : ['paste_desc', 'Paste'], undo : ['undo_desc', 'Undo'], redo : ['redo_desc', 'Redo'], link : ['link_desc', 'mceLink'], unlink : ['unlink_desc', 'unlink'], image : ['image_desc', 'mceImage'], cleanup : ['cleanup_desc', 'mceCleanup'], help : ['help_desc', 'mceHelp'], code : ['code_desc', 'mceCodeEditor'], hr : ['hr_desc', 'InsertHorizontalRule'], removeformat : ['removeformat_desc', 'RemoveFormat'], sub : ['sub_desc', 'subscript'], sup : ['sup_desc', 'superscript'], forecolor : ['forecolor_desc', 'ForeColor'], forecolorpicker : ['forecolor_desc', 'mceForeColor'], backcolor : ['backcolor_desc', 'HiliteColor'], backcolorpicker : ['backcolor_desc', 'mceBackColor'], charmap : ['charmap_desc', 'mceCharMap'], visualaid : ['visualaid_desc', 'mceToggleVisualAid'], anchor : ['anchor_desc', 'mceInsertAnchor'], newdocument : ['newdocument_desc', 'mceNewDocument'], blockquote : ['blockquote_desc', 'mceBlockQuote'] }, stateControls : ['bold', 'italic', 'underline', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'sub', 'sup', 'blockquote'], init : function(ed, url) { var t = this, s, v, o; t.editor = ed; t.url = url; t.onResolveName = new tinymce.util.Dispatcher(this); s = ed.settings; ed.forcedHighContrastMode = ed.settings.detect_highcontrast && t._isHighContrast(); ed.settings.skin = ed.forcedHighContrastMode ? 'highcontrast' : ed.settings.skin; // Setup default buttons if (!s.theme_advanced_buttons1) { s = extend({ theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect", theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code", theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap" }, s); } // Default settings t.settings = s = extend({ theme_advanced_path : true, theme_advanced_toolbar_location : 'top', theme_advanced_blockformats : "p,address,pre,h1,h2,h3,h4,h5,h6", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats", theme_advanced_more_colors : 1, theme_advanced_row_height : 23, theme_advanced_resize_horizontal : 1, theme_advanced_resizing_use_cookie : 1, theme_advanced_font_sizes : "1,2,3,4,5,6,7", theme_advanced_font_selector : "span", theme_advanced_show_current_color: 0, readonly : ed.settings.readonly }, s); // Setup default font_size_style_values if (!s.font_size_style_values) s.font_size_style_values = "8pt,10pt,12pt,14pt,18pt,24pt,36pt"; if (tinymce.is(s.theme_advanced_font_sizes, 'string')) { s.font_size_style_values = tinymce.explode(s.font_size_style_values); s.font_size_classes = tinymce.explode(s.font_size_classes || ''); // Parse string value o = {}; ed.settings.theme_advanced_font_sizes = s.theme_advanced_font_sizes; each(ed.getParam('theme_advanced_font_sizes', '', 'hash'), function(v, k) { var cl; if (k == v && v >= 1 && v <= 7) { k = v + ' (' + t.sizes[v - 1] + 'pt)'; cl = s.font_size_classes[v - 1]; v = s.font_size_style_values[v - 1] || (t.sizes[v - 1] + 'pt'); } if (/^\s*\./.test(v)) cl = v.replace(/\./g, ''); o[k] = cl ? {'class' : cl} : {fontSize : v}; }); s.theme_advanced_font_sizes = o; } if ((v = s.theme_advanced_path_location) && v != 'none') s.theme_advanced_statusbar_location = s.theme_advanced_path_location; if (s.theme_advanced_statusbar_location == 'none') s.theme_advanced_statusbar_location = 0; if (ed.settings.content_css !== false) ed.contentCSS.push(ed.baseURI.toAbsolute(url + "/skins/" + ed.settings.skin + "/content.css")); // Init editor ed.onInit.add(function() { if (!ed.settings.readonly) { ed.onNodeChange.add(t._nodeChanged, t); ed.onKeyUp.add(t._updateUndoStatus, t); ed.onMouseUp.add(t._updateUndoStatus, t); ed.dom.bind(ed.dom.getRoot(), 'dragend', function() { t._updateUndoStatus(ed); }); } }); ed.onSetProgressState.add(function(ed, b, ti) { var co, id = ed.id, tb; if (b) { t.progressTimer = setTimeout(function() { co = ed.getContainer(); co = co.insertBefore(DOM.create('DIV', {style : 'position:relative'}), co.firstChild); tb = DOM.get(ed.id + '_tbl'); DOM.add(co, 'div', {id : id + '_blocker', 'class' : 'mceBlocker', style : {width : tb.clientWidth + 2, height : tb.clientHeight + 2}}); DOM.add(co, 'div', {id : id + '_progress', 'class' : 'mceProgress', style : {left : tb.clientWidth / 2, top : tb.clientHeight / 2}}); }, ti || 0); } else { DOM.remove(id + '_blocker'); DOM.remove(id + '_progress'); clearTimeout(t.progressTimer); } }); DOM.loadCSS(s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : url + "/skins/" + ed.settings.skin + "/ui.css"); if (s.skin_variant) DOM.loadCSS(url + "/skins/" + ed.settings.skin + "/ui_" + s.skin_variant + ".css"); }, _isHighContrast : function() { var actualColor, div = DOM.add(DOM.getRoot(), 'div', {'style': 'background-color: rgb(171,239,86);'}); actualColor = (DOM.getStyle(div, 'background-color', true) + '').toLowerCase().replace(/ /g, ''); DOM.remove(div); return actualColor != 'rgb(171,239,86)' && actualColor != '#abef56'; }, createControl : function(n, cf) { var cd, c; if (c = cf.createControl(n)) return c; switch (n) { case "styleselect": return this._createStyleSelect(); case "formatselect": return this._createBlockFormats(); case "fontselect": return this._createFontSelect(); case "fontsizeselect": return this._createFontSizeSelect(); case "forecolor": return this._createForeColorMenu(); case "backcolor": return this._createBackColorMenu(); } if ((cd = this.controls[n])) return cf.createButton(n, {title : "advanced." + cd[0], cmd : cd[1], ui : cd[2], value : cd[3]}); }, execCommand : function(cmd, ui, val) { var f = this['_' + cmd]; if (f) { f.call(this, ui, val); return true; } return false; }, _importClasses : function(e) { var ed = this.editor, ctrl = ed.controlManager.get('styleselect'); if (ctrl.getLength() == 0) { each(ed.dom.getClasses(), function(o, idx) { var name = 'style_' + idx, fmt; fmt = { inline : 'span', attributes : {'class' : o['class']}, selector : '*' }; ed.formatter.register(name, fmt); ctrl.add(o['class'], name, { style: function() { return getPreviewCss(ed, fmt); } }); }); } }, _createStyleSelect : function(n) { var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl; // Setup style select box ctrl = ctrlMan.createListBox('styleselect', { title : 'advanced.style_select', onselect : function(name) { var matches, formatNames = [], removedFormat; each(ctrl.items, function(item) { formatNames.push(item.value); }); ed.focus(); ed.undoManager.add(); // Toggle off the current format(s) matches = ed.formatter.matchAll(formatNames); tinymce.each(matches, function(match) { if (!name || match == name) { if (match) ed.formatter.remove(match); removedFormat = true; } }); if (!removedFormat) ed.formatter.apply(name); ed.undoManager.add(); ed.nodeChanged(); return false; // No auto select } }); // Handle specified format ed.onPreInit.add(function() { var counter = 0, formats = ed.getParam('style_formats'); if (formats) { each(formats, function(fmt) { var name, keys = 0; each(fmt, function() {keys++;}); if (keys > 1) { name = fmt.name = fmt.name || 'style_' + (counter++); ed.formatter.register(name, fmt); ctrl.add(fmt.title, name, { style: function() { return getPreviewCss(ed, fmt); } }); } else ctrl.add(fmt.title); }); } else { each(ed.getParam('theme_advanced_styles', '', 'hash'), function(val, key) { var name, fmt; if (val) { name = 'style_' + (counter++); fmt = { inline : 'span', classes : val, selector : '*' }; ed.formatter.register(name, fmt); ctrl.add(t.editor.translate(key), name, { style: function() { return getPreviewCss(ed, fmt); } }); } }); } }); // Auto import classes if the ctrl box is empty if (ctrl.getLength() == 0) { ctrl.onPostRender.add(function(ed, n) { if (!ctrl.NativeListBox) { Event.add(n.id + '_text', 'focus', t._importClasses, t); Event.add(n.id + '_text', 'mousedown', t._importClasses, t); Event.add(n.id + '_open', 'focus', t._importClasses, t); Event.add(n.id + '_open', 'mousedown', t._importClasses, t); } else Event.add(n.id, 'focus', t._importClasses, t); }); } return ctrl; }, _createFontSelect : function() { var c, t = this, ed = t.editor; c = ed.controlManager.createListBox('fontselect', { title : 'advanced.fontdefault', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { ed.execCommand('FontName', false, cur.value); return; } ed.execCommand('FontName', false, v); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && cur.value == v) { c.select(null); } return false; // No auto select } }); if (c) { each(ed.getParam('theme_advanced_fonts', t.settings.theme_advanced_fonts, 'hash'), function(v, k) { c.add(ed.translate(k), v, {style : v.indexOf('dings') == -1 ? 'font-family:' + v : ''}); }); } return c; }, _createFontSizeSelect : function() { var t = this, ed = t.editor, c, i = 0, cl = []; c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { cur = cur.value; if (cur['class']) { ed.formatter.toggle('fontsize_class', {value : cur['class']}); ed.undoManager.add(); ed.nodeChanged(); } else { ed.execCommand('FontSize', false, cur.fontSize); } return; } if (v['class']) { ed.focus(); ed.undoManager.add(); ed.formatter.toggle('fontsize_class', {value : v['class']}); ed.undoManager.add(); ed.nodeChanged(); } else ed.execCommand('FontSize', false, v.fontSize); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && (cur.value.fontSize == v.fontSize || cur.value['class'] && cur.value['class'] == v['class'])) { c.select(null); } return false; // No auto select }}); if (c) { each(t.settings.theme_advanced_font_sizes, function(v, k) { var fz = v.fontSize; if (fz >= 1 && fz <= 7) fz = t.sizes[parseInt(fz) - 1] + 'pt'; c.add(k, v, {'style' : 'font-size:' + fz, 'class' : 'mceFontSize' + (i++) + (' ' + (v['class'] || ''))}); }); } return c; }, _createBlockFormats : function() { var c, fmts = { p : 'advanced.paragraph', address : 'advanced.address', pre : 'advanced.pre', h1 : 'advanced.h1', h2 : 'advanced.h2', h3 : 'advanced.h3', h4 : 'advanced.h4', h5 : 'advanced.h5', h6 : 'advanced.h6', div : 'advanced.div', blockquote : 'advanced.blockquote', code : 'advanced.code', dt : 'advanced.dt', dd : 'advanced.dd', samp : 'advanced.samp' }, t = this; c = t.editor.controlManager.createListBox('formatselect', {title : 'advanced.block', onselect : function(v) { t.editor.execCommand('FormatBlock', false, v); return false; }}); if (c) { each(t.editor.getParam('theme_advanced_blockformats', t.settings.theme_advanced_blockformats, 'hash'), function(v, k) { c.add(t.editor.translate(k != v ? k : fmts[v]), v, {'class' : 'mce_formatPreview mce_' + v, style: function() { return getPreviewCss(t.editor, {block: v}); }}); }); } return c; }, _createForeColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_text_colors) o.colors = v; if (s.theme_advanced_default_foreground_color) o.default_color = s.theme_advanced_default_foreground_color; o.title = 'advanced.forecolor_desc'; o.cmd = 'ForeColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('forecolor', o); return c; }, _createBackColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_background_colors) o.colors = v; if (s.theme_advanced_default_background_color) o.default_color = s.theme_advanced_default_background_color; o.title = 'advanced.backcolor_desc'; o.cmd = 'HiliteColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('backcolor', o); return c; }, renderUI : function(o) { var n, ic, tb, t = this, ed = t.editor, s = t.settings, sc, p, nl; if (ed.settings) { ed.settings.aria_label = s.aria_label + ed.getLang('advanced.help_shortcut'); } // TODO: ACC Should have an aria-describedby attribute which is user-configurable to describe what this field is actually for. // Maybe actually inherit it from the original textara? n = p = DOM.create('span', {role : 'application', 'aria-labelledby' : ed.id + '_voice', id : ed.id + '_parent', 'class' : 'mceEditor ' + ed.settings.skin + 'Skin' + (s.skin_variant ? ' ' + ed.settings.skin + 'Skin' + t._ufirst(s.skin_variant) : '') + (ed.settings.directionality == "rtl" ? ' mceRtl' : '')}); DOM.add(n, 'span', {'class': 'mceVoiceLabel', 'style': 'display:none;', id: ed.id + '_voice'}, s.aria_label); if (!DOM.boxModel) n = DOM.add(n, 'div', {'class' : 'mceOldBoxModel'}); n = sc = DOM.add(n, 'table', {role : "presentation", id : ed.id + '_tbl', 'class' : 'mceLayout', cellSpacing : 0, cellPadding : 0}); n = tb = DOM.add(n, 'tbody'); switch ((s.theme_advanced_layout_manager || '').toLowerCase()) { case "rowlayout": ic = t._rowLayout(s, tb, o); break; case "customlayout": ic = ed.execCallback("theme_advanced_custom_layout", s, tb, o, p); break; default: ic = t._simpleLayout(s, tb, o, p); } n = o.targetNode; // Add classes to first and last TRs nl = sc.rows; DOM.addClass(nl[0], 'mceFirst'); DOM.addClass(nl[nl.length - 1], 'mceLast'); // Add classes to first and last TDs each(DOM.select('tr', tb), function(n) { DOM.addClass(n.firstChild, 'mceFirst'); DOM.addClass(n.childNodes[n.childNodes.length - 1], 'mceLast'); }); if (DOM.get(s.theme_advanced_toolbar_container)) DOM.get(s.theme_advanced_toolbar_container).appendChild(p); else DOM.insertAfter(p, n); Event.add(ed.id + '_path_row', 'click', function(e) { e = e.target; if (e.nodeName == 'A') { t._sel(e.className.replace(/^.*mcePath_([0-9]+).*$/, '$1')); return false; } }); /* if (DOM.get(ed.id + '_path_row')) { Event.add(ed.id + '_tbl', 'mouseover', function(e) { var re; e = e.target; if (e.nodeName == 'SPAN' && DOM.hasClass(e.parentNode, 'mceButton')) { re = DOM.get(ed.id + '_path_row'); t.lastPath = re.innerHTML; DOM.setHTML(re, e.parentNode.title); } }); Event.add(ed.id + '_tbl', 'mouseout', function(e) { if (t.lastPath) { DOM.setHTML(ed.id + '_path_row', t.lastPath); t.lastPath = 0; } }); } */ if (!ed.getParam('accessibility_focus')) Event.add(DOM.add(p, 'a', {href : '#'}, '<!-- IE -->'), 'focus', function() {tinyMCE.get(ed.id).focus();}); if (s.theme_advanced_toolbar_location == 'external') o.deltaHeight = 0; t.deltaHeight = o.deltaHeight; o.targetNode = null; ed.onKeyDown.add(function(ed, evt) { var DOM_VK_F10 = 121, DOM_VK_F11 = 122; if (evt.altKey) { if (evt.keyCode === DOM_VK_F10) { // Make sure focus is given to toolbar in Safari. // We can't do this in IE as it prevents giving focus to toolbar when editor is in a frame if (tinymce.isWebKit) { window.focus(); } t.toolbarGroup.focus(); return Event.cancel(evt); } else if (evt.keyCode === DOM_VK_F11) { DOM.get(ed.id + '_path_row').focus(); return Event.cancel(evt); } } }); // alt+0 is the UK recommended shortcut for accessing the list of access controls. ed.addShortcut('alt+0', '', 'mceShortcuts', t); return { iframeContainer : ic, editorContainer : ed.id + '_parent', sizeContainer : sc, deltaHeight : o.deltaHeight }; }, getInfo : function() { return { longname : 'Advanced theme', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', version : tinymce.majorVersion + "." + tinymce.minorVersion } }, resizeBy : function(dw, dh) { var e = DOM.get(this.editor.id + '_ifr'); this.resizeTo(e.clientWidth + dw, e.clientHeight + dh); }, resizeTo : function(w, h, store) { var ed = this.editor, s = this.settings, e = DOM.get(ed.id + '_tbl'), ifr = DOM.get(ed.id + '_ifr'); // Boundery fix box w = Math.max(s.theme_advanced_resizing_min_width || 100, w); h = Math.max(s.theme_advanced_resizing_min_height || 100, h); w = Math.min(s.theme_advanced_resizing_max_width || 0xFFFF, w); h = Math.min(s.theme_advanced_resizing_max_height || 0xFFFF, h); // Resize iframe and container DOM.setStyle(e, 'height', ''); DOM.setStyle(ifr, 'height', h); if (s.theme_advanced_resize_horizontal) { DOM.setStyle(e, 'width', ''); DOM.setStyle(ifr, 'width', w); // Make sure that the size is never smaller than the over all ui if (w < e.clientWidth) { w = e.clientWidth; DOM.setStyle(ifr, 'width', e.clientWidth); } } // Store away the size if (store && s.theme_advanced_resizing_use_cookie) { Cookie.setHash("TinyMCE_" + ed.id + "_size", { cw : w, ch : h }); } }, destroy : function() { var id = this.editor.id; Event.clear(id + '_resize'); Event.clear(id + '_path_row'); Event.clear(id + '_external_close'); }, // Internal functions _simpleLayout : function(s, tb, o, p) { var t = this, ed = t.editor, lo = s.theme_advanced_toolbar_location, sl = s.theme_advanced_statusbar_location, n, ic, etb, c; if (s.readonly) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); return ic; } // Create toolbar container at top if (lo == 'top') t._addToolbars(tb, o); // Create external toolbar if (lo == 'external') { n = c = DOM.create('div', {style : 'position:relative'}); n = DOM.add(n, 'div', {id : ed.id + '_external', 'class' : 'mceExternalToolbar'}); DOM.add(n, 'a', {id : ed.id + '_external_close', href : 'javascript:;', 'class' : 'mceExternalClose'}); n = DOM.add(n, 'table', {id : ed.id + '_tblext', cellSpacing : 0, cellPadding : 0}); etb = DOM.add(n, 'tbody'); if (p.firstChild.className == 'mceOldBoxModel') p.firstChild.appendChild(c); else p.insertBefore(c, p.firstChild); t._addToolbars(etb, o); ed.onMouseUp.add(function() { var e = DOM.get(ed.id + '_external'); DOM.show(e); DOM.hide(lastExtID); var f = Event.add(ed.id + '_external_close', 'click', function() { DOM.hide(ed.id + '_external'); Event.remove(ed.id + '_external_close', 'click', f); return false; }); DOM.show(e); DOM.setStyle(e, 'top', 0 - DOM.getRect(ed.id + '_tblext').h - 1); // Fixes IE rendering bug DOM.hide(e); DOM.show(e); e.style.filter = ''; lastExtID = ed.id + '_external'; e = null; }); } if (sl == 'top') t._addStatusBar(tb, o); // Create iframe container if (!s.theme_advanced_toolbar_container) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); } // Create toolbar container at bottom if (lo == 'bottom') t._addToolbars(tb, o); if (sl == 'bottom') t._addStatusBar(tb, o); return ic; }, _rowLayout : function(s, tb, o) { var t = this, ed = t.editor, dc, da, cf = ed.controlManager, n, ic, to, a; dc = s.theme_advanced_containers_default_class || ''; da = s.theme_advanced_containers_default_align || 'center'; each(explode(s.theme_advanced_containers || ''), function(c, i) { var v = s['theme_advanced_container_' + c] || ''; switch (c.toLowerCase()) { case 'mceeditor': n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); break; case 'mceelementpath': t._addStatusBar(tb, o); break; default: a = (s['theme_advanced_container_' + c + '_align'] || da).toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(tb, 'tr'), 'td', { 'class' : 'mceToolbar ' + (s['theme_advanced_container_' + c + '_class'] || dc) + ' ' + a || da }); to = cf.createToolbar("toolbar" + i); t._addControls(v, to); DOM.setHTML(n, to.renderHTML()); o.deltaHeight -= s.theme_advanced_row_height; } }); return ic; }, _addControls : function(v, tb) { var t = this, s = t.settings, di, cf = t.editor.controlManager; if (s.theme_advanced_disable && !t._disabled) { di = {}; each(explode(s.theme_advanced_disable), function(v) { di[v] = 1; }); t._disabled = di; } else di = t._disabled; each(explode(v), function(n) { var c; if (di && di[n]) return; // Compatiblity with 2.x if (n == 'tablecontrols') { each(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"], function(n) { n = t.createControl(n, cf); if (n) tb.add(n); }); return; } c = t.createControl(n, cf); if (c) tb.add(c); }); }, _addToolbars : function(c, o) { var t = this, i, tb, ed = t.editor, s = t.settings, v, cf = ed.controlManager, di, n, h = [], a, toolbarGroup, toolbarsExist = false; toolbarGroup = cf.createToolbarGroup('toolbargroup', { 'name': ed.getLang('advanced.toolbar'), 'tab_focus_toolbar':ed.getParam('theme_advanced_tab_focus_toolbar') }); t.toolbarGroup = toolbarGroup; a = s.theme_advanced_toolbar_align.toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(c, 'tr', {role: 'presentation'}), 'td', {'class' : 'mceToolbar ' + a, "role":"toolbar"}); // Create toolbar and add the controls for (i=1; (v = s['theme_advanced_buttons' + i]); i++) { toolbarsExist = true; tb = cf.createToolbar("toolbar" + i, {'class' : 'mceToolbarRow' + i}); if (s['theme_advanced_buttons' + i + '_add']) v += ',' + s['theme_advanced_buttons' + i + '_add']; if (s['theme_advanced_buttons' + i + '_add_before']) v = s['theme_advanced_buttons' + i + '_add_before'] + ',' + v; t._addControls(v, tb); toolbarGroup.add(tb); o.deltaHeight -= s.theme_advanced_row_height; } // Handle case when there are no toolbar buttons and ensure editor height is adjusted accordingly if (!toolbarsExist) o.deltaHeight -= s.theme_advanced_row_height; h.push(toolbarGroup.renderHTML()); h.push(DOM.createHTML('a', {href : '#', accesskey : 'z', title : ed.getLang("advanced.toolbar_focus"), onfocus : 'tinyMCE.getInstanceById(\'' + ed.id + '\').focus();'}, '<!-- IE -->')); DOM.setHTML(n, h.join('')); }, _addStatusBar : function(tb, o) { var n, t = this, ed = t.editor, s = t.settings, r, mf, me, td; n = DOM.add(tb, 'tr'); n = td = DOM.add(n, 'td', {'class' : 'mceStatusbar'}); n = DOM.add(n, 'div', {id : ed.id + '_path_row', 'role': 'group', 'aria-labelledby': ed.id + '_path_voice'}); if (s.theme_advanced_path) { DOM.add(n, 'span', {id: ed.id + '_path_voice'}, ed.translate('advanced.path')); DOM.add(n, 'span', {}, ': '); } else { DOM.add(n, 'span', {}, '&#160;'); } if (s.theme_advanced_resizing) { DOM.add(td, 'a', {id : ed.id + '_resize', href : 'javascript:;', onclick : "return false;", 'class' : 'mceResize', tabIndex:"-1"}); if (s.theme_advanced_resizing_use_cookie) { ed.onPostRender.add(function() { var o = Cookie.getHash("TinyMCE_" + ed.id + "_size"), c = DOM.get(ed.id + '_tbl'); if (!o) return; t.resizeTo(o.cw, o.ch); }); } ed.onPostRender.add(function() { Event.add(ed.id + '_resize', 'click', function(e) { e.preventDefault(); }); Event.add(ed.id + '_resize', 'mousedown', function(e) { var mouseMoveHandler1, mouseMoveHandler2, mouseUpHandler1, mouseUpHandler2, startX, startY, startWidth, startHeight, width, height, ifrElm; function resizeOnMove(e) { e.preventDefault(); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height); }; function endResize(e) { // Stop listening Event.remove(DOM.doc, 'mousemove', mouseMoveHandler1); Event.remove(ed.getDoc(), 'mousemove', mouseMoveHandler2); Event.remove(DOM.doc, 'mouseup', mouseUpHandler1); Event.remove(ed.getDoc(), 'mouseup', mouseUpHandler2); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height, true); ed.nodeChanged(); }; e.preventDefault(); // Get the current rect size startX = e.screenX; startY = e.screenY; ifrElm = DOM.get(t.editor.id + '_ifr'); startWidth = width = ifrElm.clientWidth; startHeight = height = ifrElm.clientHeight; // Register envent handlers mouseMoveHandler1 = Event.add(DOM.doc, 'mousemove', resizeOnMove); mouseMoveHandler2 = Event.add(ed.getDoc(), 'mousemove', resizeOnMove); mouseUpHandler1 = Event.add(DOM.doc, 'mouseup', endResize); mouseUpHandler2 = Event.add(ed.getDoc(), 'mouseup', endResize); }); }); } o.deltaHeight -= 21; n = tb = null; }, _updateUndoStatus : function(ed) { var cm = ed.controlManager, um = ed.undoManager; cm.setDisabled('undo', !um.hasUndo() && !um.typing); cm.setDisabled('redo', !um.hasRedo()); }, _nodeChanged : function(ed, cm, n, co, ob) { var t = this, p, de = 0, v, c, s = t.settings, cl, fz, fn, fc, bc, formatNames, matches; tinymce.each(t.stateControls, function(c) { cm.setActive(c, ed.queryCommandState(t.controls[c][1])); }); function getParent(name) { var i, parents = ob.parents, func = name; if (typeof(name) == 'string') { func = function(node) { return node.nodeName == name; }; } for (i = 0; i < parents.length; i++) { if (func(parents[i])) return parents[i]; } }; cm.setActive('visualaid', ed.hasVisual); t._updateUndoStatus(ed); cm.setDisabled('outdent', !ed.queryCommandState('Outdent')); p = getParent('A'); if (c = cm.get('link')) { c.setDisabled((!p && co) || (p && !p.href)); c.setActive(!!p && (!p.name && !p.id)); } if (c = cm.get('unlink')) { c.setDisabled(!p && co); c.setActive(!!p && !p.name && !p.id); } if (c = cm.get('anchor')) { c.setActive(!co && !!p && (p.name || (p.id && !p.href))); } p = getParent('IMG'); if (c = cm.get('image')) c.setActive(!co && !!p && n.className.indexOf('mceItem') == -1); if (c = cm.get('styleselect')) { t._importClasses(); formatNames = []; each(c.items, function(item) { formatNames.push(item.value); }); matches = ed.formatter.matchAll(formatNames); c.select(matches[0]); tinymce.each(matches, function(match, index) { if (index > 0) { c.mark(match); } }); } if (c = cm.get('formatselect')) { p = getParent(ed.dom.isBlock); if (p) c.select(p.nodeName.toLowerCase()); } // Find out current fontSize, fontFamily and fontClass getParent(function(n) { if (n.nodeName === 'SPAN') { if (!cl && n.className) cl = n.className; } if (ed.dom.is(n, s.theme_advanced_font_selector)) { if (!fz && n.style.fontSize) fz = n.style.fontSize; if (!fn && n.style.fontFamily) fn = n.style.fontFamily.replace(/[\"\']+/g, '').replace(/^([^,]+).*/, '$1').toLowerCase(); if (!fc && n.style.color) fc = n.style.color; if (!bc && n.style.backgroundColor) bc = n.style.backgroundColor; } return false; }); if (c = cm.get('fontselect')) { c.select(function(v) { return v.replace(/^([^,]+).*/, '$1').toLowerCase() == fn; }); } // Select font size if (c = cm.get('fontsizeselect')) { // Use computed style if (s.theme_advanced_runtime_fontsize && !fz && !cl) fz = ed.dom.getStyle(n, 'fontSize', true); c.select(function(v) { if (v.fontSize && v.fontSize === fz) return true; if (v['class'] && v['class'] === cl) return true; }); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } } updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } }; updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_path && s.theme_advanced_statusbar_location) { p = DOM.get(ed.id + '_path') || DOM.add(ed.id + '_path_row', 'span', {id : ed.id + '_path'}); if (t.statusKeyboardNavigation) { t.statusKeyboardNavigation.destroy(); t.statusKeyboardNavigation = null; } DOM.setHTML(p, ''); getParent(function(n) { var na = n.nodeName.toLowerCase(), u, pi, ti = ''; // Ignore non element and bogus/hidden elements if (n.nodeType != 1 || na === 'br' || n.getAttribute('data-mce-bogus') || DOM.hasClass(n, 'mceItemHidden') || DOM.hasClass(n, 'mceItemRemoved')) return; // Handle prefix if (tinymce.isIE && n.scopeName !== 'HTML' && n.scopeName) na = n.scopeName + ':' + na; // Remove internal prefix na = na.replace(/mce\:/g, ''); // Handle node name switch (na) { case 'b': na = 'strong'; break; case 'i': na = 'em'; break; case 'img': if (v = DOM.getAttrib(n, 'src')) ti += 'src: ' + v + ' '; break; case 'a': if (v = DOM.getAttrib(n, 'name')) { ti += 'name: ' + v + ' '; na += '#' + v; } if (v = DOM.getAttrib(n, 'href')) ti += 'href: ' + v + ' '; break; case 'font': if (v = DOM.getAttrib(n, 'face')) ti += 'font: ' + v + ' '; if (v = DOM.getAttrib(n, 'size')) ti += 'size: ' + v + ' '; if (v = DOM.getAttrib(n, 'color')) ti += 'color: ' + v + ' '; break; case 'span': if (v = DOM.getAttrib(n, 'style')) ti += 'style: ' + v + ' '; break; } if (v = DOM.getAttrib(n, 'id')) ti += 'id: ' + v + ' '; if (v = n.className) { v = v.replace(/\b\s*(webkit|mce|Apple-)\w+\s*\b/g, ''); if (v) { ti += 'class: ' + v + ' '; if (ed.dom.isBlock(n) || na == 'img' || na == 'span') na += '.' + v; } } na = na.replace(/(html:)/g, ''); na = {name : na, node : n, title : ti}; t.onResolveName.dispatch(t, na); ti = na.title; na = na.name; //u = "javascript:tinymce.EditorManager.get('" + ed.id + "').theme._sel('" + (de++) + "');"; pi = DOM.create('a', {'href' : "javascript:;", role: 'button', onmousedown : "return false;", title : ti, 'class' : 'mcePath_' + (de++)}, na); if (p.hasChildNodes()) { p.insertBefore(DOM.create('span', {'aria-hidden': 'true'}, '\u00a0\u00bb '), p.firstChild); p.insertBefore(pi, p.firstChild); } else p.appendChild(pi); }, ed.getBody()); if (DOM.select('a', p).length > 0) { t.statusKeyboardNavigation = new tinymce.ui.KeyboardNavigation({ root: ed.id + "_path_row", items: DOM.select('a', p), excludeFromTabOrder: true, onCancel: function() { ed.focus(); } }, DOM); } } }, // Commands gets called by execCommand _sel : function(v) { this.editor.execCommand('mceSelectNodeDepth', false, v); }, _mceInsertAnchor : function(ui, v) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/anchor.htm', width : 320 + parseInt(ed.getLang('advanced.anchor_delta_width', 0)), height : 90 + parseInt(ed.getLang('advanced.anchor_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceCharMap : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/charmap.htm', width : 550 + parseInt(ed.getLang('advanced.charmap_delta_width', 0)), height : 265 + parseInt(ed.getLang('advanced.charmap_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceHelp : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/about.htm', width : 480, height : 380, inline : true }, { theme_url : this.url }); }, _mceShortcuts : function() { var ed = this.editor; ed.windowManager.open({ url: this.url + '/shortcuts.htm', width: 480, height: 380, inline: true }, { theme_url: this.url }); }, _mceColorPicker : function(u, v) { var ed = this.editor; v = v || {}; ed.windowManager.open({ url : this.url + '/color_picker.htm', width : 375 + parseInt(ed.getLang('advanced.colorpicker_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.colorpicker_delta_height', 0)), close_previous : false, inline : true }, { input_color : v.color, func : v.func, theme_url : this.url }); }, _mceCodeEditor : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/source_editor.htm', width : parseInt(ed.getParam("theme_advanced_source_editor_width", 720)), height : parseInt(ed.getParam("theme_advanced_source_editor_height", 580)), inline : true, resizable : true, maximizable : true }, { theme_url : this.url }); }, _mceImage : function(ui, val) { var ed = this.editor; // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class', '').indexOf('mceItem') != -1) return; ed.windowManager.open({ url : this.url + '/image.htm', width : 355 + parseInt(ed.getLang('advanced.image_delta_width', 0)), height : 275 + parseInt(ed.getLang('advanced.image_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceLink : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/link.htm', width : 310 + parseInt(ed.getLang('advanced.link_delta_width', 0)), height : 200 + parseInt(ed.getLang('advanced.link_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceNewDocument : function() { var ed = this.editor; ed.windowManager.confirm('advanced.newdocument', function(s) { if (s) ed.execCommand('mceSetContent', false, ''); }); }, _mceForeColor : function() { var t = this; this._mceColorPicker(0, { color: t.fgColor, func : function(co) { t.fgColor = co; t.editor.execCommand('ForeColor', false, co); } }); }, _mceBackColor : function() { var t = this; this._mceColorPicker(0, { color: t.bgColor, func : function(co) { t.bgColor = co; t.editor.execCommand('HiliteColor', false, co); } }); }, _ufirst : function(s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }); tinymce.ThemeManager.add('advanced', tinymce.themes.AdvancedTheme); }(tinymce));
JavaScript
// WordPress, TinyMCE, and Media // ----------------------------- (function($){ // Stores the editors' `wp.media.controller.Frame` instances. var workflows = {}; wp.media.string = { // Joins the `props` and `attachment` objects, // outputting the proper object format based on the // attachment's type. props: function( props, attachment ) { var link, linkUrl, size, sizes, fallbacks, defaultProps = wp.media.view.settings.defaultProps; // Final fallbacks run after all processing has been completed. fallbacks = function( props ) { // Generate alt fallbacks and strip tags. if ( 'image' === props.type && ! props.alt ) { props.alt = props.caption || props.title || ''; props.alt = props.alt.replace( /<\/?[^>]+>/g, '' ); props.alt = props.alt.replace( /[\r\n]+/g, ' ' ); } return props; }; props = props ? _.clone( props ) : {}; if ( attachment && attachment.type ) props.type = attachment.type; if ( 'image' === props.type ) { props = _.defaults( props || {}, { align: defaultProps.align || getUserSetting( 'align', 'none' ), size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ), url: '', classes: [] }); } // All attachment-specific settings follow. if ( ! attachment ) return fallbacks( props ); props.title = props.title || attachment.title; link = props.link || defaultProps.link || getUserSetting( 'urlbutton', 'file' ); if ( 'file' === link || 'embed' === link ) linkUrl = attachment.url; else if ( 'post' === link ) linkUrl = attachment.link; else if ( 'custom' === link ) linkUrl = props.linkUrl; props.linkUrl = linkUrl || ''; // Format properties for images. if ( 'image' === attachment.type ) { props.classes.push( 'wp-image-' + attachment.id ); sizes = attachment.sizes; size = sizes && sizes[ props.size ] ? sizes[ props.size ] : attachment; _.extend( props, _.pick( attachment, 'align', 'caption', 'alt' ), { width: size.width, height: size.height, src: size.url, captionId: 'attachment_' + attachment.id }); } else if ( 'video' === attachment.type || 'audio' === attachment.type ) { _.extend( props, _.pick( attachment, 'title', 'type', 'icon', 'mime' ) ); // Format properties for non-images. } else { props.title = props.title || attachment.filename; props.rel = props.rel || 'attachment wp-att-' + attachment.id; } return fallbacks( props ); }, link: function( props, attachment ) { var options; props = wp.media.string.props( props, attachment ); options = { tag: 'a', content: props.title, attrs: { href: props.linkUrl } }; if ( props.rel ) options.attrs.rel = props.rel; return wp.html.string( options ); }, audio: function( props, attachment ) { return wp.media.string._audioVideo( 'audio', props, attachment ); }, video: function( props, attachment ) { return wp.media.string._audioVideo( 'video', props, attachment ); }, _audioVideo: function( type, props, attachment ) { var shortcode, html, extension; props = wp.media.string.props( props, attachment ); if ( props.link !== 'embed' ) return wp.media.string.link( props ); shortcode = {}; if ( 'video' === type ) { if ( attachment.width ) shortcode.width = attachment.width; if ( attachment.height ) shortcode.height = attachment.height; } extension = attachment.filename.split('.').pop(); if ( _.contains( wp.media.view.settings.embedExts, extension ) ) { shortcode[extension] = attachment.url; } else { // Render unsupported audio and video files as links. return wp.media.string.link( props ); } html = wp.shortcode.string({ tag: type, attrs: shortcode }); return html; }, image: function( props, attachment ) { var img = {}, options, classes, shortcode, html; props = wp.media.string.props( props, attachment ); classes = props.classes || []; img.src = typeof attachment !== 'undefined' ? attachment.url : props.url; _.extend( img, _.pick( props, 'width', 'height', 'alt' ) ); // Only assign the align class to the image if we're not printing // a caption, since the alignment is sent to the shortcode. if ( props.align && ! props.caption ) classes.push( 'align' + props.align ); if ( props.size ) classes.push( 'size-' + props.size ); img['class'] = _.compact( classes ).join(' '); // Generate `img` tag options. options = { tag: 'img', attrs: img, single: true }; // Generate the `a` element options, if they exist. if ( props.linkUrl ) { options = { tag: 'a', attrs: { href: props.linkUrl }, content: options }; } html = wp.html.string( options ); // Generate the caption shortcode. if ( props.caption ) { shortcode = {}; if ( img.width ) shortcode.width = img.width; if ( props.captionId ) shortcode.id = props.captionId; if ( props.align ) shortcode.align = 'align' + props.align; html = wp.shortcode.string({ tag: 'caption', attrs: shortcode, content: html + ' ' + props.caption }); } return html; } }; wp.media.gallery = (function() { var galleries = {}; return { defaults: { order: 'ASC', id: wp.media.view.settings.post.id, itemtag: 'dl', icontag: 'dt', captiontag: 'dd', columns: '3', link: 'post', size: 'thumbnail', orderby: 'menu_order ID' }, attachments: function( shortcode ) { var shortcodeString = shortcode.string(), result = galleries[ shortcodeString ], attrs, args, query, others; delete galleries[ shortcodeString ]; if ( result ) return result; // Fill the default shortcode attributes. attrs = _.defaults( shortcode.attrs.named, wp.media.gallery.defaults ); args = _.pick( attrs, 'orderby', 'order' ); args.type = 'image'; args.perPage = -1; // Mark the `orderby` override attribute. if ( 'rand' === attrs.orderby ) attrs._orderbyRandom = true; // Map the `orderby` attribute to the corresponding model property. if ( ! attrs.orderby || /^menu_order(?: ID)?$/i.test( attrs.orderby ) ) args.orderby = 'menuOrder'; // Map the `ids` param to the correct query args. if ( attrs.ids ) { args.post__in = attrs.ids.split(','); args.orderby = 'post__in'; } else if ( attrs.include ) { args.post__in = attrs.include.split(','); } if ( attrs.exclude ) args.post__not_in = attrs.exclude.split(','); if ( ! args.post__in ) args.uploadedTo = attrs.id; // Collect the attributes that were not included in `args`. others = _.omit( attrs, 'id', 'ids', 'include', 'exclude', 'orderby', 'order' ); query = wp.media.query( args ); query.gallery = new Backbone.Model( others ); return query; }, shortcode: function( attachments ) { var props = attachments.props.toJSON(), attrs = _.pick( props, 'orderby', 'order' ), shortcode, clone; if ( attachments.gallery ) _.extend( attrs, attachments.gallery.toJSON() ); // Convert all gallery shortcodes to use the `ids` property. // Ignore `post__in` and `post__not_in`; the attachments in // the collection will already reflect those properties. attrs.ids = attachments.pluck('id'); // Copy the `uploadedTo` post ID. if ( props.uploadedTo ) attrs.id = props.uploadedTo; // Check if the gallery is randomly ordered. if ( attrs._orderbyRandom ) attrs.orderby = 'rand'; delete attrs._orderbyRandom; // If the `ids` attribute is set and `orderby` attribute // is the default value, clear it for cleaner output. if ( attrs.ids && 'post__in' === attrs.orderby ) delete attrs.orderby; // Remove default attributes from the shortcode. _.each( wp.media.gallery.defaults, function( value, key ) { if ( value === attrs[ key ] ) delete attrs[ key ]; }); shortcode = new wp.shortcode({ tag: 'gallery', attrs: attrs, type: 'single' }); // Use a cloned version of the gallery. clone = new wp.media.model.Attachments( attachments.models, { props: props }); clone.gallery = attachments.gallery; galleries[ shortcode.string() ] = clone; return shortcode; }, edit: function( content ) { var shortcode = wp.shortcode.next( 'gallery', content ), defaultPostId = wp.media.gallery.defaults.id, attachments, selection; // Bail if we didn't match the shortcode or all of the content. if ( ! shortcode || shortcode.content !== content ) return; // Ignore the rest of the match object. shortcode = shortcode.shortcode; if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) ) shortcode.set( 'id', defaultPostId ); attachments = wp.media.gallery.attachments( shortcode ); selection = new wp.media.model.Selection( attachments.models, { props: attachments.props.toJSON(), multiple: true }); selection.gallery = attachments.gallery; // Fetch the query's attachments, and then break ties from the // query to allow for sorting. selection.more().done( function() { // Break ties with the query. selection.props.set({ query: false }); selection.unmirror(); selection.props.unset('orderby'); }); // Destroy the previous gallery frame. if ( this.frame ) this.frame.dispose(); // Store the current gallery frame. this.frame = wp.media({ frame: 'post', state: 'gallery-edit', title: wp.media.view.l10n.editGalleryTitle, editing: true, multiple: true, selection: selection }).open(); return this.frame; } }; }()); wp.media.featuredImage = { get: function() { return wp.media.view.settings.post.featuredImageId; }, set: function( id ) { var settings = wp.media.view.settings; settings.post.featuredImageId = id; wp.media.post( 'set-post-thumbnail', { json: true, post_id: settings.post.id, thumbnail_id: settings.post.featuredImageId, _wpnonce: settings.post.nonce }).done( function( html ) { $( '.inside', '#postimagediv' ).html( html ); }); }, frame: function() { if ( this._frame ) return this._frame; this._frame = wp.media({ state: 'featured-image', states: [ new wp.media.controller.FeaturedImage() ] }); this._frame.on( 'toolbar:create:featured-image', function( toolbar ) { this.createSelectToolbar( toolbar, { text: wp.media.view.l10n.setFeaturedImage }); }, this._frame ); this._frame.state('featured-image').on( 'select', this.select ); return this._frame; }, select: function() { var settings = wp.media.view.settings, selection = this.get('selection').single(); if ( ! settings.post.featuredImageId ) return; wp.media.featuredImage.set( selection ? selection.id : -1 ); }, init: function() { // Open the content media manager to the 'featured image' tab when // the post thumbnail is clicked. $('#postimagediv').on( 'click', '#set-post-thumbnail', function( event ) { event.preventDefault(); // Stop propagation to prevent thickbox from activating. event.stopPropagation(); wp.media.featuredImage.frame().open(); // Update the featured image id when the 'remove' link is clicked. }).on( 'click', '#remove-post-thumbnail', function() { wp.media.view.settings.post.featuredImageId = -1; }); } }; $( wp.media.featuredImage.init ); wp.media.editor = { insert: function( h ) { var mce = typeof(tinymce) != 'undefined', qt = typeof(QTags) != 'undefined', wpActiveEditor = window.wpActiveEditor, ed; // Delegate to the global `send_to_editor` if it exists. // This attempts to play nice with any themes/plugins that have // overridden the insert functionality. if ( window.send_to_editor ) return window.send_to_editor.apply( this, arguments ); if ( ! wpActiveEditor ) { if ( mce && tinymce.activeEditor ) { ed = tinymce.activeEditor; wpActiveEditor = window.wpActiveEditor = ed.id; } else if ( !qt ) { return false; } } else if ( mce ) { if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') ) ed = tinymce.activeEditor; else ed = tinymce.get(wpActiveEditor); } if ( ed && !ed.isHidden() ) { // restore caret position on IE if ( tinymce.isIE && ed.windowManager.insertimagebookmark ) ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark); if ( h.indexOf('[caption') !== -1 ) { if ( ed.wpSetImgCaption ) h = ed.wpSetImgCaption(h); } else if ( h.indexOf('[gallery') !== -1 ) { if ( ed.plugins.wpgallery ) h = ed.plugins.wpgallery._do_gallery(h); } else if ( h.indexOf('[embed') === 0 ) { if ( ed.plugins.wordpress ) h = ed.plugins.wordpress._setEmbed(h); } ed.execCommand('mceInsertContent', false, h); } else if ( qt ) { QTags.insertContent(h); } else { document.getElementById(wpActiveEditor).value += h; } // If the old thickbox remove function exists, call it in case // a theme/plugin overloaded it. if ( window.tb_remove ) try { window.tb_remove(); } catch( e ) {} }, add: function( id, options ) { var workflow = this.get( id ); if ( workflow ) // only add once: if exists return existing return workflow; workflow = workflows[ id ] = wp.media( _.defaults( options || {}, { frame: 'post', state: 'insert', title: wp.media.view.l10n.addMedia, multiple: true } ) ); workflow.on( 'insert', function( selection ) { var state = workflow.state(); selection = selection || state.get('selection'); if ( ! selection ) return; $.when.apply( $, selection.map( function( attachment ) { var display = state.display( attachment ).toJSON(); return this.send.attachment( display, attachment.toJSON() ); }, this ) ).done( function() { wp.media.editor.insert( _.toArray( arguments ).join("\n\n") ); }); }, this ); workflow.state('gallery-edit').on( 'update', function( selection ) { this.insert( wp.media.gallery.shortcode( selection ).string() ); }, this ); workflow.state('embed').on( 'select', function() { var state = workflow.state(), type = state.get('type'), embed = state.props.toJSON(); embed.url = embed.url || ''; if ( 'link' === type ) { _.defaults( embed, { title: embed.url, linkUrl: embed.url }); this.send.link( embed ).done( function( resp ) { wp.media.editor.insert( resp ); }); } else if ( 'image' === type ) { _.defaults( embed, { title: embed.url, linkUrl: '', align: 'none', link: 'none' }); if ( 'none' === embed.link ) embed.linkUrl = ''; else if ( 'file' === embed.link ) embed.linkUrl = embed.url; this.insert( wp.media.string.image( embed ) ); } }, this ); workflow.state('featured-image').on( 'select', wp.media.featuredImage.select ); workflow.setState( workflow.options.state ); return workflow; }, id: function( id ) { if ( id ) return id; // If an empty `id` is provided, default to `wpActiveEditor`. id = wpActiveEditor; // If that doesn't work, fall back to `tinymce.activeEditor.id`. if ( ! id && typeof tinymce !== 'undefined' && tinymce.activeEditor ) id = tinymce.activeEditor.id; // Last but not least, fall back to the empty string. id = id || ''; return id; }, get: function( id ) { id = this.id( id ); return workflows[ id ]; }, remove: function( id ) { id = this.id( id ); delete workflows[ id ]; }, send: { attachment: function( props, attachment ) { var caption = attachment.caption, options, html; // If captions are disabled, clear the caption. if ( ! wp.media.view.settings.captions ) delete attachment.caption; props = wp.media.string.props( props, attachment ); options = { id: attachment.id, post_content: attachment.description, post_excerpt: caption }; if ( props.linkUrl ) options.url = props.linkUrl; if ( 'image' === attachment.type ) { html = wp.media.string.image( props ); _.each({ align: 'align', size: 'image-size', alt: 'image_alt' }, function( option, prop ) { if ( props[ prop ] ) options[ option ] = props[ prop ]; }); } else if ( 'video' === attachment.type ) { html = wp.media.string.video( props, attachment ); } else if ( 'audio' === attachment.type ) { html = wp.media.string.audio( props, attachment ); } else { html = wp.media.string.link( props ); options.post_title = props.title; } return wp.media.post( 'send-attachment-to-editor', { nonce: wp.media.view.settings.nonce.sendToEditor, attachment: options, html: html, post_id: wp.media.view.settings.post.id }); }, link: function( embed ) { return wp.media.post( 'send-link-to-editor', { nonce: wp.media.view.settings.nonce.sendToEditor, src: embed.linkUrl, title: embed.title, html: wp.media.string.link( embed ), post_id: wp.media.view.settings.post.id }); } }, open: function( id, options ) { var workflow, editor; options = options || {}; id = this.id( id ); // Save a bookmark of the caret position in IE. if ( typeof tinymce !== 'undefined' ) { editor = tinymce.get( id ); if ( tinymce.isIE && editor && ! editor.isHidden() ) { editor.focus(); editor.windowManager.insertimagebookmark = editor.selection.getBookmark(); } } workflow = this.get( id ); // Redo workflow if state has changed if ( ! workflow || ( workflow.options && options.state !== workflow.options.state ) ) workflow = this.add( id, options ); return workflow.open(); }, init: function() { $(document.body).on( 'click', '.insert-media', function( event ) { var $this = $(this), editor = $this.data('editor'), options = { frame: 'post', state: 'insert', title: wp.media.view.l10n.addMedia, multiple: true }; event.preventDefault(); // Remove focus from the `.insert-media` button. // Prevents Opera from showing the outline of the button // above the modal. // // See: http://core.trac.wordpress.org/ticket/22445 $this.blur(); if ( $this.hasClass( 'gallery' ) ) { options.state = 'gallery'; options.title = wp.media.view.l10n.createGalleryTitle; } wp.media.editor.open( editor, options ); }); } }; _.bindAll( wp.media.editor, 'open' ); $( wp.media.editor.init ); }(jQuery));
JavaScript
/* http://www.JSON.org/json2.js 2011-02-23 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false, regexp: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON; if (!JSON) { JSON = {}; } (function () { "use strict"; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
JavaScript
/*! * jQuery serializeObject - v0.2 - 1/20/2010 * http://benalman.com/projects/jquery-misc-plugins/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Whereas .serializeArray() serializes a form into an array, .serializeObject() // serializes a form into an (arguably more useful) object. (function($,undefined){ '$:nomunge'; // Used by YUI compressor. $.fn.serializeObject = function(){ var obj = {}; $.each( this.serializeArray(), function(i,o){ var n = o.name, v = o.value; obj[n] = obj[n] === undefined ? v : $.isArray( obj[n] ) ? obj[n].concat( v ) : [ obj[n], v ]; }); return obj; }; })(jQuery);
JavaScript
(function($){$.scheduler=function(){this.bucket={};return;};$.scheduler.prototype={schedule:function(){var ctx={"id":null,"time":1000,"repeat":false,"protect":false,"obj":null,"func":function(){},"args":[]};function _isfn(fn){return(!!fn&&typeof fn!="string"&&typeof fn[0]=="undefined"&&RegExp("function","i").test(fn+""));};var i=0;var override=false;if(typeof arguments[i]=="object"&&arguments.length>1){override=true;i++;} if(typeof arguments[i]=="object"){for(var option in arguments[i]) if(typeof ctx[option]!="undefined") ctx[option]=arguments[i][option];i++;} if(typeof arguments[i]=="number"||(typeof arguments[i]=="string"&&arguments[i].match(RegExp("^[0-9]+[smhdw]$")))) ctx["time"]=arguments[i++];if(typeof arguments[i]=="boolean") ctx["repeat"]=arguments[i++];if(typeof arguments[i]=="boolean") ctx["protect"]=arguments[i++];if(typeof arguments[i]=="object"&&typeof arguments[i+1]=="string"&&_isfn(arguments[i][arguments[i+1]])){ctx["obj"]=arguments[i++];ctx["func"]=arguments[i++];} else if(typeof arguments[i]!="undefined"&&(_isfn(arguments[i])||typeof arguments[i]=="string")) ctx["func"]=arguments[i++];while(typeof arguments[i]!="undefined") ctx["args"].push(arguments[i++]);if(override){if(typeof arguments[1]=="object"){for(var option in arguments[0]) if(typeof ctx[option]!="undefined"&&typeof arguments[1][option]=="undefined") ctx[option]=arguments[0][option];} else{for(var option in arguments[0]) if(typeof ctx[option]!="undefined") ctx[option]=arguments[0][option];} i++;} ctx["_scheduler"]=this;ctx["_handle"]=null;var match=String(ctx["time"]).match(RegExp("^([0-9]+)([smhdw])$"));if(match&&match[0]!="undefined"&&match[1]!="undefined") ctx["time"]=String(parseInt(match[1])*{s:1000,m:1000*60,h:1000*60*60,d:1000*60*60*24,w:1000*60*60*24*7}[match[2]]);if(ctx["id"]==null) ctx["id"]=(String(ctx["repeat"])+":" +String(ctx["protect"])+":" +String(ctx["time"])+":" +String(ctx["obj"])+":" +String(ctx["func"])+":" +String(ctx["args"]));if(ctx["protect"]) if(typeof this.bucket[ctx["id"]]!="undefined") return this.bucket[ctx["id"]];if(!_isfn(ctx["func"])){if(ctx["obj"]!=null&&typeof ctx["obj"]=="object"&&typeof ctx["func"]=="string"&&_isfn(ctx["obj"][ctx["func"]])) ctx["func"]=ctx["obj"][ctx["func"]];else ctx["func"]=eval("function () { "+ctx["func"]+" }");} ctx["_handle"]=this._schedule(ctx);this.bucket[ctx["id"]]=ctx;return ctx;},reschedule:function(ctx){if(typeof ctx=="string") ctx=this.bucket[ctx];ctx["_handle"]=this._schedule(ctx);return ctx;},_schedule:function(ctx){var trampoline=function(){var obj=(ctx["obj"]!=null?ctx["obj"]:ctx);(ctx["func"]).apply(obj,ctx["args"]);if(typeof(ctx["_scheduler"]).bucket[ctx["id"]]!="undefined"&&ctx["repeat"]) (ctx["_scheduler"])._schedule(ctx);else delete(ctx["_scheduler"]).bucket[ctx["id"]];};return setTimeout(trampoline,ctx["time"]);},cancel:function(ctx){if(typeof ctx=="string") ctx=this.bucket[ctx];if(typeof ctx=="object"){clearTimeout(ctx["_handle"]);delete this.bucket[ctx["id"]];}}};$.extend({scheduler$:new $.scheduler(),schedule:function(){return $.scheduler$.schedule.apply($.scheduler$,arguments)},reschedule:function(){return $.scheduler$.reschedule.apply($.scheduler$,arguments)},cancel:function(){return $.scheduler$.cancel.apply($.scheduler$,arguments)}});$.fn.extend({schedule:function(){var a=[{}];for(var i=0;i<arguments.length;i++) a.push(arguments[i]);return this.each(function(){a[0]={"id":this,"obj":this};return $.schedule.apply($,a);});}});})(jQuery);
JavaScript
/****************************************************************************************************************************** * @ Original idea by by Binny V A, Original version: 2.00.A * @ http://www.openjs.com/scripts/events/keyboard_shortcuts/ * @ Original License : BSD * @ jQuery Plugin by Tzury Bar Yochay mail: tzury.by@gmail.com blog: evalinux.wordpress.com face: facebook.com/profile.php?id=513676303 (c) Copyrights 2007 * @ jQuery Plugin version Beta (0.0.2) * @ License: jQuery-License. TODO: add queue support (as in gmail) e.g. 'x' then 'y', etc. add mouse + mouse wheel events. USAGE: $.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');}); $.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});> $.hotkeys.remove('Ctrl+c'); $.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'}); ******************************************************************************************************************************/ (function (jQuery){ this.version = '(beta)(0.0.3)'; this.all = {}; this.special_keys = { 27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12'}; this.shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&", "8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<", ".":">", "/":"?", "\\":"|" }; this.add = function(combi, options, callback) { if (jQuery.isFunction(options)){ callback = options; options = {}; } var opt = {}, defaults = {type: 'keydown', propagate: false, disableInInput: false, target: jQuery('html')[0]}, that = this; opt = jQuery.extend( opt , defaults, options || {} ); combi = combi.toLowerCase(); // inspect if keystroke matches var inspector = function(event) { // WP: not needed with newer jQuery // event = jQuery.event.fix(event); // jQuery event normalization. var element = event.target; // @ TextNode -> nodeType == 3 // WP: not needed with newer jQuery // element = (element.nodeType==3) ? element.parentNode : element; if(opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields var target = jQuery(element); if( target.is("input") || target.is("textarea")){ return; } } var code = event.which, type = event.type, character = String.fromCharCode(code).toLowerCase(), special = that.special_keys[code], shift = event.shiftKey, ctrl = event.ctrlKey, alt= event.altKey, meta = event.metaKey, propagate = true, // default behaivour mapPoint = null; // in opera + safari, the event.target is unpredictable. // for example: 'keydown' might be associated with HtmlBodyElement // or the element where you last clicked with your mouse. // WP: needed for all browsers // if (jQuery.browser.opera || jQuery.browser.safari){ while (!that.all[element] && element.parentNode){ element = element.parentNode; } // } var cbMap = that.all[element].events[type].callbackMap; if(!shift && !ctrl && !alt && !meta) { // No Modifiers mapPoint = cbMap[special] || cbMap[character] } // deals with combinaitons (alt|ctrl|shift+anything) else{ var modif = ''; if(alt) modif +='alt+'; if(ctrl) modif+= 'ctrl+'; if(shift) modif += 'shift+'; if(meta) modif += 'meta+'; // modifiers + special keys or modifiers + characters or modifiers + shift characters mapPoint = cbMap[modif+special] || cbMap[modif+character] || cbMap[modif+that.shift_nums[character]] } if (mapPoint){ mapPoint.cb(event); if(!mapPoint.propagate) { event.stopPropagation(); event.preventDefault(); return false; } } }; // first hook for this element if (!this.all[opt.target]){ this.all[opt.target] = {events:{}}; } if (!this.all[opt.target].events[opt.type]){ this.all[opt.target].events[opt.type] = {callbackMap: {}} jQuery.event.add(opt.target, opt.type, inspector); } this.all[opt.target].events[opt.type].callbackMap[combi] = {cb: callback, propagate:opt.propagate}; return jQuery; }; this.remove = function(exp, opt) { opt = opt || {}; target = opt.target || jQuery('html')[0]; type = opt.type || 'keydown'; exp = exp.toLowerCase(); delete this.all[target].events[type].callbackMap[exp] return jQuery; }; jQuery.hotkeys = this; return jQuery; })(jQuery);
JavaScript
/*! * jQuery Form Plugin * version: 2.73 (03-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) : ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } url = url || window.location.href || ''; 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, fileUpload); } else { fileUpload(); } } 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() { var form = $form[0]; 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; } var s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id; var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var 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); } }; var 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; } var timedOut = 0, timeoutHandle; // add submitting element to data if we know it var sub = form.clk; if (sub) { var 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]); } } // 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 ok = true; 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'); xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.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]; }; var scr = /(json|script|text)/.test(s.dataType); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; } 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; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = httpData(xhr, s.dataType, s); } catch(e){ log('error caught:',e); ok = false; xhr.error = e; s.error && s.error.call(s.context, xhr, 'error', e); g && $.event.trigger("ajaxError", [xhr, s, e]); } if (xhr.aborted) { log('upload aborted'); ok = false; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error'); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { $io.removeData('form-plugin-onload'); $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 // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug) { 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
(function($){ $.fn.filter_visible = function(depth) { depth = depth || 3; var is_visible = function() { var p = $(this), i; for(i=0; i<depth-1; ++i) { if (!p.is(':visible')) return false; p = p.parent(); } return true; } return this.filter(is_visible); }; $.table_hotkeys = function(table, keys, opts) { opts = $.extend($.table_hotkeys.defaults, opts); var selected_class, destructive_class, set_current_row, adjacent_row_callback, get_adjacent_row, adjacent_row, prev_row, next_row, check, get_first_row, get_last_row, make_key_callback, first_row; selected_class = opts.class_prefix + opts.selected_suffix; destructive_class = opts.class_prefix + opts.destructive_suffix set_current_row = function (tr) { if ($.table_hotkeys.current_row) $.table_hotkeys.current_row.removeClass(selected_class); tr.addClass(selected_class); tr[0].scrollIntoView(false); $.table_hotkeys.current_row = tr; }; adjacent_row_callback = function(which) { if (!adjacent_row(which) && $.isFunction(opts[which+'_page_link_cb'])) { opts[which+'_page_link_cb'](); } }; get_adjacent_row = function(which) { var first_row, method; if (!$.table_hotkeys.current_row) { first_row = get_first_row(); $.table_hotkeys.current_row = first_row; return first_row[0]; } method = 'prev' == which? $.fn.prevAll : $.fn.nextAll; return method.call($.table_hotkeys.current_row, opts.cycle_expr).filter_visible()[0]; }; adjacent_row = function(which) { var adj = get_adjacent_row(which); if (!adj) return false; set_current_row($(adj)); return true; }; prev_row = function() { return adjacent_row('prev'); }; next_row = function() { return adjacent_row('next'); }; check = function() { $(opts.checkbox_expr, $.table_hotkeys.current_row).each(function() { this.checked = !this.checked; }); }; get_first_row = function() { return $(opts.cycle_expr, table).filter_visible().eq(opts.start_row_index); }; get_last_row = function() { var rows = $(opts.cycle_expr, table).filter_visible(); return rows.eq(rows.length-1); }; make_key_callback = function(expr) { return function() { if ( null == $.table_hotkeys.current_row ) return false; var clickable = $(expr, $.table_hotkeys.current_row); if (!clickable.length) return false; if (clickable.is('.'+destructive_class)) next_row() || prev_row(); clickable.click(); } }; first_row = get_first_row(); if (!first_row.length) return; if (opts.highlight_first) set_current_row(first_row); else if (opts.highlight_last) set_current_row(get_last_row()); $.hotkeys.add(opts.prev_key, opts.hotkeys_opts, function() {return adjacent_row_callback('prev')}); $.hotkeys.add(opts.next_key, opts.hotkeys_opts, function() {return adjacent_row_callback('next')}); $.hotkeys.add(opts.mark_key, opts.hotkeys_opts, check); $.each(keys, function() { var callback, key; if ($.isFunction(this[1])) { callback = this[1]; key = this[0]; $.hotkeys.add(key, opts.hotkeys_opts, function(event) { return callback(event, $.table_hotkeys.current_row); }); } else { key = this; $.hotkeys.add(key, opts.hotkeys_opts, make_key_callback('.'+opts.class_prefix+key)); } }); }; $.table_hotkeys.current_row = null; $.table_hotkeys.defaults = {cycle_expr: 'tr', class_prefix: 'vim-', selected_suffix: 'current', destructive_suffix: 'destructive', hotkeys_opts: {disableInInput: true, type: 'keypress'}, checkbox_expr: ':checkbox', next_key: 'j', prev_key: 'k', mark_key: 'x', start_row_index: 2, highlight_first: false, highlight_last: false, next_page_link_cb: false, prev_page_link_cb: false}; })(jQuery);
JavaScript
window.wp = window.wp || {}; (function($){ var Attachment, Attachments, Query, compare, l10n, media; /** * wp.media( attributes ) * * Handles the default media experience. Automatically creates * and opens a media frame, and returns the result. * Does nothing if the controllers do not exist. * * @param {object} attributes The properties passed to the main media controller. * @return {object} A media workflow. */ media = wp.media = function( attributes ) { var MediaFrame = media.view.MediaFrame, frame; if ( ! MediaFrame ) return; attributes = _.defaults( attributes || {}, { frame: 'select' }); if ( 'select' === attributes.frame && MediaFrame.Select ) frame = new MediaFrame.Select( attributes ); else if ( 'post' === attributes.frame && MediaFrame.Post ) frame = new MediaFrame.Post( attributes ); delete attributes.frame; return frame; }; _.extend( media, { model: {}, view: {}, controller: {}, frames: {} }); // Link any localized strings. l10n = media.model.l10n = typeof _wpMediaModelsL10n === 'undefined' ? {} : _wpMediaModelsL10n; // Link any settings. media.model.settings = l10n.settings || {}; delete l10n.settings; /** * ======================================================================== * UTILITIES * ======================================================================== */ /** * A basic comparator. * * @param {mixed} a The primary parameter to compare. * @param {mixed} b The primary parameter to compare. * @param {string} ac The fallback parameter to compare, a's cid. * @param {string} bc The fallback parameter to compare, b's cid. * @return {number} -1: a should come before b. * 0: a and b are of the same rank. * 1: b should come before a. */ compare = function( a, b, ac, bc ) { if ( _.isEqual( a, b ) ) return ac === bc ? 0 : (ac > bc ? -1 : 1); else return a > b ? -1 : 1; }; _.extend( media, { /** * media.template( id ) * * Fetches a template by id. * See wp.template() in `wp-includes/js/wp-util.js`. */ template: wp.template, /** * media.post( [action], [data] ) * * Sends a POST request to WordPress. * See wp.ajax.post() in `wp-includes/js/wp-util.js`. */ post: wp.ajax.post, /** * media.ajax( [action], [options] ) * * Sends an XHR request to WordPress. * See wp.ajax.send() in `wp-includes/js/wp-util.js`. */ ajax: wp.ajax.send, // Scales a set of dimensions to fit within bounding dimensions. fit: function( dimensions ) { var width = dimensions.width, height = dimensions.height, maxWidth = dimensions.maxWidth, maxHeight = dimensions.maxHeight, constraint; // Compare ratios between the two values to determine which // max to constrain by. If a max value doesn't exist, then the // opposite side is the constraint. if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) { constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height'; } else if ( _.isUndefined( maxHeight ) ) { constraint = 'width'; } else if ( _.isUndefined( maxWidth ) && height > maxHeight ) { constraint = 'height'; } // If the value of the constrained side is larger than the max, // then scale the values. Otherwise return the originals; they fit. if ( 'width' === constraint && width > maxWidth ) { return { width : maxWidth, height: Math.round( maxWidth * height / width ) }; } else if ( 'height' === constraint && height > maxHeight ) { return { width : Math.round( maxHeight * width / height ), height: maxHeight }; } else { return { width : width, height: height }; } }, // Truncates a string by injecting an ellipsis into the middle. // Useful for filenames. truncate: function( string, length, replacement ) { length = length || 30; replacement = replacement || '&hellip;'; if ( string.length <= length ) return string; return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 ); } }); /** * ======================================================================== * MODELS * ======================================================================== */ /** * wp.media.attachment */ media.attachment = function( id ) { return Attachment.get( id ); }; /** * wp.media.model.Attachment */ Attachment = media.model.Attachment = Backbone.Model.extend({ sync: function( method, model, options ) { // If the attachment does not yet have an `id`, return an instantly // rejected promise. Otherwise, all of our requests will fail. if ( _.isUndefined( this.id ) ) return $.Deferred().rejectWith( this ).promise(); // Overload the `read` request so Attachment.fetch() functions correctly. if ( 'read' === method ) { options = options || {}; options.context = this; options.data = _.extend( options.data || {}, { action: 'get-attachment', id: this.id }); return media.ajax( options ); // Overload the `update` request so properties can be saved. } else if ( 'update' === method ) { // If we do not have the necessary nonce, fail immeditately. if ( ! this.get('nonces') || ! this.get('nonces').update ) return $.Deferred().rejectWith( this ).promise(); options = options || {}; options.context = this; // Set the action and ID. options.data = _.extend( options.data || {}, { action: 'save-attachment', id: this.id, nonce: this.get('nonces').update, post_id: media.model.settings.post.id }); // Record the values of the changed attributes. if ( model.hasChanged() ) { options.data.changes = {}; _.each( model.changed, function( value, key ) { options.data.changes[ key ] = this.get( key ); }, this ); } return media.ajax( options ); // Overload the `delete` request so attachments can be removed. // This will permanently delete an attachment. } else if ( 'delete' === method ) { options = options || {}; if ( ! options.wait ) this.destroyed = true; options.context = this; options.data = _.extend( options.data || {}, { action: 'delete-post', id: this.id, _wpnonce: this.get('nonces')['delete'] }); return media.ajax( options ).done( function() { this.destroyed = true; }).fail( function() { this.destroyed = false; }); // Otherwise, fall back to `Backbone.sync()`. } else { return Backbone.Model.prototype.sync.apply( this, arguments ); } }, parse: function( resp, xhr ) { if ( ! resp ) return resp; // Convert date strings into Date objects. resp.date = new Date( resp.date ); resp.modified = new Date( resp.modified ); return resp; }, saveCompat: function( data, options ) { var model = this; // If we do not have the necessary nonce, fail immeditately. if ( ! this.get('nonces') || ! this.get('nonces').update ) return $.Deferred().rejectWith( this ).promise(); return media.post( 'save-attachment-compat', _.defaults({ id: this.id, nonce: this.get('nonces').update, post_id: media.model.settings.post.id }, data ) ).done( function( resp, status, xhr ) { model.set( model.parse( resp, xhr ), options ); }); } }, { create: function( attrs ) { return Attachments.all.push( attrs ); }, get: _.memoize( function( id, attachment ) { return Attachments.all.push( attachment || { id: id } ); }) }); /** * wp.media.model.Attachments */ Attachments = media.model.Attachments = Backbone.Collection.extend({ model: Attachment, initialize: function( models, options ) { options = options || {}; this.props = new Backbone.Model(); this.filters = options.filters || {}; // Bind default `change` events to the `props` model. this.props.on( 'change', this._changeFilteredProps, this ); this.props.on( 'change:order', this._changeOrder, this ); this.props.on( 'change:orderby', this._changeOrderby, this ); this.props.on( 'change:query', this._changeQuery, this ); // Set the `props` model and fill the default property values. this.props.set( _.defaults( options.props || {} ) ); // Observe another `Attachments` collection if one is provided. if ( options.observe ) this.observe( options.observe ); }, // Automatically sort the collection when the order changes. _changeOrder: function( model, order ) { if ( this.comparator ) this.sort(); }, // Set the default comparator only when the `orderby` property is set. _changeOrderby: function( model, orderby ) { // If a different comparator is defined, bail. if ( this.comparator && this.comparator !== Attachments.comparator ) return; if ( orderby && 'post__in' !== orderby ) this.comparator = Attachments.comparator; else delete this.comparator; }, // If the `query` property is set to true, query the server using // the `props` values, and sync the results to this collection. _changeQuery: function( model, query ) { if ( query ) { this.props.on( 'change', this._requery, this ); this._requery(); } else { this.props.off( 'change', this._requery, this ); } }, _changeFilteredProps: function( model, options ) { // If this is a query, updating the collection will be handled by // `this._requery()`. if ( this.props.get('query') ) return; var changed = _.chain( model.changed ).map( function( t, prop ) { var filter = Attachments.filters[ prop ], term = model.get( prop ); if ( ! filter ) return; if ( term && ! this.filters[ prop ] ) this.filters[ prop ] = filter; else if ( ! term && this.filters[ prop ] === filter ) delete this.filters[ prop ]; else return; // Record the change. return true; }, this ).any().value(); if ( ! changed ) return; // If no `Attachments` model is provided to source the searches // from, then automatically generate a source from the existing // models. if ( ! this._source ) this._source = new Attachments( this.models ); this.reset( this._source.filter( this.validator, this ) ); }, validateDestroyed: false, validator: function( attachment ) { if ( ! this.validateDestroyed && attachment.destroyed ) return false; return _.all( this.filters, function( filter, key ) { return !! filter.call( this, attachment ); }, this ); }, validate: function( attachment, options ) { var valid = this.validator( attachment ), hasAttachment = !! this.get( attachment.cid ); if ( ! valid && hasAttachment ) this.remove( attachment, options ); else if ( valid && ! hasAttachment ) this.add( attachment, options ); return this; }, validateAll: function( attachments, options ) { options = options || {}; _.each( attachments.models, function( attachment ) { this.validate( attachment, { silent: true }); }, this ); if ( ! options.silent ) this.trigger( 'reset', this, options ); return this; }, observe: function( attachments ) { this.observers = this.observers || []; this.observers.push( attachments ); attachments.on( 'add change remove', this._validateHandler, this ); attachments.on( 'reset', this._validateAllHandler, this ); this.validateAll( attachments ); return this; }, unobserve: function( attachments ) { if ( attachments ) { attachments.off( null, null, this ); this.observers = _.without( this.observers, attachments ); } else { _.each( this.observers, function( attachments ) { attachments.off( null, null, this ); }, this ); delete this.observers; } return this; }, _validateHandler: function( attachment, attachments, options ) { // If we're not mirroring this `attachments` collection, // only retain the `silent` option. options = attachments === this.mirroring ? options : { silent: options && options.silent }; return this.validate( attachment, options ); }, _validateAllHandler: function( attachments, options ) { return this.validateAll( attachments, options ); }, mirror: function( attachments ) { if ( this.mirroring && this.mirroring === attachments ) return this; this.unmirror(); this.mirroring = attachments; // Clear the collection silently. A `reset` event will be fired // when `observe()` calls `validateAll()`. this.reset( [], { silent: true } ); this.observe( attachments ); return this; }, unmirror: function() { if ( ! this.mirroring ) return; this.unobserve( this.mirroring ); delete this.mirroring; }, more: function( options ) { var deferred = $.Deferred(), mirroring = this.mirroring, attachments = this; if ( ! mirroring || ! mirroring.more ) return deferred.resolveWith( this ).promise(); // If we're mirroring another collection, forward `more` to // the mirrored collection. Account for a race condition by // checking if we're still mirroring that collection when // the request resolves. mirroring.more( options ).done( function() { if ( this === attachments.mirroring ) deferred.resolveWith( this ); }); return deferred.promise(); }, hasMore: function() { return this.mirroring ? this.mirroring.hasMore() : false; }, parse: function( resp, xhr ) { if ( ! _.isArray( resp ) ) resp = [resp]; return _.map( resp, function( attrs ) { var id, attachment, newAttributes; if ( attrs instanceof Backbone.Model ) { id = attrs.get( 'id' ); attrs = attrs.attributes; } else { id = attrs.id; } attachment = Attachment.get( id ); newAttributes = attachment.parse( attrs, xhr ); if ( ! _.isEqual( attachment.attributes, newAttributes ) ) attachment.set( newAttributes ); return attachment; }); }, _requery: function() { if ( this.props.get('query') ) this.mirror( Query.get( this.props.toJSON() ) ); }, // If this collection is sorted by `menuOrder`, recalculates and saves // the menu order to the database. saveMenuOrder: function() { if ( 'menuOrder' !== this.props.get('orderby') ) return; // Removes any uploading attachments, updates each attachment's // menu order, and returns an object with an { id: menuOrder } // mapping to pass to the request. var attachments = this.chain().filter( function( attachment ) { return ! _.isUndefined( attachment.id ); }).map( function( attachment, index ) { // Indices start at 1. index = index + 1; attachment.set( 'menuOrder', index ); return [ attachment.id, index ]; }).object().value(); if ( _.isEmpty( attachments ) ) return; return media.post( 'save-attachment-order', { nonce: media.model.settings.post.nonce, post_id: media.model.settings.post.id, attachments: attachments }); } }, { comparator: function( a, b, options ) { var key = this.props.get('orderby'), order = this.props.get('order') || 'DESC', ac = a.cid, bc = b.cid; a = a.get( key ); b = b.get( key ); if ( 'date' === key || 'modified' === key ) { a = a || new Date(); b = b || new Date(); } // If `options.ties` is set, don't enforce the `cid` tiebreaker. if ( options && options.ties ) ac = bc = null; return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac ); }, filters: { // Note that this client-side searching is *not* equivalent // to our server-side searching. search: function( attachment ) { if ( ! this.props.get('search') ) return true; return _.any(['title','filename','description','caption','name'], function( key ) { var value = attachment.get( key ); return value && -1 !== value.search( this.props.get('search') ); }, this ); }, type: function( attachment ) { var type = this.props.get('type'); return ! type || -1 !== type.indexOf( attachment.get('type') ); }, uploadedTo: function( attachment ) { var uploadedTo = this.props.get('uploadedTo'); if ( _.isUndefined( uploadedTo ) ) return true; return uploadedTo === attachment.get('uploadedTo'); } } }); Attachments.all = new Attachments(); /** * wp.media.query */ media.query = function( props ) { return new Attachments( null, { props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } ) }); }; /** * wp.media.model.Query * * A set of attachments that corresponds to a set of consecutively paged * queries on the server. * * Note: Do NOT change this.args after the query has been initialized. * Things will break. */ Query = media.model.Query = Attachments.extend({ initialize: function( models, options ) { var allowed; options = options || {}; Attachments.prototype.initialize.apply( this, arguments ); this.args = options.args; this._hasMore = true; this.created = new Date(); this.filters.order = function( attachment ) { var orderby = this.props.get('orderby'), order = this.props.get('order'); if ( ! this.comparator ) return true; // We want any items that can be placed before the last // item in the set. If we add any items after the last // item, then we can't guarantee the set is complete. if ( this.length ) { return 1 !== this.comparator( attachment, this.last(), { ties: true }); // Handle the case where there are no items yet and // we're sorting for recent items. In that case, we want // changes that occurred after we created the query. } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) { return attachment.get( orderby ) >= this.created; // If we're sorting by menu order and we have no items, // accept any items that have the default menu order (0). } else if ( 'ASC' === order && 'menuOrder' === orderby ) { return attachment.get( orderby ) === 0; } // Otherwise, we don't want any items yet. return false; }; // Observe the central `wp.Uploader.queue` collection to watch for // new matches for the query. // // Only observe when a limited number of query args are set. There // are no filters for other properties, so observing will result in // false positives in those queries. allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ]; if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() ) this.observe( wp.Uploader.queue ); }, hasMore: function() { return this._hasMore; }, more: function( options ) { var query = this; if ( this._more && 'pending' === this._more.state() ) return this._more; if ( ! this.hasMore() ) return $.Deferred().resolveWith( this ).promise(); options = options || {}; options.remove = false; return this._more = this.fetch( options ).done( function( resp ) { if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page ) query._hasMore = false; }); }, sync: function( method, model, options ) { var fallback; // Overload the read method so Attachment.fetch() functions correctly. if ( 'read' === method ) { options = options || {}; options.context = this; options.data = _.extend( options.data || {}, { action: 'query-attachments', post_id: media.model.settings.post.id }); // Clone the args so manipulation is non-destructive. args = _.clone( this.args ); // Determine which page to query. if ( -1 !== args.posts_per_page ) args.paged = Math.floor( this.length / args.posts_per_page ) + 1; options.data.query = args; return media.ajax( options ); // Otherwise, fall back to Backbone.sync() } else { fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone; return fallback.sync.apply( this, arguments ); } } }, { defaultProps: { orderby: 'date', order: 'DESC' }, defaultArgs: { posts_per_page: 40 }, orderby: { allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ], valuemap: { 'id': 'ID', 'uploadedTo': 'parent', 'menuOrder': 'menu_order ID' } }, propmap: { 'search': 's', 'type': 'post_mime_type', 'perPage': 'posts_per_page', 'menuOrder': 'menu_order', 'uploadedTo': 'post_parent' }, // Caches query objects so queries can be easily reused. get: (function(){ var queries = []; return function( props, options ) { var args = {}, orderby = Query.orderby, defaults = Query.defaultProps, query; // Remove the `query` property. This isn't linked to a query, // this *is* the query. delete props.query; // Fill default args. _.defaults( props, defaults ); // Normalize the order. props.order = props.order.toUpperCase(); if ( 'DESC' !== props.order && 'ASC' !== props.order ) props.order = defaults.order.toUpperCase(); // Ensure we have a valid orderby value. if ( ! _.contains( orderby.allowed, props.orderby ) ) props.orderby = defaults.orderby; // Generate the query `args` object. // Correct any differing property names. _.each( props, function( value, prop ) { if ( _.isNull( value ) ) return; args[ Query.propmap[ prop ] || prop ] = value; }); // Fill any other default query args. _.defaults( args, Query.defaultArgs ); // `props.orderby` does not always map directly to `args.orderby`. // Substitute exceptions specified in orderby.keymap. args.orderby = orderby.valuemap[ props.orderby ] || props.orderby; // Search the query cache for matches. query = _.find( queries, function( query ) { return _.isEqual( query.args, args ); }); // Otherwise, create a new query and add it to the cache. if ( ! query ) { query = new Query( [], _.extend( options || {}, { props: props, args: args } ) ); queries.push( query ); } return query; }; }()) }); /** * wp.media.model.Selection * * Used to manage a selection of attachments in the views. */ media.model.Selection = Attachments.extend({ initialize: function( models, options ) { Attachments.prototype.initialize.apply( this, arguments ); this.multiple = options && options.multiple; // Refresh the `single` model whenever the selection changes. // Binds `single` instead of using the context argument to ensure // it receives no parameters. this.on( 'add remove reset', _.bind( this.single, this, false ) ); }, // Override the selection's add method. // If the workflow does not support multiple // selected attachments, reset the selection. add: function( models, options ) { if ( ! this.multiple ) this.remove( this.models ); return Attachments.prototype.add.call( this, models, options ); }, single: function( model ) { var previous = this._single; // If a `model` is provided, use it as the single model. if ( model ) this._single = model; // If the single model isn't in the selection, remove it. if ( this._single && ! this.get( this._single.cid ) ) delete this._single; this._single = this._single || this.last(); // If single has changed, fire an event. if ( this._single !== previous ) { if ( previous ) { previous.trigger( 'selection:unsingle', previous, this ); // If the model was already removed, trigger the collection // event manually. if ( ! this.get( previous.cid ) ) this.trigger( 'selection:unsingle', previous, this ); } if ( this._single ) this._single.trigger( 'selection:single', this._single, this ); } // Return the single model, or the last model as a fallback. return this._single; } }); // Clean up. Prevents mobile browsers caching $(window).on('unload', function(){ window.wp = null; }); }(jQuery));
JavaScript
/* * Quicktags * * This is the HTML editor in WordPress. It can be attached to any textarea and will * append a toolbar above it. This script is self-contained (does not require external libraries). * * Run quicktags(settings) to initialize it, where settings is an object containing up to 3 properties: * settings = { * id : 'my_id', the HTML ID of the textarea, required * buttons: '' Comma separated list of the names of the default buttons to show. Optional. * Current list of default button names: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close'; * } * * The settings can also be a string quicktags_id. * * quicktags_id string The ID of the textarea that will be the editor canvas * buttons string Comma separated list of the default buttons names that will be shown in that instance. */ // new edit toolbar used with permission // by Alex King // http://www.alexking.org/ var QTags, edButtons = [], edCanvas, /** * Back-compat * * Define all former global functions so plugins that hack quicktags.js directly don't cause fatal errors. */ edAddTag = function(){}, edCheckOpenTags = function(){}, edCloseAllTags = function(){}, edInsertImage = function(){}, edInsertLink = function(){}, edInsertTag = function(){}, edLink = function(){}, edQuickLink = function(){}, edRemoveTag = function(){}, edShowButton = function(){}, edShowLinks = function(){}, edSpell = function(){}, edToolbar = function(){}; /** * Initialize new instance of the Quicktags editor */ function quicktags(settings) { return new QTags(settings); } /** * Inserts content at the caret in the active editor (textarea) * * Added for back compatibility * @see QTags.insertContent() */ function edInsertContent(bah, txt) { return QTags.insertContent(txt); } /** * Adds a button to all instances of the editor * * Added for back compatibility, use QTags.addButton() as it gives more flexibility like type of button, button placement, etc. * @see QTags.addButton() */ function edButton(id, display, tagStart, tagEnd, access, open) { return QTags.addButton( id, display, tagStart, tagEnd, access, '', -1 ); } (function(){ // private stuff is prefixed with an underscore var _domReady = function(func) { var t, i, DOMContentLoaded; if ( typeof jQuery != 'undefined' ) { jQuery(document).ready(func); } else { t = _domReady; t.funcs = []; t.ready = function() { if ( ! t.isReady ) { t.isReady = true; for ( i = 0; i < t.funcs.length; i++ ) { t.funcs[i](); } } }; if ( t.isReady ) { func(); } else { t.funcs.push(func); } if ( ! t.eventAttached ) { if ( document.addEventListener ) { DOMContentLoaded = function(){document.removeEventListener('DOMContentLoaded', DOMContentLoaded, false);t.ready();}; document.addEventListener('DOMContentLoaded', DOMContentLoaded, false); window.addEventListener('load', t.ready, false); } else if ( document.attachEvent ) { DOMContentLoaded = function(){if (document.readyState === 'complete'){ document.detachEvent('onreadystatechange', DOMContentLoaded);t.ready();}}; document.attachEvent('onreadystatechange', DOMContentLoaded); window.attachEvent('onload', t.ready); (function(){ try { document.documentElement.doScroll("left"); } catch(e) { setTimeout(arguments.callee, 50); return; } t.ready(); })(); } t.eventAttached = true; } } }, _datetime = (function() { var now = new Date(), zeroise; zeroise = function(number) { var str = number.toString(); if ( str.length < 2 ) str = "0" + str; return str; } return now.getUTCFullYear() + '-' + zeroise( now.getUTCMonth() + 1 ) + '-' + zeroise( now.getUTCDate() ) + 'T' + zeroise( now.getUTCHours() ) + ':' + zeroise( now.getUTCMinutes() ) + ':' + zeroise( now.getUTCSeconds() ) + '+00:00'; })(), qt; qt = QTags = function(settings) { if ( typeof(settings) == 'string' ) settings = {id: settings}; else if ( typeof(settings) != 'object' ) return false; var t = this, id = settings.id, canvas = document.getElementById(id), name = 'qt_' + id, tb, onclick, toolbar_id; if ( !id || !canvas ) return false; t.name = name; t.id = id; t.canvas = canvas; t.settings = settings; if ( id == 'content' && typeof(adminpage) == 'string' && ( adminpage == 'post-new-php' || adminpage == 'post-php' ) ) { // back compat hack :-( edCanvas = canvas; toolbar_id = 'ed_toolbar'; } else { toolbar_id = name + '_toolbar'; } tb = document.createElement('div'); tb.id = toolbar_id; tb.className = 'quicktags-toolbar'; canvas.parentNode.insertBefore(tb, canvas); t.toolbar = tb; // listen for click events onclick = function(e) { e = e || window.event; var target = e.target || e.srcElement, visible = target.clientWidth || target.offsetWidth, i; // don't call the callback on pressing the accesskey when the button is not visible if ( !visible ) return; // as long as it has the class ed_button, execute the callback if ( / ed_button /.test(' ' + target.className + ' ') ) { // we have to reassign canvas here t.canvas = canvas = document.getElementById(id); i = target.id.replace(name + '_', ''); if ( t.theButtons[i] ) t.theButtons[i].callback.call(t.theButtons[i], target, canvas, t); } }; if ( tb.addEventListener ) { tb.addEventListener('click', onclick, false); } else if ( tb.attachEvent ) { tb.attachEvent('onclick', onclick); } t.getButton = function(id) { return t.theButtons[id]; }; t.getButtonElement = function(id) { return document.getElementById(name + '_' + id); }; qt.instances[id] = t; if ( !qt.instances[0] ) { qt.instances[0] = qt.instances[id]; _domReady( function(){ qt._buttonsInit(); } ); } }; qt.instances = {}; qt.getInstance = function(id) { return qt.instances[id]; }; qt._buttonsInit = function() { var t = this, canvas, name, settings, theButtons, html, inst, ed, id, i, use, defaults = ',strong,em,link,block,del,ins,img,ul,ol,li,code,more,close,'; for ( inst in t.instances ) { if ( inst == 0 ) continue; ed = t.instances[inst]; canvas = ed.canvas; name = ed.name; settings = ed.settings; html = ''; theButtons = {}; use = ''; // set buttons if ( settings.buttons ) use = ','+settings.buttons+','; for ( i in edButtons ) { if ( !edButtons[i] ) continue; id = edButtons[i].id; if ( use && defaults.indexOf(','+id+',') != -1 && use.indexOf(','+id+',') == -1 ) continue; if ( !edButtons[i].instance || edButtons[i].instance == inst ) { theButtons[id] = edButtons[i]; if ( edButtons[i].html ) html += edButtons[i].html(name + '_'); } } if ( use && use.indexOf(',fullscreen,') != -1 ) { theButtons['fullscreen'] = new qt.FullscreenButton(); html += theButtons['fullscreen'].html(name + '_'); } if ( 'rtl' == document.getElementsByTagName('html')[0].dir ) { theButtons['textdirection'] = new qt.TextDirectionButton(); html += theButtons['textdirection'].html(name + '_'); } ed.toolbar.innerHTML = html; ed.theButtons = theButtons; } t.buttonsInitDone = true; }; /** * Main API function for adding a button to Quicktags * * Adds qt.Button or qt.TagButton depending on the args. The first three args are always required. * To be able to add button(s) to Quicktags, your script should be enqueued as dependent * on "quicktags" and outputted in the footer. If you are echoing JS directly from PHP, * use add_action( 'admin_print_footer_scripts', 'output_my_js', 100 ) or add_action( 'wp_footer', 'output_my_js', 100 ) * * Minimum required to add a button that calls an external function: * QTags.addButton( 'my_id', 'my button', my_callback ); * function my_callback() { alert('yeah!'); } * * Minimum required to add a button that inserts a tag: * QTags.addButton( 'my_id', 'my button', '<span>', '</span>' ); * QTags.addButton( 'my_id2', 'my button', '<br />' ); * * @param string id Required. Button HTML ID * @param string display Required. Button's value="..." * @param string|function arg1 Required. Either a starting tag to be inserted like "<span>" or a callback that is executed when the button is clicked. * @param string arg2 Optional. Ending tag like "</span>" * @param string access_key Optional. Access key for the button. * @param string title Optional. Button's title="..." * @param int priority Optional. Number representing the desired position of the button in the toolbar. 1 - 9 = first, 11 - 19 = second, 21 - 29 = third, etc. * @param string instance Optional. Limit the button to a specifric instance of Quicktags, add to all instances if not present. * @return mixed null or the button object that is needed for back-compat. */ qt.addButton = function( id, display, arg1, arg2, access_key, title, priority, instance ) { var btn; if ( !id || !display ) return; priority = priority || 0; arg2 = arg2 || ''; if ( typeof(arg1) === 'function' ) { btn = new qt.Button(id, display, access_key, title, instance); btn.callback = arg1; } else if ( typeof(arg1) === 'string' ) { btn = new qt.TagButton(id, display, arg1, arg2, access_key, title, instance); } else { return; } if ( priority == -1 ) // back-compat return btn; if ( priority > 0 ) { while ( typeof(edButtons[priority]) != 'undefined' ) { priority++ } edButtons[priority] = btn; } else { edButtons[edButtons.length] = btn; } if ( this.buttonsInitDone ) this._buttonsInit(); // add the button HTML to all instances toolbars if addButton() was called too late }; qt.insertContent = function(content) { var sel, startPos, endPos, scrollTop, text, canvas = document.getElementById(wpActiveEditor); if ( !canvas ) return false; if ( document.selection ) { //IE canvas.focus(); sel = document.selection.createRange(); sel.text = content; canvas.focus(); } else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera text = canvas.value; startPos = canvas.selectionStart; endPos = canvas.selectionEnd; scrollTop = canvas.scrollTop; canvas.value = text.substring(0, startPos) + content + text.substring(endPos, text.length); canvas.focus(); canvas.selectionStart = startPos + content.length; canvas.selectionEnd = startPos + content.length; canvas.scrollTop = scrollTop; } else { canvas.value += content; canvas.focus(); } return true; }; // a plain, dumb button qt.Button = function(id, display, access, title, instance) { var t = this; t.id = id; t.display = display; t.access = access; t.title = title || ''; t.instance = instance || ''; }; qt.Button.prototype.html = function(idPrefix) { var access = this.access ? ' accesskey="' + this.access + '"' : ''; return '<input type="button" id="' + idPrefix + this.id + '"' + access + ' class="ed_button" title="' + this.title + '" value="' + this.display + '" />'; }; qt.Button.prototype.callback = function(){}; // a button that inserts HTML tag qt.TagButton = function(id, display, tagStart, tagEnd, access, title, instance) { var t = this; qt.Button.call(t, id, display, access, title, instance); t.tagStart = tagStart; t.tagEnd = tagEnd; }; qt.TagButton.prototype = new qt.Button(); qt.TagButton.prototype.openTag = function(e, ed) { var t = this; if ( ! ed.openTags ) { ed.openTags = []; } if ( t.tagEnd ) { ed.openTags.push(t.id); e.value = '/' + e.value; } }; qt.TagButton.prototype.closeTag = function(e, ed) { var t = this, i = t.isOpen(ed); if ( i !== false ) { ed.openTags.splice(i, 1); } e.value = t.display; }; // whether a tag is open or not. Returns false if not open, or current open depth of the tag qt.TagButton.prototype.isOpen = function (ed) { var t = this, i = 0, ret = false; if ( ed.openTags ) { while ( ret === false && i < ed.openTags.length ) { ret = ed.openTags[i] == t.id ? i : false; i ++; } } else { ret = false; } return ret; }; qt.TagButton.prototype.callback = function(element, canvas, ed) { var t = this, startPos, endPos, cursorPos, scrollTop, v = canvas.value, l, r, i, sel, endTag = v ? t.tagEnd : ''; if ( document.selection ) { // IE canvas.focus(); sel = document.selection.createRange(); if ( sel.text.length > 0 ) { if ( !t.tagEnd ) sel.text = sel.text + t.tagStart; else sel.text = t.tagStart + sel.text + endTag; } else { if ( !t.tagEnd ) { sel.text = t.tagStart; } else if ( t.isOpen(ed) === false ) { sel.text = t.tagStart; t.openTag(element, ed); } else { sel.text = endTag; t.closeTag(element, ed); } } canvas.focus(); } else if ( canvas.selectionStart || canvas.selectionStart == '0' ) { // FF, WebKit, Opera startPos = canvas.selectionStart; endPos = canvas.selectionEnd; cursorPos = endPos; scrollTop = canvas.scrollTop; l = v.substring(0, startPos); // left of the selection r = v.substring(endPos, v.length); // right of the selection i = v.substring(startPos, endPos); // inside the selection if ( startPos != endPos ) { if ( !t.tagEnd ) { canvas.value = l + i + t.tagStart + r; // insert self closing tags after the selection cursorPos += t.tagStart.length; } else { canvas.value = l + t.tagStart + i + endTag + r; cursorPos += t.tagStart.length + endTag.length; } } else { if ( !t.tagEnd ) { canvas.value = l + t.tagStart + r; cursorPos = startPos + t.tagStart.length; } else if ( t.isOpen(ed) === false ) { canvas.value = l + t.tagStart + r; t.openTag(element, ed); cursorPos = startPos + t.tagStart.length; } else { canvas.value = l + endTag + r; cursorPos = startPos + endTag.length; t.closeTag(element, ed); } } canvas.focus(); canvas.selectionStart = cursorPos; canvas.selectionEnd = cursorPos; canvas.scrollTop = scrollTop; } else { // other browsers? if ( !endTag ) { canvas.value += t.tagStart; } else if ( t.isOpen(ed) !== false ) { canvas.value += t.tagStart; t.openTag(element, ed); } else { canvas.value += endTag; t.closeTag(element, ed); } canvas.focus(); } }; // removed qt.SpellButton = function() {}; // the close tags button qt.CloseButton = function() { qt.Button.call(this, 'close', quicktagsL10n.closeTags, '', quicktagsL10n.closeAllOpenTags); }; qt.CloseButton.prototype = new qt.Button(); qt._close = function(e, c, ed) { var button, element, tbo = ed.openTags; if ( tbo ) { while ( tbo.length > 0 ) { button = ed.getButton(tbo[tbo.length - 1]); element = document.getElementById(ed.name + '_' + button.id); if ( e ) button.callback.call(button, element, c, ed); else button.closeTag(element, ed); } } }; qt.CloseButton.prototype.callback = qt._close; qt.closeAllTags = function(editor_id) { var ed = this.getInstance(editor_id); qt._close('', ed.canvas, ed); }; // the link button qt.LinkButton = function() { qt.TagButton.call(this, 'link', 'link', '', '</a>', 'a'); }; qt.LinkButton.prototype = new qt.TagButton(); qt.LinkButton.prototype.callback = function(e, c, ed, defaultValue) { var URL, t = this; if ( typeof(wpLink) != 'undefined' ) { wpLink.open(); return; } if ( ! defaultValue ) defaultValue = 'http://'; if ( t.isOpen(ed) === false ) { URL = prompt(quicktagsL10n.enterURL, defaultValue); if ( URL ) { t.tagStart = '<a href="' + URL + '">'; qt.TagButton.prototype.callback.call(t, e, c, ed); } } else { qt.TagButton.prototype.callback.call(t, e, c, ed); } }; // the img button qt.ImgButton = function() { qt.TagButton.call(this, 'img', 'img', '', '', 'm'); }; qt.ImgButton.prototype = new qt.TagButton(); qt.ImgButton.prototype.callback = function(e, c, ed, defaultValue) { if ( ! defaultValue ) { defaultValue = 'http://'; } var src = prompt(quicktagsL10n.enterImageURL, defaultValue), alt; if ( src ) { alt = prompt(quicktagsL10n.enterImageDescription, ''); this.tagStart = '<img src="' + src + '" alt="' + alt + '" />'; qt.TagButton.prototype.callback.call(this, e, c, ed); } }; qt.FullscreenButton = function() { qt.Button.call(this, 'fullscreen', quicktagsL10n.fullscreen, 'f', quicktagsL10n.toggleFullscreen); }; qt.FullscreenButton.prototype = new qt.Button(); qt.FullscreenButton.prototype.callback = function(e, c) { if ( !c.id || typeof(fullscreen) == 'undefined' ) return; fullscreen.on(); }; qt.TextDirectionButton = function() { qt.Button.call(this, 'textdirection', quicktagsL10n.textdirection, '', quicktagsL10n.toggleTextdirection) }; qt.TextDirectionButton.prototype = new qt.Button(); qt.TextDirectionButton.prototype.callback = function(e, c) { var isRTL = ( 'rtl' == document.getElementsByTagName('html')[0].dir ), currentDirection = c.style.direction; if ( ! currentDirection ) currentDirection = ( isRTL ) ? 'rtl' : 'ltr'; c.style.direction = ( 'rtl' == currentDirection ) ? 'ltr' : 'rtl'; c.focus(); } // ensure backward compatibility edButtons[10] = new qt.TagButton('strong','b','<strong>','</strong>','b'); edButtons[20] = new qt.TagButton('em','i','<em>','</em>','i'), edButtons[30] = new qt.LinkButton(), // special case edButtons[40] = new qt.TagButton('block','b-quote','\n\n<blockquote>','</blockquote>\n\n','q'), edButtons[50] = new qt.TagButton('del','del','<del datetime="' + _datetime + '">','</del>','d'), edButtons[60] = new qt.TagButton('ins','ins','<ins datetime="' + _datetime + '">','</ins>','s'), edButtons[70] = new qt.ImgButton(), // special case edButtons[80] = new qt.TagButton('ul','ul','<ul>\n','</ul>\n\n','u'), edButtons[90] = new qt.TagButton('ol','ol','<ol>\n','</ol>\n\n','o'), edButtons[100] = new qt.TagButton('li','li','\t<li>','</li>\n','l'), edButtons[110] = new qt.TagButton('code','code','<code>','</code>','c'), edButtons[120] = new qt.TagButton('more','more','<!--more-->','','t'), edButtons[140] = new qt.CloseButton() })();
JavaScript
/** * Heartbeat API * * Note: this API is "experimental" meaning it will likely change a lot * in the next few releases based on feedback from 3.6.0. If you intend * to use it, please follow the development closely. * * Heartbeat is a simple server polling API that sends XHR requests to * the server every 15 seconds and triggers events (or callbacks) upon * receiving data. Currently these 'ticks' handle transports for post locking, * login-expiration warnings, and related tasks while a user is logged in. * * Available filters in ajax-actions.php: * - heartbeat_received * - heartbeat_send * - heartbeat_tick * - heartbeat_nopriv_received * - heartbeat_nopriv_send * - heartbeat_nopriv_tick * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat() * * @since 3.6.0 */ // Ensure the global `wp` object exists. window.wp = window.wp || {}; (function($){ var Heartbeat = function() { var self = this, running, beat, screenId = typeof pagenow != 'undefined' ? pagenow : '', url = typeof ajaxurl != 'undefined' ? ajaxurl : '', settings, tick = 0, queue = {}, interval, connecting, countdown = 0, errorcount = 0, tempInterval, hasFocus = true, isUserActive, userActiveEvents, winBlurTimeout, frameBlurTimeout = -1, hasConnectionError = false; /** * Returns a boolean that's indicative of whether or not there is a connection error * * @returns boolean */ this.hasConnectionError = function() { return hasConnectionError; }; if ( typeof( window.heartbeatSettings ) == 'object' ) { settings = $.extend( {}, window.heartbeatSettings ); // Add private vars url = settings.ajaxurl || url; delete settings.ajaxurl; delete settings.nonce; interval = settings.interval || 15; // default interval delete settings.interval; // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec. if ( interval < 15 ) interval = 15; else if ( interval > 60 ) interval = 60; interval = interval * 1000; // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set screenId = screenId || settings.screenId || 'front'; delete settings.screenId; // Add or overwrite public vars $.extend( this, settings ); } function time(s) { if ( s ) return parseInt( (new Date()).getTime() / 1000 ); return (new Date()).getTime(); } function isLocalFrame( frame ) { var origin, src = frame.src; if ( src && /^https?:\/\//.test( src ) ) { origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host; if ( src.indexOf( origin ) !== 0 ) return false; } try { if ( frame.contentWindow.document ) return true; } catch(e) {} return false; } // Set error state and fire an event on XHR errors or timeout function errorstate( error ) { var trigger; if ( error ) { switch ( error ) { case 'abort': // do nothing break; case 'timeout': // no response for 30 sec. trigger = true; break; case 'parsererror': case 'error': case 'empty': case 'unknown': errorcount++; if ( errorcount > 2 ) trigger = true; break; } if ( trigger && ! self.hasConnectionError() ) { hasConnectionError = true; $(document).trigger( 'heartbeat-connection-lost', [error] ); } } else if ( self.hasConnectionError() ) { errorcount = 0; hasConnectionError = false; $(document).trigger( 'heartbeat-connection-restored' ); } } function connect() { var send = {}, data, i, empty = true, nonce = typeof window.heartbeatSettings == 'object' ? window.heartbeatSettings.nonce : ''; tick = time(); data = $.extend( {}, queue ); // Clear the data queue, anything added after this point will be send on the next tick queue = {}; $(document).trigger( 'heartbeat-send', [data] ); for ( i in data ) { if ( data.hasOwnProperty( i ) ) { empty = false; break; } } // If nothing to send (nothing is expecting a response), // schedule the next tick and bail if ( empty && ! self.hasConnectionError() ) { connecting = false; next(); return; } send.data = data; send.interval = interval / 1000; send._nonce = nonce; send.action = 'heartbeat'; send.screen_id = screenId; send.has_focus = hasFocus; connecting = true; self.xhr = $.ajax({ url: url, type: 'post', timeout: 30000, // throw an error if not completed after 30 sec. data: send, dataType: 'json' }).done( function( response, textStatus, jqXHR ) { var new_interval; if ( ! response ) return errorstate( 'empty' ); // Clear error state if ( self.hasConnectionError() ) errorstate(); if ( response.nonces_expired ) { $(document).trigger( 'heartbeat-nonces-expired' ); return; } // Change the interval from PHP if ( response.heartbeat_interval ) { new_interval = response.heartbeat_interval; delete response.heartbeat_interval; } self.tick( response, textStatus, jqXHR ); // do this last, can trigger the next XHR if connection time > 5 sec. and new_interval == 'fast' if ( new_interval ) self.interval.call( self, new_interval ); }).always( function() { connecting = false; next(); }).fail( function( jqXHR, textStatus, error ) { errorstate( textStatus || 'unknown' ); self.error( jqXHR, textStatus, error ); }); } function next() { var delta = time() - tick, t = interval; if ( ! running ) return; if ( ! hasFocus ) { t = 100000; // 100 sec. Post locks expire after 120 sec. } else if ( countdown > 0 && tempInterval ) { t = tempInterval; countdown--; } window.clearTimeout(beat); if ( delta < t ) { beat = window.setTimeout( function(){ if ( running ) connect(); }, t - delta ); } else { connect(); } } function blurred() { window.clearTimeout(winBlurTimeout); window.clearTimeout(frameBlurTimeout); winBlurTimeout = frameBlurTimeout = 0; hasFocus = false; } function focused() { window.clearTimeout(winBlurTimeout); window.clearTimeout(frameBlurTimeout); winBlurTimeout = frameBlurTimeout = 0; isUserActive = time(); if ( hasFocus ) return; hasFocus = true; window.clearTimeout(beat); if ( ! connecting ) next(); } function setFrameEvents() { $('iframe').each( function( i, frame ){ if ( ! isLocalFrame( frame ) ) return; if ( $.data( frame, 'wp-heartbeat-focus' ) ) return; $.data( frame, 'wp-heartbeat-focus', 1 ); $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function(e) { focused(); }).on('blur.wp-heartbeat-focus', function(e) { setFrameEvents(); frameBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 ); }); }); } $(window).on( 'blur.wp-heartbeat-focus', function(e) { setFrameEvents(); winBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 ); }).on( 'focus.wp-heartbeat-focus', function() { $('iframe').each( function( i, frame ) { if ( !isLocalFrame( frame ) ) return; $.removeData( frame, 'wp-heartbeat-focus' ); $( frame.contentWindow ).off( '.wp-heartbeat-focus' ); }); focused(); }); function userIsActive() { userActiveEvents = false; $(document).off( '.wp-heartbeat-active' ); $('iframe').each( function( i, frame ) { if ( ! isLocalFrame( frame ) ) return; $( frame.contentWindow ).off( '.wp-heartbeat-active' ); }); focused(); } // Set 'hasFocus = true' if user is active and the window is in the background. // Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity) for 5 min. even when the window has focus. function checkUserActive() { var lastActive = isUserActive ? time() - isUserActive : 0; // Throttle down when no mouse or keyboard activity for 5 min if ( lastActive > 300000 && hasFocus ) blurred(); if ( ! userActiveEvents ) { $(document).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } ); $('iframe').each( function( i, frame ) { if ( ! isLocalFrame( frame ) ) return; $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } ); }); userActiveEvents = true; } } // Check for user activity every 30 seconds. window.setInterval( function(){ checkUserActive(); }, 30000 ); $(document).ready( function() { // Start one tick (15 sec) after DOM ready running = true; tick = time(); next(); }); this.hasFocus = function() { return hasFocus; }; /** * Get/Set the interval * * When setting to 'fast', the interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec). * If the window doesn't have focus, the interval slows down to 2 min. * * @param string speed Interval speed: 'fast' (5sec), 'standard' (15sec) default, 'slow' (60sec) * @param string ticks Used with speed = 'fast', how many ticks before the speed reverts back * @return int Current interval in seconds */ this.interval = function( speed, ticks ) { var reset, seconds; ticks = parseInt( ticks, 10 ) || 30; ticks = ticks < 1 || ticks > 30 ? 30 : ticks; if ( speed ) { switch ( speed ) { case 'fast': seconds = 5; countdown = ticks; break; case 'slow': seconds = 60; countdown = 0; break; case 'long-polling': // Allow long polling, (experimental) interval = 0; return 0; break; default: seconds = 15; countdown = 0; } // Reset when the new interval value is lower than the current one reset = seconds * 1000 < interval; if ( countdown > 0 ) { tempInterval = seconds * 1000; } else { interval = seconds * 1000; tempInterval = 0; } if ( reset ) next(); } if ( ! hasFocus ) return 120; return tempInterval ? tempInterval / 1000 : interval / 1000; }; /** * Enqueue data to send with the next XHR * * As the data is sent later, this function doesn't return the XHR response. * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example: * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) { * // code * }); * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'. * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle. * * $param string handle Unique handle for the data. The handle is used in PHP to receive the data. * $param mixed data The data to send. * $param bool dont_overwrite Whether to overwrite existing data in the queue. * $return bool Whether the data was queued or not. */ this.enqueue = function( handle, data, dont_overwrite ) { if ( handle ) { if ( queue.hasOwnProperty( handle ) && dont_overwrite ) return false; queue[handle] = data; return true; } return false; }; /** * Check if data with a particular handle is queued * * $param string handle The handle for the data * $return mixed The data queued with that handle or null */ this.isQueued = function( handle ) { return queue[handle]; }; }; $.extend( Heartbeat.prototype, { tick: function( data, textStatus, jqXHR ) { $(document).trigger( 'heartbeat-tick', [data, textStatus, jqXHR] ); }, error: function( jqXHR, textStatus, error ) { $(document).trigger( 'heartbeat-error', [jqXHR, textStatus, error] ); } }); wp.heartbeat = new Heartbeat(); }(jQuery));
JavaScript
// =================================================================== // Author: Matt Kruse <matt@mattkruse.com> // WWW: http://www.mattkruse.com/ // // NOTICE: You may use this code for any purpose, commercial or // private, without any further permission from the author. You may // remove this notice from your final code if you wish, however it is // appreciated by the author if at least my web site address is kept. // // You may *NOT* re-distribute this code in any way except through its // use. That means, you can include it in your product, or your web // site, or any other form where the code is actually being used. You // may not put the plain javascript up on your site for download or // include it in your javascript libraries for download. // If you wish to share this code with others, please just point them // to the URL instead. // Please DO NOT link directly to my .js files from your site. Copy // the files to your server and use them there. Thank you. // =================================================================== /* SOURCE FILE: AnchorPosition.js */ /* AnchorPosition.js Author: Matt Kruse Last modified: 10/11/02 DESCRIPTION: These functions find the position of an <A> tag in a document, so other elements can be positioned relative to it. COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small positioning errors - usually with Window positioning - occur on the Macintosh platform. FUNCTIONS: getAnchorPosition(anchorname) Returns an Object() having .x and .y properties of the pixel coordinates of the upper-left corner of the anchor. Position is relative to the PAGE. getAnchorWindowPosition(anchorname) Returns an Object() having .x and .y properties of the pixel coordinates of the upper-left corner of the anchor, relative to the WHOLE SCREEN. NOTES: 1) For popping up separate browser windows, use getAnchorWindowPosition. Otherwise, use getAnchorPosition 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. */ // getAnchorPosition(anchorname) // This function returns an object having .x and .y properties which are the coordinates // of the named anchor, relative to the page. function getAnchorPosition(anchorname) { // This function will return an Object with x and y properties var useWindow=false; var coordinates=new Object(); var x=0,y=0; // Browser capability sniffing var use_gebi=false, use_css=false, use_layers=false; if (document.getElementById) { use_gebi=true; } else if (document.all) { use_css=true; } else if (document.layers) { use_layers=true; } // Logic to find position if (use_gebi && document.all) { x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_gebi) { var o=document.getElementById(anchorname); x=AnchorPosition_getPageOffsetLeft(o); y=AnchorPosition_getPageOffsetTop(o); } else if (use_css) { x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_layers) { var found=0; for (var i=0; i<document.anchors.length; i++) { if (document.anchors[i].name==anchorname) { found=1; break; } } if (found==0) { coordinates.x=0; coordinates.y=0; return coordinates; } x=document.anchors[i].x; y=document.anchors[i].y; } else { coordinates.x=0; coordinates.y=0; return coordinates; } coordinates.x=x; coordinates.y=y; return coordinates; } // getAnchorWindowPosition(anchorname) // This function returns an object having .x and .y properties which are the coordinates // of the named anchor, relative to the window function getAnchorWindowPosition(anchorname) { var coordinates=getAnchorPosition(anchorname); var x=0; var y=0; if (document.getElementById) { if (isNaN(window.screenX)) { x=coordinates.x-document.body.scrollLeft+window.screenLeft; y=coordinates.y-document.body.scrollTop+window.screenTop; } else { x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset; y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset; } } else if (document.all) { x=coordinates.x-document.body.scrollLeft+window.screenLeft; y=coordinates.y-document.body.scrollTop+window.screenTop; } else if (document.layers) { x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset; y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset; } coordinates.x=x; coordinates.y=y; return coordinates; } // Functions for IE to get position of an object function AnchorPosition_getPageOffsetLeft (el) { var ol=el.offsetLeft; while ((el=el.offsetParent) != null) { ol += el.offsetLeft; } return ol; } function AnchorPosition_getWindowOffsetLeft (el) { return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft; } function AnchorPosition_getPageOffsetTop (el) { var ot=el.offsetTop; while((el=el.offsetParent) != null) { ot += el.offsetTop; } return ot; } function AnchorPosition_getWindowOffsetTop (el) { return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop; } /* SOURCE FILE: PopupWindow.js */ /* PopupWindow.js Author: Matt Kruse Last modified: 02/16/04 DESCRIPTION: This object allows you to easily and quickly popup a window in a certain place. The window can either be a DIV or a separate browser window. COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small positioning errors - usually with Window positioning - occur on the Macintosh platform. Due to bugs in Netscape 4.x, populating the popup window with <STYLE> tags may cause errors. USAGE: // Create an object for a WINDOW popup var win = new PopupWindow(); // Create an object for a DIV window using the DIV named 'mydiv' var win = new PopupWindow('mydiv'); // Set the window to automatically hide itself when the user clicks // anywhere else on the page except the popup win.autoHide(); // Show the window relative to the anchor name passed in win.showPopup(anchorname); // Hide the popup win.hidePopup(); // Set the size of the popup window (only applies to WINDOW popups win.setSize(width,height); // Populate the contents of the popup window that will be shown. If you // change the contents while it is displayed, you will need to refresh() win.populate(string); // set the URL of the window, rather than populating its contents // manually win.setUrl("http://www.site.com/"); // Refresh the contents of the popup win.refresh(); // Specify how many pixels to the right of the anchor the popup will appear win.offsetX = 50; // Specify how many pixels below the anchor the popup will appear win.offsetY = 100; NOTES: 1) Requires the functions in AnchorPosition.js 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. 4) When a PopupWindow object is created, a handler for 'onmouseup' is attached to any event handler you may have already defined. Do NOT define an event handler for 'onmouseup' after you define a PopupWindow object or the autoHide() will not work correctly. */ // Set the position of the popup window based on the anchor function PopupWindow_getXYPosition(anchorname) { var coordinates; if (this.type == "WINDOW") { coordinates = getAnchorWindowPosition(anchorname); } else { coordinates = getAnchorPosition(anchorname); } this.x = coordinates.x; this.y = coordinates.y; } // Set width/height of DIV/popup window function PopupWindow_setSize(width,height) { this.width = width; this.height = height; } // Fill the window with contents function PopupWindow_populate(contents) { this.contents = contents; this.populated = false; } // Set the URL to go to function PopupWindow_setUrl(url) { this.url = url; } // Set the window popup properties function PopupWindow_setWindowProperties(props) { this.windowProperties = props; } // Refresh the displayed contents of the popup function PopupWindow_refresh() { if (this.divName != null) { // refresh the DIV object if (this.use_gebi) { document.getElementById(this.divName).innerHTML = this.contents; } else if (this.use_css) { document.all[this.divName].innerHTML = this.contents; } else if (this.use_layers) { var d = document.layers[this.divName]; d.document.open(); d.document.writeln(this.contents); d.document.close(); } } else { if (this.popupWindow != null && !this.popupWindow.closed) { if (this.url!="") { this.popupWindow.location.href=this.url; } else { this.popupWindow.document.open(); this.popupWindow.document.writeln(this.contents); this.popupWindow.document.close(); } this.popupWindow.focus(); } } } // Position and show the popup, relative to an anchor object function PopupWindow_showPopup(anchorname) { this.getXYPosition(anchorname); this.x += this.offsetX; this.y += this.offsetY; if (!this.populated && (this.contents != "")) { this.populated = true; this.refresh(); } if (this.divName != null) { // Show the DIV object if (this.use_gebi) { document.getElementById(this.divName).style.left = this.x + "px"; document.getElementById(this.divName).style.top = this.y; document.getElementById(this.divName).style.visibility = "visible"; } else if (this.use_css) { document.all[this.divName].style.left = this.x; document.all[this.divName].style.top = this.y; document.all[this.divName].style.visibility = "visible"; } else if (this.use_layers) { document.layers[this.divName].left = this.x; document.layers[this.divName].top = this.y; document.layers[this.divName].visibility = "visible"; } } else { if (this.popupWindow == null || this.popupWindow.closed) { // If the popup window will go off-screen, move it so it doesn't if (this.x<0) { this.x=0; } if (this.y<0) { this.y=0; } if (screen && screen.availHeight) { if ((this.y + this.height) > screen.availHeight) { this.y = screen.availHeight - this.height; } } if (screen && screen.availWidth) { if ((this.x + this.width) > screen.availWidth) { this.x = screen.availWidth - this.width; } } var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+""); } this.refresh(); } } // Hide the popup function PopupWindow_hidePopup() { if (this.divName != null) { if (this.use_gebi) { document.getElementById(this.divName).style.visibility = "hidden"; } else if (this.use_css) { document.all[this.divName].style.visibility = "hidden"; } else if (this.use_layers) { document.layers[this.divName].visibility = "hidden"; } } else { if (this.popupWindow && !this.popupWindow.closed) { this.popupWindow.close(); this.popupWindow = null; } } } // Pass an event and return whether or not it was the popup DIV that was clicked function PopupWindow_isClicked(e) { if (this.divName != null) { if (this.use_layers) { var clickX = e.pageX; var clickY = e.pageY; var t = document.layers[this.divName]; if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) { return true; } else { return false; } } else if (document.all) { // Need to hard-code this to trap IE for error-handling var t = window.event.srcElement; while (t.parentElement != null) { if (t.id==this.divName) { return true; } t = t.parentElement; } return false; } else if (this.use_gebi && e) { var t = e.originalTarget; while (t.parentNode != null) { if (t.id==this.divName) { return true; } t = t.parentNode; } return false; } return false; } return false; } // Check an onMouseDown event to see if we should hide function PopupWindow_hideIfNotClicked(e) { if (this.autoHideEnabled && !this.isClicked(e)) { this.hidePopup(); } } // Call this to make the DIV disable automatically when mouse is clicked outside it function PopupWindow_autoHide() { this.autoHideEnabled = true; } // This global function checks all PopupWindow objects onmouseup to see if they should be hidden function PopupWindow_hidePopupWindows(e) { for (var i=0; i<popupWindowObjects.length; i++) { if (popupWindowObjects[i] != null) { var p = popupWindowObjects[i]; p.hideIfNotClicked(e); } } } // Run this immediately to attach the event listener function PopupWindow_attachListener() { if (document.layers) { document.captureEvents(Event.MOUSEUP); } window.popupWindowOldEventListener = document.onmouseup; if (window.popupWindowOldEventListener != null) { document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();"); } else { document.onmouseup = PopupWindow_hidePopupWindows; } } // CONSTRUCTOR for the PopupWindow object // Pass it a DIV name to use a DHTML popup, otherwise will default to window popup function PopupWindow() { if (!window.popupWindowIndex) { window.popupWindowIndex = 0; } if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); } if (!window.listenerAttached) { window.listenerAttached = true; PopupWindow_attachListener(); } this.index = popupWindowIndex++; popupWindowObjects[this.index] = this; this.divName = null; this.popupWindow = null; this.width=0; this.height=0; this.populated = false; this.visible = false; this.autoHideEnabled = false; this.contents = ""; this.url=""; this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no"; if (arguments.length>0) { this.type="DIV"; this.divName = arguments[0]; } else { this.type="WINDOW"; } this.use_gebi = false; this.use_css = false; this.use_layers = false; if (document.getElementById) { this.use_gebi = true; } else if (document.all) { this.use_css = true; } else if (document.layers) { this.use_layers = true; } else { this.type = "WINDOW"; } this.offsetX = 0; this.offsetY = 0; // Method mappings this.getXYPosition = PopupWindow_getXYPosition; this.populate = PopupWindow_populate; this.setUrl = PopupWindow_setUrl; this.setWindowProperties = PopupWindow_setWindowProperties; this.refresh = PopupWindow_refresh; this.showPopup = PopupWindow_showPopup; this.hidePopup = PopupWindow_hidePopup; this.setSize = PopupWindow_setSize; this.isClicked = PopupWindow_isClicked; this.autoHide = PopupWindow_autoHide; this.hideIfNotClicked = PopupWindow_hideIfNotClicked; } /* SOURCE FILE: ColorPicker2.js */ /* Last modified: 02/24/2003 DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB form. It uses a color "swatch" to display the standard 216-color web-safe palette. The user can then click on a color to select it. COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js. Only the latest DHTML-capable browsers will show the color and hex values at the bottom as your mouse goes over them. USAGE: // Create a new ColorPicker object using DHTML popup var cp = new ColorPicker(); // Create a new ColorPicker object using Window Popup var cp = new ColorPicker('window'); // Add a link in your page to trigger the popup. For example: <A HREF="#" onClick="cp.show('pick');return false;" NAME="pick" ID="pick">Pick</A> // Or use the built-in "select" function to do the dirty work for you: <A HREF="#" onClick="cp.select(document.forms[0].color,'pick');return false;" NAME="pick" ID="pick">Pick</A> // If using DHTML popup, write out the required DIV tag near the bottom // of your page. <SCRIPT LANGUAGE="JavaScript">cp.writeDiv()</SCRIPT> // Write the 'pickColor' function that will be called when the user clicks // a color and do something with the value. This is only required if you // want to do something other than simply populate a form field, which is // what the 'select' function will give you. function pickColor(color) { field.value = color; } NOTES: 1) Requires the functions in AnchorPosition.js and PopupWindow.js 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. 4) When a ColorPicker object is created, a handler for 'onmouseup' is attached to any event handler you may have already defined. Do NOT define an event handler for 'onmouseup' after you define a ColorPicker object or the color picker will not hide itself correctly. */ ColorPicker_targetInput = null; function ColorPicker_writeDiv() { document.writeln("<DIV ID=\"colorPickerDiv\" STYLE=\"position:absolute;visibility:hidden;\"> </DIV>"); } function ColorPicker_show(anchorname) { this.showPopup(anchorname); } function ColorPicker_pickColor(color,obj) { obj.hidePopup(); pickColor(color); } // A Default "pickColor" function to accept the color passed back from popup. // User can over-ride this with their own function. function pickColor(color) { if (ColorPicker_targetInput==null) { alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!"); return; } ColorPicker_targetInput.value = color; } // This function is the easiest way to popup the window, select a color, and // have the value populate a form field, which is what most people want to do. function ColorPicker_select(inputobj,linkname) { if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") { alert("colorpicker.select: Input object passed is not a valid form input object"); window.ColorPicker_targetInput=null; return; } window.ColorPicker_targetInput = inputobj; this.show(linkname); } // This function runs when you move your mouse over a color block, if you have a newer browser function ColorPicker_highlightColor(c) { var thedoc = (arguments.length>1)?arguments[1]:window.document; var d = thedoc.getElementById("colorPickerSelectedColor"); d.style.backgroundColor = c; d = thedoc.getElementById("colorPickerSelectedColorValue"); d.innerHTML = c; } function ColorPicker() { var windowMode = false; // Create a new PopupWindow object if (arguments.length==0) { var divname = "colorPickerDiv"; } else if (arguments[0] == "window") { var divname = ''; windowMode = true; } else { var divname = arguments[0]; } if (divname != "") { var cp = new PopupWindow(divname); } else { var cp = new PopupWindow(); cp.setSize(225,250); } // Object variables cp.currentValue = "#FFFFFF"; // Method Mappings cp.writeDiv = ColorPicker_writeDiv; cp.highlightColor = ColorPicker_highlightColor; cp.show = ColorPicker_show; cp.select = ColorPicker_select; // Code to populate color picker window var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099", "#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099", "#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099", "#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF", "#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F", "#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000", "#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399", "#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399", "#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399", "#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF", "#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F", "#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00", "#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699", "#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699", "#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699", "#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F", "#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F", "#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F", "#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999", "#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999", "#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999", "#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF", "#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F", "#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000", "#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99", "#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99", "#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99", "#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF", "#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F", "#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00", "#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99", "#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99", "#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99", "#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F", "#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F", "#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F", "#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666", "#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000", "#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000", "#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999", "#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF", "#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66", "#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00", "#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000", "#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099", "#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF", "#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF", "#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC", "#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000", "#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900", "#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33", "#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF", "#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF", "#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F", "#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F", "#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F", "#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000"); var total = colors.length; var width = 72; var cp_contents = ""; var windowRef = (windowMode)?"window.opener.":""; if (windowMode) { cp_contents += "<html><head><title>Select Color</title></head>"; cp_contents += "<body marginwidth=0 marginheight=0 leftmargin=0 topmargin=0><span style='text-align: center;'>"; } cp_contents += "<table style='border: none;' cellspacing=0 cellpadding=0>"; var use_highlight = (document.getElementById || document.all)?true:false; for (var i=0; i<total; i++) { if ((i % width) == 0) { cp_contents += "<tr>"; } if (use_highlight) { var mo = 'onMouseOver="'+windowRef+'ColorPicker_highlightColor(\''+colors[i]+'\',window.document)"'; } else { mo = ""; } cp_contents += '<td style="background-color: '+colors[i]+';"><a href="javascript:void()" onclick="'+windowRef+'ColorPicker_pickColor(\''+colors[i]+'\','+windowRef+'window.popupWindowObjects['+cp.index+']);return false;" '+mo+'>&nbsp;</a></td>'; if ( ((i+1)>=total) || (((i+1) % width) == 0)) { cp_contents += "</tr>"; } } // If the browser supports dynamically changing TD cells, add the fancy stuff if (document.getElementById) { var width1 = Math.floor(width/2); var width2 = width = width1; cp_contents += "<tr><td colspan='"+width1+"' style='background-color: #FFF;' ID='colorPickerSelectedColor'>&nbsp;</td><td colspan='"+width2+"' style='text-align: center;' id='colorPickerSelectedColorValue'>#FFFFFF</td></tr>"; } cp_contents += "</table>"; if (windowMode) { cp_contents += "</span></body></html>"; } // end populate code // Write the contents to the popup object cp.populate(cp_contents+"\n"); // Move the table down a bit so you can see it cp.offsetY = 25; cp.autoHide(); return cp; }
JavaScript
window.wp = window.wp || {}; (function( exports, $ ){ var api, extend, ctor, inherits, slice = Array.prototype.slice; /* ===================================================================== * Micro-inheritance - thank you, backbone.js. * ===================================================================== */ extend = function( protoProps, classProps ) { var child = inherits( this, protoProps, classProps ); child.extend = this.extend; return child; }; // Shared empty constructor function to aid in prototype-chain creation. ctor = function() {}; // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. inherits = function( parent, protoProps, staticProps ) { var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call `super()`. if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) { child = protoProps.constructor; } else { child = function() { // Storing the result `super()` before returning the value // prevents a bug in Opera where, if the constructor returns // a function, Opera will reject the return value in favor of // the original object. This causes all sorts of trouble. var result = parent.apply( this, arguments ); return result; }; } // Inherit class (static) properties from parent. $.extend( child, parent ); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. ctor.prototype = parent.prototype; child.prototype = new ctor(); // Add prototype properties (instance properties) to the subclass, // if supplied. if ( protoProps ) $.extend( child.prototype, protoProps ); // Add static properties to the constructor function, if supplied. if ( staticProps ) $.extend( child, staticProps ); // Correctly set child's `prototype.constructor`. child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed later. child.__super__ = parent.prototype; return child; }; api = {}; /* ===================================================================== * Base class. * ===================================================================== */ api.Class = function( applicator, argsArray, options ) { var magic, args = arguments; if ( applicator && argsArray && api.Class.applicator === applicator ) { args = argsArray; $.extend( this, options || {} ); } magic = this; if ( this.instance ) { magic = function() { return magic.instance.apply( magic, arguments ); }; $.extend( magic, this ); } magic.initialize.apply( magic, args ); return magic; }; api.Class.applicator = {}; api.Class.prototype.initialize = function() {}; /* * Checks whether a given instance extended a constructor. * * The magic surrounding the instance parameter causes the instanceof * keyword to return inaccurate results; it defaults to the function's * prototype instead of the constructor chain. Hence this function. */ api.Class.prototype.extended = function( constructor ) { var proto = this; while ( typeof proto.constructor !== 'undefined' ) { if ( proto.constructor === constructor ) return true; if ( typeof proto.constructor.__super__ === 'undefined' ) return false; proto = proto.constructor.__super__; } return false; }; api.Class.extend = extend; /* ===================================================================== * Events mixin. * ===================================================================== */ api.Events = { trigger: function( id ) { if ( this.topics && this.topics[ id ] ) this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) ); return this; }, bind: function( id, callback ) { this.topics = this.topics || {}; this.topics[ id ] = this.topics[ id ] || $.Callbacks(); this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) ); return this; }, unbind: function( id, callback ) { if ( this.topics && this.topics[ id ] ) this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) ); return this; } }; /* ===================================================================== * Observable values that support two-way binding. * ===================================================================== */ api.Value = api.Class.extend({ initialize: function( initial, options ) { this._value = initial; // @todo: potentially change this to a this.set() call. this.callbacks = $.Callbacks(); $.extend( this, options || {} ); this.set = $.proxy( this.set, this ); }, /* * Magic. Returns a function that will become the instance. * Set to null to prevent the instance from extending a function. */ instance: function() { return arguments.length ? this.set.apply( this, arguments ) : this.get(); }, get: function() { return this._value; }, set: function( to ) { var from = this._value; to = this._setter.apply( this, arguments ); to = this.validate( to ); // Bail if the sanitized value is null or unchanged. if ( null === to || this._value === to ) return this; this._value = to; this.callbacks.fireWith( this, [ to, from ] ); return this; }, _setter: function( to ) { return to; }, setter: function( callback ) { var from = this.get(); this._setter = callback; // Temporarily clear value so setter can decide if it's valid. this._value = null; this.set( from ); return this; }, resetSetter: function() { this._setter = this.constructor.prototype._setter; this.set( this.get() ); return this; }, validate: function( value ) { return value; }, bind: function( callback ) { this.callbacks.add.apply( this.callbacks, arguments ); return this; }, unbind: function( callback ) { this.callbacks.remove.apply( this.callbacks, arguments ); return this; }, link: function() { // values* var set = this.set; $.each( arguments, function() { this.bind( set ); }); return this; }, unlink: function() { // values* var set = this.set; $.each( arguments, function() { this.unbind( set ); }); return this; }, sync: function() { // values* var that = this; $.each( arguments, function() { that.link( this ); this.link( that ); }); return this; }, unsync: function() { // values* var that = this; $.each( arguments, function() { that.unlink( this ); this.unlink( that ); }); return this; } }); /* ===================================================================== * A collection of observable values. * ===================================================================== */ api.Values = api.Class.extend({ defaultConstructor: api.Value, initialize: function( options ) { $.extend( this, options || {} ); this._value = {}; this._deferreds = {}; }, instance: function( id ) { if ( arguments.length === 1 ) return this.value( id ); return this.when.apply( this, arguments ); }, value: function( id ) { return this._value[ id ]; }, has: function( id ) { return typeof this._value[ id ] !== 'undefined'; }, add: function( id, value ) { if ( this.has( id ) ) return this.value( id ); this._value[ id ] = value; value.parent = this; if ( value.extended( api.Value ) ) value.bind( this._change ); this.trigger( 'add', value ); if ( this._deferreds[ id ] ) this._deferreds[ id ].resolve(); return this._value[ id ]; }, create: function( id ) { return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) ); }, each: function( callback, context ) { context = typeof context === 'undefined' ? this : context; $.each( this._value, function( key, obj ) { callback.call( context, obj, key ); }); }, remove: function( id ) { var value; if ( this.has( id ) ) { value = this.value( id ); this.trigger( 'remove', value ); if ( value.extended( api.Value ) ) value.unbind( this._change ); delete value.parent; } delete this._value[ id ]; delete this._deferreds[ id ]; }, /** * Runs a callback once all requested values exist. * * when( ids*, [callback] ); * * For example: * when( id1, id2, id3, function( value1, value2, value3 ) {} ); * * @returns $.Deferred.promise(); */ when: function() { var self = this, ids = slice.call( arguments ), dfd = $.Deferred(); // If the last argument is a callback, bind it to .done() if ( $.isFunction( ids[ ids.length - 1 ] ) ) dfd.done( ids.pop() ); $.when.apply( $, $.map( ids, function( id ) { if ( self.has( id ) ) return; return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred(); })).done( function() { var values = $.map( ids, function( id ) { return self( id ); }); // If a value is missing, we've used at least one expired deferred. // Call Values.when again to generate a new deferred. if ( values.length !== ids.length ) { // ids.push( callback ); self.when.apply( self, ids ).done( function() { dfd.resolveWith( self, values ); }); return; } dfd.resolveWith( self, values ); }); return dfd.promise(); }, _change: function() { this.parent.trigger( 'change', this ); } }); $.extend( api.Values.prototype, api.Events ); /* ===================================================================== * An observable value that syncs with an element. * * Handles inputs, selects, and textareas by default. * ===================================================================== */ api.ensure = function( element ) { return typeof element == 'string' ? $( element ) : element; }; api.Element = api.Value.extend({ initialize: function( element, options ) { var self = this, synchronizer = api.Element.synchronizer.html, type, update, refresh; this.element = api.ensure( element ); this.events = ''; if ( this.element.is('input, select, textarea') ) { this.events += 'change'; synchronizer = api.Element.synchronizer.val; if ( this.element.is('input') ) { type = this.element.prop('type'); if ( api.Element.synchronizer[ type ] ) synchronizer = api.Element.synchronizer[ type ]; if ( 'text' === type || 'password' === type ) this.events += ' keyup'; } else if ( this.element.is('textarea') ) { this.events += ' keyup'; } } api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) ); this._value = this.get(); update = this.update; refresh = this.refresh; this.update = function( to ) { if ( to !== refresh.call( self ) ) update.apply( this, arguments ); }; this.refresh = function() { self.set( refresh.call( self ) ); }; this.bind( this.update ); this.element.bind( this.events, this.refresh ); }, find: function( selector ) { return $( selector, this.element ); }, refresh: function() {}, update: function() {} }); api.Element.synchronizer = {}; $.each( [ 'html', 'val' ], function( i, method ) { api.Element.synchronizer[ method ] = { update: function( to ) { this.element[ method ]( to ); }, refresh: function() { return this.element[ method ](); } }; }); api.Element.synchronizer.checkbox = { update: function( to ) { this.element.prop( 'checked', to ); }, refresh: function() { return this.element.prop( 'checked' ); } }; api.Element.synchronizer.radio = { update: function( to ) { this.element.filter( function() { return this.value === to; }).prop( 'checked', true ); }, refresh: function() { return this.element.filter( ':checked' ).val(); } }; /* ===================================================================== * Messenger for postMessage. * ===================================================================== */ $.support.postMessage = !! window.postMessage; api.Messenger = api.Class.extend({ add: function( key, initial, options ) { return this[ key ] = new api.Value( initial, options ); }, /** * Initialize Messenger. * * @param {object} params Parameters to configure the messenger. * {string} .url The URL to communicate with. * {window} .targetWindow The window instance to communicate with. Default window.parent. * {string} .channel If provided, will send the channel with each message and only accept messages a matching channel. * @param {object} options Extend any instance parameter or method with this object. */ initialize: function( params, options ) { // Target the parent frame by default, but only if a parent frame exists. var defaultTarget = window.parent == window ? null : window.parent; $.extend( this, options || {} ); this.add( 'channel', params.channel ); this.add( 'url', params.url || '' ); this.add( 'targetWindow', params.targetWindow || defaultTarget ); this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) { return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' ); }); // Since we want jQuery to treat the receive function as unique // to this instance, we give the function a new guid. // // This will prevent every Messenger's receive function from being // unbound when calling $.off( 'message', this.receive ); this.receive = $.proxy( this.receive, this ); this.receive.guid = $.guid++; $( window ).on( 'message', this.receive ); }, destroy: function() { $( window ).off( 'message', this.receive ); }, receive: function( event ) { var message; event = event.originalEvent; if ( ! this.targetWindow() ) return; // Check to make sure the origin is valid. if ( this.origin() && event.origin !== this.origin() ) return; message = JSON.parse( event.data ); // Check required message properties. if ( ! message || ! message.id || typeof message.data === 'undefined' ) return; // Check if channel names match. if ( ( message.channel || this.channel() ) && this.channel() !== message.channel ) return; this.trigger( message.id, message.data ); }, send: function( id, data ) { var message; data = typeof data === 'undefined' ? null : data; if ( ! this.url() || ! this.targetWindow() ) return; message = { id: id, data: data }; if ( this.channel() ) message.channel = this.channel(); this.targetWindow().postMessage( JSON.stringify( message ), this.origin() ); } }); // Add the Events mixin to api.Messenger. $.extend( api.Messenger.prototype, api.Events ); /* ===================================================================== * Core customize object. * ===================================================================== */ api = $.extend( new api.Values(), api ); api.get = function() { var result = {}; this.each( function( obj, key ) { result[ key ] = obj.get(); }); return result; }; // Expose the API to the world. exports.customize = api; })( wp, jQuery );
JavaScript
(function(w) { var init = function() { var pr = document.getElementById('post-revisions'), inputs = pr ? pr.getElementsByTagName('input') : []; pr.onclick = function() { var i, checkCount = 0, side; for ( i = 0; i < inputs.length; i++ ) { checkCount += inputs[i].checked ? 1 : 0; side = inputs[i].getAttribute('name'); if ( ! inputs[i].checked && ( 'left' == side && 1 > checkCount || 'right' == side && 1 < checkCount && ( ! inputs[i-1] || ! inputs[i-1].checked ) ) && ! ( inputs[i+1] && inputs[i+1].checked && 'right' == inputs[i+1].getAttribute('name') ) ) inputs[i].style.visibility = 'hidden'; else if ( 'left' == side || 'right' == side ) inputs[i].style.visibility = 'visible'; } } pr.onclick(); } if ( w && w.addEventListener ) w.addEventListener('load', init, false); else if ( w && w.attachEvent ) w.attachEvent('onload', init); })(window);
JavaScript
// Utility functions for parsing and handling shortcodes in Javascript. // Ensure the global `wp` object exists. window.wp = window.wp || {}; (function(){ wp.shortcode = { // ### Find the next matching shortcode // // Given a shortcode `tag`, a block of `text`, and an optional starting // `index`, returns the next matching shortcode or `undefined`. // // Shortcodes are formatted as an object that contains the match // `content`, the matching `index`, and the parsed `shortcode` object. next: function( tag, text, index ) { var re = wp.shortcode.regexp( tag ), match, result; re.lastIndex = index || 0; match = re.exec( text ); if ( ! match ) return; // If we matched an escaped shortcode, try again. if ( match[1] === '[' && match[7] === ']' ) return wp.shortcode.next( tag, text, re.lastIndex ); result = { index: match.index, content: match[0], shortcode: wp.shortcode.fromMatch( match ) }; // If we matched a leading `[`, strip it from the match // and increment the index accordingly. if ( match[1] ) { result.match = result.match.slice( 1 ); result.index++; } // If we matched a trailing `]`, strip it from the match. if ( match[7] ) result.match = result.match.slice( 0, -1 ); return result; }, // ### Replace matching shortcodes in a block of text // // Accepts a shortcode `tag`, content `text` to scan, and a `callback` // to process the shortcode matches and return a replacement string. // Returns the `text` with all shortcodes replaced. // // Shortcode matches are objects that contain the shortcode `tag`, // a shortcode `attrs` object, the `content` between shortcode tags, // and a boolean flag to indicate if the match was a `single` tag. replace: function( tag, text, callback ) { return text.replace( wp.shortcode.regexp( tag ), function( match, left, tag, attrs, slash, content, closing, right, offset ) { // If both extra brackets exist, the shortcode has been // properly escaped. if ( left === '[' && right === ']' ) return match; // Create the match object and pass it through the callback. var result = callback( wp.shortcode.fromMatch( arguments ) ); // Make sure to return any of the extra brackets if they // weren't used to escape the shortcode. return result ? left + result + right : match; }); }, // ### Generate a string from shortcode parameters // // Creates a `wp.shortcode` instance and returns a string. // // Accepts the same `options` as the `wp.shortcode()` constructor, // containing a `tag` string, a string or object of `attrs`, a boolean // indicating whether to format the shortcode using a `single` tag, and a // `content` string. string: function( options ) { return new wp.shortcode( options ).string(); }, // ### Generate a RegExp to identify a shortcode // // The base regex is functionally equivalent to the one found in // `get_shortcode_regex()` in `wp-includes/shortcodes.php`. // // Capture groups: // // 1. An extra `[` to allow for escaping shortcodes with double `[[]]` // 2. The shortcode name // 3. The shortcode argument list // 4. The self closing `/` // 5. The content of a shortcode when it wraps some content. // 6. The closing tag. // 7. An extra `]` to allow for escaping shortcodes with double `[[]]` regexp: _.memoize( function( tag ) { return new RegExp( '\\[(\\[?)(' + tag + ')(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)', 'g' ); }), // ### Parse shortcode attributes // // Shortcodes accept many types of attributes. These can chiefly be // divided into named and numeric attributes: // // Named attributes are assigned on a key/value basis, while numeric // attributes are treated as an array. // // Named attributes can be formatted as either `name="value"`, // `name='value'`, or `name=value`. Numeric attributes can be formatted // as `"value"` or just `value`. attrs: _.memoize( function( text ) { var named = {}, numeric = [], pattern, match; // This regular expression is reused from `shortcode_parse_atts()` // in `wp-includes/shortcodes.php`. // // Capture groups: // // 1. An attribute name, that corresponds to... // 2. a value in double quotes. // 3. An attribute name, that corresponds to... // 4. a value in single quotes. // 5. An attribute name, that corresponds to... // 6. an unquoted value. // 7. A numeric attribute in double quotes. // 8. An unquoted numeric attribute. pattern = /(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/g; // Map zero-width spaces to actual spaces. text = text.replace( /[\u00a0\u200b]/g, ' ' ); // Match and normalize attributes. while ( (match = pattern.exec( text )) ) { if ( match[1] ) { named[ match[1].toLowerCase() ] = match[2]; } else if ( match[3] ) { named[ match[3].toLowerCase() ] = match[4]; } else if ( match[5] ) { named[ match[5].toLowerCase() ] = match[6]; } else if ( match[7] ) { numeric.push( match[7] ); } else if ( match[8] ) { numeric.push( match[8] ); } } return { named: named, numeric: numeric }; }), // ### Generate a Shortcode Object from a RegExp match // Accepts a `match` object from calling `regexp.exec()` on a `RegExp` // generated by `wp.shortcode.regexp()`. `match` can also be set to the // `arguments` from a callback passed to `regexp.replace()`. fromMatch: function( match ) { var type; if ( match[4] ) type = 'self-closing'; else if ( match[6] ) type = 'closed'; else type = 'single'; return new wp.shortcode({ tag: match[2], attrs: match[3], type: type, content: match[5] }); } }; // Shortcode Objects // ----------------- // // Shortcode objects are generated automatically when using the main // `wp.shortcode` methods: `next()`, `replace()`, and `string()`. // // To access a raw representation of a shortcode, pass an `options` object, // containing a `tag` string, a string or object of `attrs`, a string // indicating the `type` of the shortcode ('single', 'self-closing', or // 'closed'), and a `content` string. wp.shortcode = _.extend( function( options ) { _.extend( this, _.pick( options || {}, 'tag', 'attrs', 'type', 'content' ) ); var attrs = this.attrs; // Ensure we have a correctly formatted `attrs` object. this.attrs = { named: {}, numeric: [] }; if ( ! attrs ) return; // Parse a string of attributes. if ( _.isString( attrs ) ) { this.attrs = wp.shortcode.attrs( attrs ); // Identify a correctly formatted `attrs` object. } else if ( _.isEqual( _.keys( attrs ), [ 'named', 'numeric' ] ) ) { this.attrs = attrs; // Handle a flat object of attributes. } else { _.each( options.attrs, function( value, key ) { this.set( key, value ); }, this ); } }, wp.shortcode ); _.extend( wp.shortcode.prototype, { // ### Get a shortcode attribute // // Automatically detects whether `attr` is named or numeric and routes // it accordingly. get: function( attr ) { return this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ]; }, // ### Set a shortcode attribute // // Automatically detects whether `attr` is named or numeric and routes // it accordingly. set: function( attr, value ) { this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ] = value; return this; }, // ### Transform the shortcode match into a string string: function() { var text = '[' + this.tag; _.each( this.attrs.numeric, function( value ) { if ( /\s/.test( value ) ) text += ' "' + value + '"'; else text += ' ' + value; }); _.each( this.attrs.named, function( value, name ) { text += ' ' + name + '="' + value + '"'; }); // If the tag is marked as `single` or `self-closing`, close the // tag and ignore any additional content. if ( 'single' === this.type ) return text + ']'; else if ( 'self-closing' === this.type ) return text + ' /]'; // Complete the opening tag. text += ']'; if ( this.content ) text += this.content; // Add the closing tag. return text + '[/' + this.tag + ']'; } }); }()); // HTML utility functions // ---------------------- // // Experimental. These functions may change or be removed in the future. (function(){ wp.html = _.extend( wp.html || {}, { // ### Parse HTML attributes. // // Converts `content` to a set of parsed HTML attributes. // Utilizes `wp.shortcode.attrs( content )`, which is a valid superset of // the HTML attribute specification. Reformats the attributes into an // object that contains the `attrs` with `key:value` mapping, and a record // of the attributes that were entered using `empty` attribute syntax (i.e. // with no value). attrs: function( content ) { var result, attrs; // If `content` ends in a slash, strip it. if ( '/' === content[ content.length - 1 ] ) content = content.slice( 0, -1 ); result = wp.shortcode.attrs( content ); attrs = result.named; _.each( result.numeric, function( key ) { if ( /\s/.test( key ) ) return; attrs[ key ] = ''; }); return attrs; }, // ### Convert an HTML-representation of an object to a string. string: function( options ) { var text = '<' + options.tag, content = options.content || ''; _.each( options.attrs, function( value, attr ) { text += ' ' + attr; // Use empty attribute notation where possible. if ( '' === value ) return; // Convert boolean values to strings. if ( _.isBoolean( value ) ) value = value ? 'true' : 'false'; text += '="' + value + '"'; }); // Return the result if it is a self-closing tag. if ( options.single ) return text + ' />'; // Complete the opening tag. text += '>'; // If `content` is an object, recursively call this function. text += _.isObject( content ) ? wp.html.string( content ) : content; return text + '</' + options.tag + '>'; } }); }());
JavaScript
var wpAjax = jQuery.extend( { unserialize: function( s ) { var r = {}, q, pp, i, p; if ( !s ) { return r; } q = s.split('?'); if ( q[1] ) { s = q[1]; } pp = s.split('&'); for ( i in pp ) { if ( jQuery.isFunction(pp.hasOwnProperty) && !pp.hasOwnProperty(i) ) { continue; } p = pp[i].split('='); r[p[0]] = p[1]; } return r; }, parseAjaxResponse: function( x, r, e ) { // 1 = good, 0 = strange (bad data?), -1 = you lack permission var parsed = {}, re = jQuery('#' + r).html(''), err = ''; if ( x && typeof x == 'object' && x.getElementsByTagName('wp_ajax') ) { parsed.responses = []; parsed.errors = false; jQuery('response', x).each( function() { var th = jQuery(this), child = jQuery(this.firstChild), response; response = { action: th.attr('action'), what: child.get(0).nodeName, id: child.attr('id'), oldId: child.attr('old_id'), position: child.attr('position') }; response.data = jQuery( 'response_data', child ).text(); response.supplemental = {}; if ( !jQuery( 'supplemental', child ).children().each( function() { response.supplemental[this.nodeName] = jQuery(this).text(); } ).size() ) { response.supplemental = false } response.errors = []; if ( !jQuery('wp_error', child).each( function() { var code = jQuery(this).attr('code'), anError, errorData, formField; anError = { code: code, message: this.firstChild.nodeValue, data: false }; errorData = jQuery('wp_error_data[code="' + code + '"]', x); if ( errorData ) { anError.data = errorData.get(); } formField = jQuery( 'form-field', errorData ).text(); if ( formField ) { code = formField; } if ( e ) { wpAjax.invalidateForm( jQuery('#' + e + ' :input[name="' + code + '"]' ).parents('.form-field:first') ); } err += '<p>' + anError.message + '</p>'; response.errors.push( anError ); parsed.errors = true; } ).size() ) { response.errors = false; } parsed.responses.push( response ); } ); if ( err.length ) { re.html( '<div class="error">' + err + '</div>' ); } return parsed; } if ( isNaN(x) ) { return !re.html('<div class="error"><p>' + x + '</p></div>'); } x = parseInt(x,10); if ( -1 == x ) { return !re.html('<div class="error"><p>' + wpAjax.noPerm + '</p></div>'); } else if ( 0 === x ) { return !re.html('<div class="error"><p>' + wpAjax.broken + '</p></div>'); } return true; }, invalidateForm: function ( selector ) { return jQuery( selector ).addClass( 'form-invalid' ).find('input:visible').change( function() { jQuery(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ); }, validateForm: function( selector ) { selector = jQuery( selector ); return !wpAjax.invalidateForm( selector.find('.form-required').filter( function() { return jQuery('input:visible', this).val() == ''; } ) ).size(); } }, wpAjax || { noPerm: 'You do not have permission to do that.', broken: 'An unidentified error has occurred.' } ); // Basic form validation jQuery(document).ready( function($){ $('form.validate').submit( function() { return wpAjax.validateForm( $(this) ); } ); });
JavaScript
(function($) { var fs = {add:'ajaxAdd',del:'ajaxDel',dim:'ajaxDim',process:'process',recolor:'recolor'}, wpList; wpList = { settings: { url: ajaxurl, type: 'POST', response: 'ajax-response', what: '', alt: 'alternate', altOffset: 0, addColor: null, delColor: null, dimAddColor: null, dimDelColor: null, confirm: null, addBefore: null, addAfter: null, delBefore: null, delAfter: null, dimBefore: null, dimAfter: null }, nonce: function(e,s) { var url = wpAjax.unserialize(e.attr('href')); return s.nonce || url._ajax_nonce || $('#' + s.element + ' input[name="_ajax_nonce"]').val() || url._wpnonce || $('#' + s.element + ' input[name="_wpnonce"]').val() || 0; }, parseData: function(e,t) { var d = [], wpListsData; try { wpListsData = $(e).attr('data-wp-lists') || ''; wpListsData = wpListsData.match(new RegExp(t+':[\\S]+')); if ( wpListsData ) d = wpListsData[0].split(':'); } catch(r) {} return d; }, pre: function(e,s,a) { var bg, r; s = $.extend( {}, this.wpList.settings, { element: null, nonce: 0, target: e.get(0) }, s || {} ); if ( $.isFunction( s.confirm ) ) { if ( 'add' != a ) { bg = $('#' + s.element).css('backgroundColor'); $('#' + s.element).css('backgroundColor', '#FF9966'); } r = s.confirm.call(this, e, s, a, bg); if ( 'add' != a ) $('#' + s.element).css('backgroundColor', bg ); if ( !r ) return false; } return s; }, ajaxAdd: function( e, s ) { e = $(e); s = s || {}; var list = this, data = wpList.parseData(e,'add'), es, valid, formData, res, rres; s = wpList.pre.call( list, e, s, 'add' ); s.element = data[2] || e.attr( 'id' ) || s.element || null; if ( data[3] ) s.addColor = '#' + data[3]; else s.addColor = s.addColor || '#FFFF33'; if ( !s ) return false; if ( !e.is('[id="' + s.element + '-submit"]') ) return !wpList.add.call( list, e, s ); if ( !s.element ) return true; s.action = 'add-' + s.what; s.nonce = wpList.nonce(e,s); es = $('#' + s.element + ' :input').not('[name="_ajax_nonce"], [name="_wpnonce"], [name="action"]'); valid = wpAjax.validateForm( '#' + s.element ); if ( !valid ) return false; s.data = $.param( $.extend( { _ajax_nonce: s.nonce, action: s.action }, wpAjax.unserialize( data[4] || '' ) ) ); formData = $.isFunction(es.fieldSerialize) ? es.fieldSerialize() : es.serialize(); if ( formData ) s.data += '&' + formData; if ( $.isFunction(s.addBefore) ) { s = s.addBefore( s ); if ( !s ) return true; } if ( !s.data.match(/_ajax_nonce=[a-f0-9]+/) ) return true; s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) return false; if ( true === res ) return true; jQuery.each( res.responses, function() { wpList.add.call( list, this.data, $.extend( {}, s, { // this.firstChild.nodevalue pos: this.position || 0, id: this.id || 0, oldId: this.oldId || null } ) ); } ); list.wpList.recolor(); $(list).trigger( 'wpListAddEnd', [ s, list.wpList ] ); wpList.clear.call(list,'#' + s.element); }; s.complete = function(x, st) { if ( $.isFunction(s.addAfter) ) { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.addAfter( rres, _s ); } }; $.ajax( s ); return false; }, ajaxDel: function( e, s ) { e = $(e); s = s || {}; var list = this, data = wpList.parseData(e,'delete'), element, res, rres; s = wpList.pre.call( list, e, s, 'delete' ); s.element = data[2] || s.element || null; if ( data[3] ) s.delColor = '#' + data[3]; else s.delColor = s.delColor || '#faa'; if ( !s || !s.element ) return false; s.action = 'delete-' + s.what; s.nonce = wpList.nonce(e,s); s.data = $.extend( { action: s.action, id: s.element.split('-').pop(), _ajax_nonce: s.nonce }, wpAjax.unserialize( data[4] || '' ) ); if ( $.isFunction(s.delBefore) ) { s = s.delBefore( s, list ); if ( !s ) return true; } if ( !s.data._ajax_nonce ) return true; element = $('#' + s.element); if ( 'none' != s.delColor ) { element.css( 'backgroundColor', s.delColor ).fadeOut( 350, function(){ list.wpList.recolor(); $(list).trigger( 'wpListDelEnd', [ s, list.wpList ] ); }); } else { list.wpList.recolor(); $(list).trigger( 'wpListDelEnd', [ s, list.wpList ] ); } s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) { element.stop().stop().css( 'backgroundColor', '#faa' ).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } ); return false; } }; s.complete = function(x, st) { if ( $.isFunction(s.delAfter) ) { element.queue( function() { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.delAfter( rres, _s ); }).dequeue(); } } $.ajax( s ); return false; }, ajaxDim: function( e, s ) { if ( $(e).parent().css('display') == 'none' ) // Prevent hidden links from being clicked by hotkeys return false; e = $(e); s = s || {}; var list = this, data = wpList.parseData(e,'dim'), element, isClass, color, dimColor, res, rres; s = wpList.pre.call( list, e, s, 'dim' ); s.element = data[2] || s.element || null; s.dimClass = data[3] || s.dimClass || null; if ( data[4] ) s.dimAddColor = '#' + data[4]; else s.dimAddColor = s.dimAddColor || '#FFFF33'; if ( data[5] ) s.dimDelColor = '#' + data[5]; else s.dimDelColor = s.dimDelColor || '#FF3333'; if ( !s || !s.element || !s.dimClass ) return true; s.action = 'dim-' + s.what; s.nonce = wpList.nonce(e,s); s.data = $.extend( { action: s.action, id: s.element.split('-').pop(), dimClass: s.dimClass, _ajax_nonce : s.nonce }, wpAjax.unserialize( data[6] || '' ) ); if ( $.isFunction(s.dimBefore) ) { s = s.dimBefore( s ); if ( !s ) return true; } element = $('#' + s.element); isClass = element.toggleClass(s.dimClass).is('.' + s.dimClass); color = wpList.getColor( element ); element.toggleClass( s.dimClass ); dimColor = isClass ? s.dimAddColor : s.dimDelColor; if ( 'none' != dimColor ) { element .animate( { backgroundColor: dimColor }, 'fast' ) .queue( function() { element.toggleClass(s.dimClass); $(this).dequeue(); } ) .animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); $(list).trigger( 'wpListDimEnd', [ s, list.wpList ] ); } }); } else { $(list).trigger( 'wpListDimEnd', [ s, list.wpList ] ); } if ( !s.data._ajax_nonce ) return true; s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) { element.stop().stop().css( 'backgroundColor', '#FF3333' )[isClass?'removeClass':'addClass'](s.dimClass).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } ); return false; } }; s.complete = function(x, st) { if ( $.isFunction(s.dimAfter) ) { element.queue( function() { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.dimAfter( rres, _s ); }).dequeue(); } }; $.ajax( s ); return false; }, getColor: function( el ) { var color = jQuery(el).css('backgroundColor'); return color || '#ffffff'; }, add: function( e, s ) { e = $(e); var list = $(this), old = false, _s = { pos: 0, id: 0, oldId: null }, ba, ref, color; if ( 'string' == typeof s ) s = { what: s }; s = $.extend(_s, this.wpList.settings, s); if ( !e.size() || !s.what ) return false; if ( s.oldId ) old = $('#' + s.what + '-' + s.oldId); if ( s.id && ( s.id != s.oldId || !old || !old.size() ) ) $('#' + s.what + '-' + s.id).remove(); if ( old && old.size() ) { old.before(e); old.remove(); } else if ( isNaN(s.pos) ) { ba = 'after'; if ( '-' == s.pos.substr(0,1) ) { s.pos = s.pos.substr(1); ba = 'before'; } ref = list.find( '#' + s.pos ); if ( 1 === ref.size() ) ref[ba](e); else list.append(e); } else if ( 'comment' != s.what || 0 === $('#' + s.element).length ) { if ( s.pos < 0 ) { list.prepend(e); } else { list.append(e); } } if ( s.alt ) { if ( ( list.children(':visible').index( e[0] ) + s.altOffset ) % 2 ) { e.removeClass( s.alt ); } else { e.addClass( s.alt ); } } if ( 'none' != s.addColor ) { color = wpList.getColor( e ); e.css( 'backgroundColor', s.addColor ).animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); } } ); } list.each( function() { this.wpList.process( e ); } ); return e; }, clear: function(e) { var list = this, t, tag; e = $(e); if ( list.wpList && e.parents( '#' + list.id ).size() ) return; e.find(':input').each( function() { if ( $(this).parents('.form-no-clear').size() ) return; t = this.type.toLowerCase(); tag = this.tagName.toLowerCase(); if ( 'text' == t || 'password' == t || 'textarea' == tag ) this.value = ''; else if ( 'checkbox' == t || 'radio' == t ) this.checked = false; else if ( 'select' == tag ) this.selectedIndex = null; }); }, process: function(el) { var list = this, $el = $(el || document); $el.delegate( 'form[data-wp-lists^="add:' + list.id + ':"]', 'submit', function(){ return list.wpList.add(this); }); $el.delegate( 'a[data-wp-lists^="add:' + list.id + ':"], input[data-wp-lists^="add:' + list.id + ':"]', 'click', function(){ return list.wpList.add(this); }); $el.delegate( '[data-wp-lists^="delete:' + list.id + ':"]', 'click', function(){ return list.wpList.del(this); }); $el.delegate( '[data-wp-lists^="dim:' + list.id + ':"]', 'click', function(){ return list.wpList.dim(this); }); }, recolor: function() { var list = this, items, eo; if ( !list.wpList.settings.alt ) return; items = $('.list-item:visible', list); if ( !items.size() ) items = $(list).children(':visible'); eo = [':even',':odd']; if ( list.wpList.settings.altOffset % 2 ) eo.reverse(); items.filter(eo[0]).addClass(list.wpList.settings.alt).end().filter(eo[1]).removeClass(list.wpList.settings.alt); }, init: function() { var lists = this; lists.wpList.process = function(a) { lists.each( function() { this.wpList.process(a); } ); }; lists.wpList.recolor = function() { lists.each( function() { this.wpList.recolor(); } ); }; } }; $.fn.wpList = function( settings ) { this.each( function() { var _this = this; this.wpList = { settings: $.extend( {}, wpList.settings, { what: wpList.parseData(this,'list')[1] || '' }, settings ) }; $.each( fs, function(i,f) { _this.wpList[i] = function( e, s ) { return wpList[f].call( _this, e, s ); }; } ); } ); wpList.init.call(this); this.wpList.process(); return this; }; })(jQuery);
JavaScript
(function( exports, $ ){ var api = wp.customize, debounce; debounce = function( fn, delay, context ) { var timeout; return function() { var args = arguments; context = context || this; clearTimeout( timeout ); timeout = setTimeout( function() { timeout = null; fn.apply( context, args ); }, delay ); }; }; api.Preview = api.Messenger.extend({ /** * Requires params: * - url - the URL of preview frame */ initialize: function( params, options ) { var self = this; api.Messenger.prototype.initialize.call( this, params, options ); this.body = $( document.body ); this.body.on( 'click.preview', 'a', function( event ) { event.preventDefault(); self.send( 'scroll', 0 ); self.send( 'url', $(this).prop('href') ); }); // You cannot submit forms. // @todo: Allow form submissions by mixing $_POST data with the customize setting $_POST data. this.body.on( 'submit.preview', 'form', function( event ) { event.preventDefault(); }); this.window = $( window ); this.window.on( 'scroll.preview', debounce( function() { self.send( 'scroll', self.window.scrollTop() ); }, 200 )); this.bind( 'scroll', function( distance ) { self.window.scrollTop( distance ); }); } }); $( function() { api.settings = window._wpCustomizeSettings; if ( ! api.settings ) return; var preview, bg; preview = new api.Preview({ url: window.location.href, channel: api.settings.channel }); preview.bind( 'settings', function( values ) { $.each( values, function( id, value ) { if ( api.has( id ) ) api( id ).set( value ); else api.create( id, value ); }); }); preview.trigger( 'settings', api.settings.values ); preview.bind( 'setting', function( args ) { var value; args = args.slice(); if ( value = api( args.shift() ) ) value.set.apply( value, args ); }); preview.bind( 'sync', function( events ) { $.each( events, function( event, args ) { preview.trigger( event, args ); }); preview.send( 'synced' ); }); preview.bind( 'active', function() { if ( api.settings.nonce ) preview.send( 'nonce', api.settings.nonce ); }); preview.send( 'ready' ); /* Custom Backgrounds */ bg = $.map(['color', 'image', 'position_x', 'repeat', 'attachment'], function( prop ) { return 'background_' + prop; }); api.when.apply( api, bg ).done( function( color, image, position_x, repeat, attachment ) { var body = $(document.body), head = $('head'), style = $('#custom-background-css'), update; // If custom backgrounds are active and we can't find the // default output, bail. if ( body.hasClass('custom-background') && ! style.length ) return; update = function() { var css = ''; // The body will support custom backgrounds if either // the color or image are set. // // See get_body_class() in /wp-includes/post-template.php body.toggleClass( 'custom-background', !! ( color() || image() ) ); if ( color() ) css += 'background-color: ' + color() + ';'; if ( image() ) { css += 'background-image: url("' + image() + '");'; css += 'background-position: top ' + position_x() + ';'; css += 'background-repeat: ' + repeat() + ';'; css += 'background-attachment: ' + attachment() + ';'; } // Refresh the stylesheet by removing and recreating it. style.remove(); style = $('<style type="text/css" id="custom-background-css">body.custom-background { ' + css + ' }</style>').appendTo( head ); }; $.each( arguments, function() { this.bind( update ); }); }); }); })( wp, jQuery );
JavaScript
(function ($) { // add mime-type aliases to MediaElement plugin support mejs.plugins.silverlight[0].types.push('video/x-ms-wmv'); mejs.plugins.silverlight[0].types.push('audio/x-ms-wma'); $(function () { var settings = {}; if ( typeof _wpmejsSettings !== 'undefined' ) settings.pluginPath = _wpmejsSettings.pluginPath; $('.wp-audio-shortcode, .wp-video-shortcode').mediaelementplayer( settings ); }); }(jQuery));
JavaScript
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ if ( typeof tb_pathToImage != 'string' ) { var tb_pathToImage = thickboxL10n.loadingAnimation; } /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init jQuery(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ jQuery('body').on('click', domChunk, tb_click); } function tb_click(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 jQuery("body","html").css({height: "100%", width: "100%"}); jQuery("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 jQuery("body").append("<iframe id='TB_HideSelect'>"+thickboxL10n.noiframes+"</iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' width='208' /></div>");//add loader to the page jQuery('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = jQuery("a[rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.next+"</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.prev+"</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='"+thickboxL10n.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div>"); jQuery("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);} jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } jQuery("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } jQuery("#TB_next").click(goNext); } jQuery(document).bind('keydown.thickbox', function(e){ e.stopImmediatePropagation(); if ( e.which == 27 ){ // close if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); } else if ( e.which == 190 ){ // display previous image if(!(TB_NextHTML == "")){ jQuery(document).unbind('thickbox'); goNext(); } } else if ( e.which == 188 ){ // display next image if(!(TB_PrevHTML == "")){ jQuery(document).unbind('thickbox'); goPrev(); } } return false; }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_ImageOff").click(tb_remove); jQuery("#TB_window").css({'visibility':'visible'}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); jQuery("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' >"+thickboxL10n.noiframes+"</iframe>"); }else{//iframe modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'>"+thickboxL10n.noiframes+"</iframe>"); } }else{// not an iframe, ajax if(jQuery("#TB_window").css("visibility") != "visible"){ if(params['modal'] != "true"){//ajax no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><div class='tb-close-icon'></div></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; jQuery("#TB_ajaxContent")[0].scrollTop = 0; jQuery("#TB_ajaxWindowTitle").html(caption); } } jQuery("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children()); jQuery("#TB_window").bind('tb_unload', function () { jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); }else{ jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); jQuery("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); jQuery("#TB_window").css({'visibility':'visible'}); }); } } if(!params['modal']){ jQuery(document).bind('keyup.thickbox', function(e){ if ( e.which == 27 ){ // close e.stopImmediatePropagation(); if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); return false; } }); } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); } function tb_remove() { jQuery("#TB_imageOff").unbind("click"); jQuery("#TB_closeWindowButton").unbind("click"); jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("tb_unload").unbind().remove();}); jQuery("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 jQuery("body","html").css({height: "auto", width: "auto"}); jQuery("html").css("overflow",""); } jQuery(document).unbind('.thickbox'); return false; } function tb_position() { var isIE6 = typeof document.body.style.maxHeight === "undefined"; jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( ! isIE6 ) { // take away IE6 jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
JavaScript
(function($){ var media = wp.media, Attachment = media.model.Attachment, Attachments = media.model.Attachments, Query = media.model.Query, l10n; // Link any localized strings. l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n; // Link any settings. media.view.settings = l10n.settings || {}; delete l10n.settings; // Copy the `post` setting over to the model settings. media.model.settings.post = media.view.settings.post; // Check if the browser supports CSS 3.0 transitions $.support.transition = (function(){ var style = document.documentElement.style, transitions = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' }, transition; transition = _.find( _.keys( transitions ), function( transition ) { return ! _.isUndefined( style[ transition ] ); }); return transition && { end: transitions[ transition ] }; }()); // Makes it easier to bind events using transitions. media.transition = function( selector, sensitivity ) { var deferred = $.Deferred(); sensitivity = sensitivity || 2000; if ( $.support.transition ) { if ( ! (selector instanceof $) ) selector = $( selector ); // Resolve the deferred when the first element finishes animating. selector.first().one( $.support.transition.end, deferred.resolve ); // Just in case the event doesn't trigger, fire a callback. _.delay( deferred.resolve, sensitivity ); // Otherwise, execute on the spot. } else { deferred.resolve(); } return deferred.promise(); }; /** * ======================================================================== * CONTROLLERS * ======================================================================== */ /** * wp.media.controller.Region */ media.controller.Region = function( options ) { _.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) ); }; // Use Backbone's self-propagating `extend` inheritance method. media.controller.Region.extend = Backbone.Model.extend; _.extend( media.controller.Region.prototype, { mode: function( mode ) { if ( ! mode ) return this._mode; // Bail if we're trying to change to the current mode. if ( mode === this._mode ) return this; this.trigger('deactivate'); this._mode = mode; this.render( mode ); this.trigger('activate'); return this; }, render: function( mode ) { // If no mode is provided, just re-render the current mode. // If the provided mode isn't active, perform a full switch. if ( mode && mode !== this._mode ) return this.mode( mode ); var set = { view: null }, view; this.trigger( 'create', set ); view = set.view; this.trigger( 'render', view ); if ( view ) this.set( view ); return this; }, get: function() { return this.view.views.first( this.selector ); }, set: function( views, options ) { if ( options ) options.add = false; return this.view.views.set( this.selector, views, options ); }, trigger: function( event ) { var base; if ( ! this._mode ) return; var args = _.toArray( arguments ); base = this.id + ':' + event; // Trigger `region:action:mode` event. args[0] = base + ':' + this._mode; this.view.trigger.apply( this.view, args ); // Trigger `region:action` event. args[0] = base; this.view.trigger.apply( this.view, args ); return this; } }); /** * wp.media.controller.StateMachine */ media.controller.StateMachine = function( states ) { this.states = new Backbone.Collection( states ); }; // Use Backbone's self-propagating `extend` inheritance method. media.controller.StateMachine.extend = Backbone.Model.extend; // Add events to the `StateMachine`. _.extend( media.controller.StateMachine.prototype, Backbone.Events, { // Fetch a state. // // If no `id` is provided, returns the active state. // // Implicitly creates states. state: function( id ) { // Ensure that the `states` collection exists so the `StateMachine` // can be used as a mixin. this.states = this.states || new Backbone.Collection(); // Default to the active state. id = id || this._state; if ( id && ! this.states.get( id ) ) this.states.add({ id: id }); return this.states.get( id ); }, // Sets the active state. setState: function( id ) { var previous = this.state(); // Bail if we're trying to select the current state, if we haven't // created the `states` collection, or are trying to select a state // that does not exist. if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) ) return this; if ( previous ) { previous.trigger('deactivate'); this._lastState = previous.id; } this._state = id; this.state().trigger('activate'); return this; }, // Returns the previous active state. // // Call the `state()` method with no parameters to retrieve the current // active state. lastState: function() { if ( this._lastState ) return this.state( this._lastState ); } }); // Map methods from the `states` collection to the `StateMachine` itself. _.each([ 'on', 'off', 'trigger' ], function( method ) { media.controller.StateMachine.prototype[ method ] = function() { // Ensure that the `states` collection exists so the `StateMachine` // can be used as a mixin. this.states = this.states || new Backbone.Collection(); // Forward the method to the `states` collection. this.states[ method ].apply( this.states, arguments ); return this; }; }); // wp.media.controller.State // --------------------------- media.controller.State = Backbone.Model.extend({ constructor: function() { this.on( 'activate', this._preActivate, this ); this.on( 'activate', this.activate, this ); this.on( 'activate', this._postActivate, this ); this.on( 'deactivate', this._deactivate, this ); this.on( 'deactivate', this.deactivate, this ); this.on( 'reset', this.reset, this ); this.on( 'ready', this._ready, this ); this.on( 'ready', this.ready, this ); Backbone.Model.apply( this, arguments ); this.on( 'change:menu', this._updateMenu, this ); }, ready: function() {}, activate: function() {}, deactivate: function() {}, reset: function() {}, _ready: function() { this._updateMenu(); }, _preActivate: function() { this.active = true; }, _postActivate: function() { this.on( 'change:menu', this._menu, this ); this.on( 'change:titleMode', this._title, this ); this.on( 'change:content', this._content, this ); this.on( 'change:toolbar', this._toolbar, this ); this.frame.on( 'title:render:default', this._renderTitle, this ); this._title(); this._menu(); this._toolbar(); this._content(); this._router(); }, _deactivate: function() { this.active = false; this.frame.off( 'title:render:default', this._renderTitle, this ); this.off( 'change:menu', this._menu, this ); this.off( 'change:titleMode', this._title, this ); this.off( 'change:content', this._content, this ); this.off( 'change:toolbar', this._toolbar, this ); }, _title: function() { this.frame.title.render( this.get('titleMode') || 'default' ); }, _renderTitle: function( view ) { view.$el.text( this.get('title') || '' ); }, _router: function() { var router = this.frame.router, mode = this.get('router'), view; this.frame.$el.toggleClass( 'hide-router', ! mode ); if ( ! mode ) return; this.frame.router.render( mode ); view = router.get(); if ( view && view.select ) view.select( this.frame.content.mode() ); }, _menu: function() { var menu = this.frame.menu, mode = this.get('menu'), view; if ( ! mode ) return; menu.mode( mode ); view = menu.get(); if ( view && view.select ) view.select( this.id ); }, _updateMenu: function() { var previous = this.previous('menu'), menu = this.get('menu'); if ( previous ) this.frame.off( 'menu:render:' + previous, this._renderMenu, this ); if ( menu ) this.frame.on( 'menu:render:' + menu, this._renderMenu, this ); }, _renderMenu: function( view ) { var menuItem = this.get('menuItem'), title = this.get('title'), priority = this.get('priority'); if ( ! menuItem && title ) { menuItem = { text: title }; if ( priority ) menuItem.priority = priority; } if ( ! menuItem ) return; view.set( this.id, menuItem ); } }); _.each(['toolbar','content'], function( region ) { media.controller.State.prototype[ '_' + region ] = function() { var mode = this.get( region ); if ( mode ) this.frame[ region ].render( mode ); }; }); // wp.media.controller.Library // --------------------------- media.controller.Library = media.controller.State.extend({ defaults: { id: 'library', multiple: false, // false, 'add', 'reset' describe: false, toolbar: 'select', sidebar: 'settings', content: 'upload', router: 'browse', menu: 'default', searchable: true, filterable: false, sortable: true, title: l10n.mediaLibraryTitle, // Uses a user setting to override the content mode. contentUserSetting: true, // Sync the selection from the last state when 'multiple' matches. syncSelection: true }, initialize: function() { var selection = this.get('selection'), props; // If a library isn't provided, query all media items. if ( ! this.get('library') ) this.set( 'library', media.query() ); // If a selection instance isn't provided, create one. if ( ! (selection instanceof media.model.Selection) ) { props = selection; if ( ! props ) { props = this.get('library').props.toJSON(); props = _.omit( props, 'orderby', 'query' ); } // If the `selection` attribute is set to an object, // it will use those values as the selection instance's // `props` model. Otherwise, it will copy the library's // `props` model. this.set( 'selection', new media.model.Selection( null, { multiple: this.get('multiple'), props: props }) ); } if ( ! this.get('edge') ) this.set( 'edge', 120 ); if ( ! this.get('gutter') ) this.set( 'gutter', 8 ); this.resetDisplays(); }, activate: function() { this.syncSelection(); wp.Uploader.queue.on( 'add', this.uploading, this ); this.get('selection').on( 'add remove reset', this.refreshContent, this ); if ( this.get('contentUserSetting') ) { this.frame.on( 'content:activate', this.saveContentMode, this ); this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) ); } }, deactivate: function() { this.recordSelection(); this.frame.off( 'content:activate', this.saveContentMode, this ); // Unbind all event handlers that use this state as the context // from the selection. this.get('selection').off( null, null, this ); wp.Uploader.queue.off( null, null, this ); }, reset: function() { this.get('selection').reset(); this.resetDisplays(); this.refreshContent(); }, resetDisplays: function() { var defaultProps = media.view.settings.defaultProps; this._displays = []; this._defaultDisplaySettings = { align: defaultProps.align || getUserSetting( 'align', 'none' ), size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ), link: defaultProps.link || getUserSetting( 'urlbutton', 'file' ) }; }, display: function( attachment ) { var displays = this._displays; if ( ! displays[ attachment.cid ] ) displays[ attachment.cid ] = new Backbone.Model( this.defaultDisplaySettings( attachment ) ); return displays[ attachment.cid ]; }, defaultDisplaySettings: function( attachment ) { settings = this._defaultDisplaySettings; if ( settings.canEmbed = this.canEmbed( attachment ) ) settings.link = 'embed'; return settings; }, canEmbed: function( attachment ) { // If uploading, we know the filename but not the mime type. if ( ! attachment.get('uploading') ) { var type = attachment.get('type'); if ( type !== 'audio' && type !== 'video' ) return false; } return _.contains( media.view.settings.embedExts, attachment.get('filename').split('.').pop() ); }, syncSelection: function() { var selection = this.get('selection'), manager = this.frame._selection; if ( ! this.get('syncSelection') || ! manager || ! selection ) return; // If the selection supports multiple items, validate the stored // attachments based on the new selection's conditions. Record // the attachments that are not included; we'll maintain a // reference to those. Other attachments are considered in flux. if ( selection.multiple ) { selection.reset( [], { silent: true }); selection.validateAll( manager.attachments ); manager.difference = _.difference( manager.attachments.models, selection.models ); } // Sync the selection's single item with the master. selection.single( manager.single ); }, recordSelection: function() { var selection = this.get('selection'), manager = this.frame._selection, filtered; if ( ! this.get('syncSelection') || ! manager || ! selection ) return; // Record the currently active attachments, which is a combination // of the selection's attachments and the set of selected // attachments that this specific selection considered invalid. // Reset the difference and record the single attachment. if ( selection.multiple ) { manager.attachments.reset( selection.toArray().concat( manager.difference ) ); manager.difference = []; } else { manager.attachments.add( selection.toArray() ); } manager.single = selection._single; }, refreshContent: function() { var selection = this.get('selection'), frame = this.frame, router = frame.router.get(), mode = frame.content.mode(); // If the state is active, no items are selected, and the current // content mode is not an option in the state's router (provided // the state has a router), reset the content mode to the default. if ( this.active && ! selection.length && router && ! router.get( mode ) ) this.frame.content.render( this.get('content') ); }, uploading: function( attachment ) { var content = this.frame.content; // If the uploader was selected, navigate to the browser. if ( 'upload' === content.mode() ) this.frame.content.mode('browse'); // Automatically select any uploading attachments. // // Selections that don't support multiple attachments automatically // limit themselves to one attachment (in this case, the last // attachment in the upload queue). this.get('selection').add( attachment ); }, saveContentMode: function() { // Only track the browse router on library states. if ( 'browse' !== this.get('router') ) return; var mode = this.frame.content.mode(), view = this.frame.router.get(); if ( view && view.get( mode ) ) setUserSetting( 'libraryContent', mode ); } }); // wp.media.controller.GalleryEdit // ------------------------------- media.controller.GalleryEdit = media.controller.Library.extend({ defaults: { id: 'gallery-edit', multiple: false, describe: true, edge: 199, editing: false, sortable: true, searchable: false, toolbar: 'gallery-edit', content: 'browse', title: l10n.editGalleryTitle, priority: 60, dragInfo: true, // Don't sync the selection, as the Edit Gallery library // *is* the selection. syncSelection: false }, initialize: function() { // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', new media.model.Selection() ); // The single `Attachment` view to be used in the `Attachments` view. if ( ! this.get('AttachmentView') ) this.set( 'AttachmentView', media.view.Attachment.EditLibrary ); media.controller.Library.prototype.initialize.apply( this, arguments ); }, activate: function() { var library = this.get('library'); // Limit the library to images only. library.props.set( 'type', 'image' ); // Watch for uploaded attachments. this.get('library').observe( wp.Uploader.queue ); this.frame.on( 'content:render:browse', this.gallerySettings, this ); media.controller.Library.prototype.activate.apply( this, arguments ); }, deactivate: function() { // Stop watching for uploaded attachments. this.get('library').unobserve( wp.Uploader.queue ); this.frame.off( 'content:render:browse', this.gallerySettings, this ); media.controller.Library.prototype.deactivate.apply( this, arguments ); }, gallerySettings: function( browser ) { var library = this.get('library'); if ( ! library || ! browser ) return; library.gallery = library.gallery || new Backbone.Model(); browser.sidebar.set({ gallery: new media.view.Settings.Gallery({ controller: this, model: library.gallery, priority: 40 }) }); browser.toolbar.set( 'reverse', { text: l10n.reverseOrder, priority: 80, click: function() { library.reset( library.toArray().reverse() ); } }); } }); // wp.media.controller.GalleryAdd // --------------------------------- media.controller.GalleryAdd = media.controller.Library.extend({ defaults: _.defaults({ id: 'gallery-library', filterable: 'uploaded', multiple: 'add', menu: 'gallery', toolbar: 'gallery-add', title: l10n.addToGalleryTitle, priority: 100, // Don't sync the selection, as the Edit Gallery library // *is* the selection. syncSelection: false }, media.controller.Library.prototype.defaults ), initialize: function() { // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', media.query({ type: 'image' }) ); media.controller.Library.prototype.initialize.apply( this, arguments ); }, activate: function() { var library = this.get('library'), edit = this.frame.state('gallery-edit').get('library'); if ( this.editLibrary && this.editLibrary !== edit ) library.unobserve( this.editLibrary ); // Accepts attachments that exist in the original library and // that do not exist in gallery's library. library.validator = function( attachment ) { return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments ); }; // Reset the library to ensure that all attachments are re-added // to the collection. Do so silently, as calling `observe` will // trigger the `reset` event. library.reset( library.mirroring.models, { silent: true }); library.observe( edit ); this.editLibrary = edit; media.controller.Library.prototype.activate.apply( this, arguments ); } }); // wp.media.controller.FeaturedImage // --------------------------------- media.controller.FeaturedImage = media.controller.Library.extend({ defaults: _.defaults({ id: 'featured-image', filterable: 'uploaded', multiple: false, toolbar: 'featured-image', title: l10n.setFeaturedImageTitle, priority: 60, syncSelection: false }, media.controller.Library.prototype.defaults ), initialize: function() { var library, comparator; // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', media.query({ type: 'image' }) ); media.controller.Library.prototype.initialize.apply( this, arguments ); library = this.get('library'); comparator = library.comparator; // Overload the library's comparator to push items that are not in // the mirrored query to the front of the aggregate collection. library.comparator = function( a, b ) { var aInQuery = !! this.mirroring.get( a.cid ), bInQuery = !! this.mirroring.get( b.cid ); if ( ! aInQuery && bInQuery ) return -1; else if ( aInQuery && ! bInQuery ) return 1; else return comparator.apply( this, arguments ); }; // Add all items in the selection to the library, so any featured // images that are not initially loaded still appear. library.observe( this.get('selection') ); }, activate: function() { this.updateSelection(); this.frame.on( 'open', this.updateSelection, this ); media.controller.Library.prototype.activate.apply( this, arguments ); }, deactivate: function() { this.frame.off( 'open', this.updateSelection, this ); media.controller.Library.prototype.deactivate.apply( this, arguments ); }, updateSelection: function() { var selection = this.get('selection'), id = media.view.settings.post.featuredImageId, attachment; if ( '' !== id && -1 !== id ) { attachment = Attachment.get( id ); attachment.fetch(); } selection.reset( attachment ? [ attachment ] : [] ); } }); // wp.media.controller.Embed // ------------------------- media.controller.Embed = media.controller.State.extend({ defaults: { id: 'embed', url: '', menu: 'default', content: 'embed', toolbar: 'main-embed', type: 'link', title: l10n.insertFromUrlTitle, priority: 120 }, // The amount of time used when debouncing the scan. sensitivity: 200, initialize: function() { this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity ); this.props = new Backbone.Model({ url: '' }); this.props.on( 'change:url', this.debouncedScan, this ); this.props.on( 'change:url', this.refresh, this ); this.on( 'scan', this.scanImage, this ); }, scan: function() { var scanners, embed = this, attributes = { type: 'link', scanners: [] }; // Scan is triggered with the list of `attributes` to set on the // state, useful for the 'type' attribute and 'scanners' attribute, // an array of promise objects for asynchronous scan operations. if ( this.props.get('url') ) this.trigger( 'scan', attributes ); if ( attributes.scanners.length ) { scanners = attributes.scanners = $.when.apply( $, attributes.scanners ); scanners.always( function() { if ( embed.get('scanners') === scanners ) embed.set( 'loading', false ); }); } else { attributes.scanners = null; } attributes.loading = !! attributes.scanners; this.set( attributes ); }, scanImage: function( attributes ) { var frame = this.frame, state = this, url = this.props.get('url'), image = new Image(), deferred = $.Deferred(); attributes.scanners.push( deferred.promise() ); // Try to load the image and find its width/height. image.onload = function() { deferred.resolve(); if ( state !== frame.state() || url !== state.props.get('url') ) return; state.set({ type: 'image' }); state.props.set({ width: image.width, height: image.height }); }; image.onerror = deferred.reject; image.src = url; }, refresh: function() { this.frame.toolbar.get().refresh(); }, reset: function() { this.props.clear().set({ url: '' }); if ( this.active ) this.refresh(); } }); /** * ======================================================================== * VIEWS * ======================================================================== */ // wp.media.View // ------------- // // The base view class. // // Undelegating events, removing events from the model, and // removing events from the controller mirror the code for // `Backbone.View.dispose` in Backbone 0.9.8 development. // // This behavior has since been removed, and should not be used // outside of the media manager. media.View = wp.Backbone.View.extend({ constructor: function( options ) { if ( options && options.controller ) this.controller = options.controller; wp.Backbone.View.apply( this, arguments ); }, dispose: function() { // Undelegating events, removing events from the model, and // removing events from the controller mirror the code for // `Backbone.View.dispose` in Backbone 0.9.8 development. this.undelegateEvents(); if ( this.model && this.model.off ) this.model.off( null, null, this ); if ( this.collection && this.collection.off ) this.collection.off( null, null, this ); // Unbind controller events. if ( this.controller && this.controller.off ) this.controller.off( null, null, this ); return this; }, remove: function() { this.dispose(); return wp.Backbone.View.prototype.remove.apply( this, arguments ); } }); /** * wp.media.view.Frame */ media.view.Frame = media.View.extend({ initialize: function() { this._createRegions(); this._createStates(); }, _createRegions: function() { // Clone the regions array. this.regions = this.regions ? this.regions.slice() : []; // Initialize regions. _.each( this.regions, function( region ) { this[ region ] = new media.controller.Region({ view: this, id: region, selector: '.media-frame-' + region }); }, this ); }, _createStates: function() { // Create the default `states` collection. this.states = new Backbone.Collection( null, { model: media.controller.State }); // Ensure states have a reference to the frame. this.states.on( 'add', function( model ) { model.frame = this; model.trigger('ready'); }, this ); if ( this.options.states ) this.states.add( this.options.states ); }, reset: function() { this.states.invoke( 'trigger', 'reset' ); return this; } }); // Make the `Frame` a `StateMachine`. _.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype ); /** * wp.media.view.MediaFrame */ media.view.MediaFrame = media.view.Frame.extend({ className: 'media-frame', template: media.template('media-frame'), regions: ['menu','title','content','toolbar','router'], initialize: function() { media.view.Frame.prototype.initialize.apply( this, arguments ); _.defaults( this.options, { title: '', modal: true, uploader: true }); // Ensure core UI is enabled. this.$el.addClass('wp-core-ui'); // Initialize modal container view. if ( this.options.modal ) { this.modal = new media.view.Modal({ controller: this, title: this.options.title }); this.modal.content( this ); } // Force the uploader off if the upload limit has been exceeded or // if the browser isn't supported. if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) this.options.uploader = false; // Initialize window-wide uploader. if ( this.options.uploader ) { this.uploader = new media.view.UploaderWindow({ controller: this, uploader: { dropzone: this.modal ? this.modal.$el : this.$el, container: this.$el } }); this.views.set( '.media-frame-uploader', this.uploader ); } this.on( 'attach', _.bind( this.views.ready, this.views ), this ); // Bind default title creation. this.on( 'title:create:default', this.createTitle, this ); this.title.mode('default'); // Bind default menu. this.on( 'menu:create:default', this.createMenu, this ); }, render: function() { // Activate the default state if no active state exists. if ( ! this.state() && this.options.state ) this.setState( this.options.state ); return media.view.Frame.prototype.render.apply( this, arguments ); }, createTitle: function( title ) { title.view = new media.View({ controller: this, tagName: 'h1' }); }, createMenu: function( menu ) { menu.view = new media.view.Menu({ controller: this }); }, createToolbar: function( toolbar ) { toolbar.view = new media.view.Toolbar({ controller: this }); }, createRouter: function( router ) { router.view = new media.view.Router({ controller: this }); }, createIframeStates: function( options ) { var settings = media.view.settings, tabs = settings.tabs, tabUrl = settings.tabUrl, $postId; if ( ! tabs || ! tabUrl ) return; // Add the post ID to the tab URL if it exists. $postId = $('#post_ID'); if ( $postId.length ) tabUrl += '&post_id=' + $postId.val(); // Generate the tab states. _.each( tabs, function( title, id ) { var frame = this.state( 'iframe:' + id ).set( _.defaults({ tab: id, src: tabUrl + '&tab=' + id, title: title, content: 'iframe', menu: 'default' }, options ) ); }, this ); this.on( 'content:create:iframe', this.iframeContent, this ); this.on( 'menu:render:default', this.iframeMenu, this ); this.on( 'open', this.hijackThickbox, this ); this.on( 'close', this.restoreThickbox, this ); }, iframeContent: function( content ) { this.$el.addClass('hide-toolbar'); content.view = new media.view.Iframe({ controller: this }); }, iframeMenu: function( view ) { var views = {}; if ( ! view ) return; _.each( media.view.settings.tabs, function( title, id ) { views[ 'iframe:' + id ] = { text: this.state( 'iframe:' + id ).get('title'), priority: 200 }; }, this ); view.set( views ); }, hijackThickbox: function() { var frame = this; if ( ! window.tb_remove || this._tb_remove ) return; this._tb_remove = window.tb_remove; window.tb_remove = function() { frame.close(); frame.reset(); frame.setState( frame.options.state ); frame._tb_remove.call( window ); }; }, restoreThickbox: function() { if ( ! this._tb_remove ) return; window.tb_remove = this._tb_remove; delete this._tb_remove; } }); // Map some of the modal's methods to the frame. _.each(['open','close','attach','detach','escape'], function( method ) { media.view.MediaFrame.prototype[ method ] = function( view ) { if ( this.modal ) this.modal[ method ].apply( this.modal, arguments ); return this; }; }); /** * wp.media.view.MediaFrame.Select */ media.view.MediaFrame.Select = media.view.MediaFrame.extend({ initialize: function() { media.view.MediaFrame.prototype.initialize.apply( this, arguments ); _.defaults( this.options, { selection: [], library: {}, multiple: false, state: 'library' }); this.createSelection(); this.createStates(); this.bindHandlers(); }, createSelection: function() { var controller = this, selection = this.options.selection; if ( ! (selection instanceof media.model.Selection) ) { this.options.selection = new media.model.Selection( selection, { multiple: this.options.multiple }); } this._selection = { attachments: new Attachments(), difference: [] }; }, createStates: function() { var options = this.options; if ( this.options.states ) return; // Add the default states. this.states.add([ // Main states. new media.controller.Library({ library: media.query( options.library ), multiple: options.multiple, title: options.title, priority: 20 }) ]); }, bindHandlers: function() { this.on( 'router:create:browse', this.createRouter, this ); this.on( 'router:render:browse', this.browseRouter, this ); this.on( 'content:create:browse', this.browseContent, this ); this.on( 'content:render:upload', this.uploadContent, this ); this.on( 'toolbar:create:select', this.createSelectToolbar, this ); }, // Routers browseRouter: function( view ) { view.set({ upload: { text: l10n.uploadFilesTitle, priority: 20 }, browse: { text: l10n.mediaLibraryTitle, priority: 40 } }); }, // Content browseContent: function( content ) { var state = this.state(); this.$el.removeClass('hide-toolbar'); // Browse our library of attachments. content.view = new media.view.AttachmentsBrowser({ controller: this, collection: state.get('library'), selection: state.get('selection'), model: state, sortable: state.get('sortable'), search: state.get('searchable'), filters: state.get('filterable'), display: state.get('displaySettings'), dragInfo: state.get('dragInfo'), AttachmentView: state.get('AttachmentView') }); }, uploadContent: function() { this.$el.removeClass('hide-toolbar'); this.content.set( new media.view.UploaderInline({ controller: this }) ); }, // Toolbars createSelectToolbar: function( toolbar, options ) { options = options || this.options.button || {}; options.controller = this; toolbar.view = new media.view.Toolbar.Select( options ); } }); /** * wp.media.view.MediaFrame.Post */ media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({ initialize: function() { _.defaults( this.options, { multiple: true, editing: false, state: 'insert' }); media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments ); this.createIframeStates(); }, createStates: function() { var options = this.options; // Add the default states. this.states.add([ // Main states. new media.controller.Library({ id: 'insert', title: l10n.insertMediaTitle, priority: 20, toolbar: 'main-insert', filterable: 'all', library: media.query( options.library ), multiple: options.multiple ? 'reset' : false, editable: true, // If the user isn't allowed to edit fields, // can they still edit it locally? allowLocalEdits: true, // Show the attachment display settings. displaySettings: true, // Update user settings when users adjust the // attachment display settings. displayUserSettings: true }), new media.controller.Library({ id: 'gallery', title: l10n.createGalleryTitle, priority: 40, toolbar: 'main-gallery', filterable: 'uploaded', multiple: 'add', editable: false, library: media.query( _.defaults({ type: 'image' }, options.library ) ) }), // Embed states. new media.controller.Embed(), // Gallery states. new media.controller.GalleryEdit({ library: options.selection, editing: options.editing, menu: 'gallery' }), new media.controller.GalleryAdd() ]); if ( media.view.settings.post.featuredImageId ) { this.states.add( new media.controller.FeaturedImage() ); } }, bindHandlers: function() { media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments ); this.on( 'menu:create:gallery', this.createMenu, this ); this.on( 'toolbar:create:main-insert', this.createToolbar, this ); this.on( 'toolbar:create:main-gallery', this.createToolbar, this ); this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this ); this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this ); var handlers = { menu: { 'default': 'mainMenu', 'gallery': 'galleryMenu' }, content: { 'embed': 'embedContent', 'edit-selection': 'editSelectionContent' }, toolbar: { 'main-insert': 'mainInsertToolbar', 'main-gallery': 'mainGalleryToolbar', 'gallery-edit': 'galleryEditToolbar', 'gallery-add': 'galleryAddToolbar' } }; _.each( handlers, function( regionHandlers, region ) { _.each( regionHandlers, function( callback, handler ) { this.on( region + ':render:' + handler, this[ callback ], this ); }, this ); }, this ); }, // Menus mainMenu: function( view ) { view.set({ 'library-separator': new media.View({ className: 'separator', priority: 100 }) }); }, galleryMenu: function( view ) { var lastState = this.lastState(), previous = lastState && lastState.id, frame = this; view.set({ cancel: { text: l10n.cancelGalleryTitle, priority: 20, click: function() { if ( previous ) frame.setState( previous ); else frame.close(); } }, separateCancel: new media.View({ className: 'separator', priority: 40 }) }); }, // Content embedContent: function() { var view = new media.view.Embed({ controller: this, model: this.state() }).render(); this.content.set( view ); view.url.focus(); }, editSelectionContent: function() { var state = this.state(), selection = state.get('selection'), view; view = new media.view.AttachmentsBrowser({ controller: this, collection: selection, selection: selection, model: state, sortable: true, search: false, dragInfo: true, AttachmentView: media.view.Attachment.EditSelection }).render(); view.toolbar.set( 'backToLibrary', { text: l10n.returnToLibrary, priority: -100, click: function() { this.controller.content.mode('browse'); } }); // Browse our library of attachments. this.content.set( view ); }, // Toolbars selectionStatusToolbar: function( view ) { var editable = this.state().get('editable'); view.set( 'selection', new media.view.Selection({ controller: this, collection: this.state().get('selection'), priority: -40, // If the selection is editable, pass the callback to // switch the content mode. editable: editable && function() { this.controller.content.mode('edit-selection'); } }).render() ); }, mainInsertToolbar: function( view ) { var controller = this; this.selectionStatusToolbar( view ); view.set( 'insert', { style: 'primary', priority: 80, text: l10n.insertIntoPost, requires: { selection: true }, click: function() { var state = controller.state(), selection = state.get('selection'); controller.close(); state.trigger( 'insert', selection ).reset(); } }); }, mainGalleryToolbar: function( view ) { var controller = this; this.selectionStatusToolbar( view ); view.set( 'gallery', { style: 'primary', text: l10n.createNewGallery, priority: 60, requires: { selection: true }, click: function() { var selection = controller.state().get('selection'), edit = controller.state('gallery-edit'), models = selection.where({ type: 'image' }); edit.set( 'library', new media.model.Selection( models, { props: selection.props.toJSON(), multiple: true }) ); this.controller.setState('gallery-edit'); } }); }, featuredImageToolbar: function( toolbar ) { this.createSelectToolbar( toolbar, { text: l10n.setFeaturedImage, state: this.options.state }); }, mainEmbedToolbar: function( toolbar ) { toolbar.view = new media.view.Toolbar.Embed({ controller: this }); }, galleryEditToolbar: function() { var editing = this.state().get('editing'); this.toolbar.set( new media.view.Toolbar({ controller: this, items: { insert: { style: 'primary', text: editing ? l10n.updateGallery : l10n.insertGallery, priority: 80, requires: { library: true }, click: function() { var controller = this.controller, state = controller.state(); controller.close(); state.trigger( 'update', state.get('library') ); // Restore and reset the default state. controller.setState( controller.options.state ); controller.reset(); } } } }) ); }, galleryAddToolbar: function() { this.toolbar.set( new media.view.Toolbar({ controller: this, items: { insert: { style: 'primary', text: l10n.addToGallery, priority: 80, requires: { selection: true }, click: function() { var controller = this.controller, state = controller.state(), edit = controller.state('gallery-edit'); edit.get('library').add( state.get('selection').models ); state.trigger('reset'); controller.setState('gallery-edit'); } } } }) ); } }); /** * wp.media.view.Modal */ media.view.Modal = media.View.extend({ tagName: 'div', template: media.template('media-modal'), attributes: { tabindex: 0 }, events: { 'click .media-modal-backdrop, .media-modal-close': 'escapeHandler', 'keydown': 'keydown' }, initialize: function() { _.defaults( this.options, { container: document.body, title: '', propagate: true, freeze: true }); }, prepare: function() { return { title: this.options.title }; }, attach: function() { if ( this.views.attached ) return this; if ( ! this.views.rendered ) this.render(); this.$el.appendTo( this.options.container ); // Manually mark the view as attached and trigger ready. this.views.attached = true; this.views.ready(); return this.propagate('attach'); }, detach: function() { if ( this.$el.is(':visible') ) this.close(); this.$el.detach(); this.views.attached = false; return this.propagate('detach'); }, open: function() { var $el = this.$el, options = this.options; if ( $el.is(':visible') ) return this; if ( ! this.views.attached ) this.attach(); // If the `freeze` option is set, record the window's scroll position. if ( options.freeze ) { this._freeze = { scrollTop: $( window ).scrollTop() }; } $el.show().focus(); return this.propagate('open'); }, close: function( options ) { var freeze = this._freeze; if ( ! this.views.attached || ! this.$el.is(':visible') ) return this; this.$el.hide(); this.propagate('close'); // If the `freeze` option is set, restore the container's scroll position. if ( freeze ) { $( window ).scrollTop( freeze.scrollTop ); } if ( options && options.escape ) this.propagate('escape'); return this; }, escape: function() { return this.close({ escape: true }); }, escapeHandler: function( event ) { event.preventDefault(); this.escape(); }, content: function( content ) { this.views.set( '.media-modal-content', content ); return this; }, // Triggers a modal event and if the `propagate` option is set, // forwards events to the modal's controller. propagate: function( id ) { this.trigger( id ); if ( this.options.propagate ) this.controller.trigger( id ); return this; }, keydown: function( event ) { // Close the modal when escape is pressed. if ( 27 === event.which ) { event.preventDefault(); this.escape(); return; } } }); // wp.media.view.FocusManager // ---------------------------- media.view.FocusManager = media.View.extend({ events: { keydown: 'recordTab', focusin: 'updateIndex' }, focus: function() { if ( _.isUndefined( this.index ) ) return; // Update our collection of `$tabbables`. this.$tabbables = this.$(':tabbable'); // If tab is saved, focus it. this.$tabbables.eq( this.index ).focus(); }, recordTab: function( event ) { // Look for the tab key. if ( 9 !== event.keyCode ) return; // First try to update the index. if ( _.isUndefined( this.index ) ) this.updateIndex( event ); // If we still don't have an index, bail. if ( _.isUndefined( this.index ) ) return; var index = this.index + ( event.shiftKey ? -1 : 1 ); if ( index >= 0 && index < this.$tabbables.length ) this.index = index; else delete this.index; }, updateIndex: function( event ) { this.$tabbables = this.$(':tabbable'); var index = this.$tabbables.index( event.target ); if ( -1 === index ) delete this.index; else this.index = index; } }); // wp.media.view.UploaderWindow // ---------------------------- media.view.UploaderWindow = media.View.extend({ tagName: 'div', className: 'uploader-window', template: media.template('uploader-window'), initialize: function() { var uploader; this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body'); uploader = this.options.uploader = _.defaults( this.options.uploader || {}, { dropzone: this.$el, browser: this.$browser, params: {} }); // Ensure the dropzone is a jQuery collection. if ( uploader.dropzone && ! (uploader.dropzone instanceof $) ) uploader.dropzone = $( uploader.dropzone ); this.controller.on( 'activate', this.refresh, this ); }, refresh: function() { if ( this.uploader ) this.uploader.refresh(); }, ready: function() { var postId = media.view.settings.post.id, dropzone; // If the uploader already exists, bail. if ( this.uploader ) return; if ( postId ) this.options.uploader.params.post_id = postId; this.uploader = new wp.Uploader( this.options.uploader ); dropzone = this.uploader.dropzone; dropzone.on( 'dropzone:enter', _.bind( this.show, this ) ); dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) ); }, show: function() { var $el = this.$el.show(); // Ensure that the animation is triggered by waiting until // the transparent element is painted into the DOM. _.defer( function() { $el.css({ opacity: 1 }); }); }, hide: function() { var $el = this.$el.css({ opacity: 0 }); media.transition( $el ).done( function() { // Transition end events are subject to race conditions. // Make sure that the value is set as intended. if ( '0' === $el.css('opacity') ) $el.hide(); }); } }); media.view.UploaderInline = media.View.extend({ tagName: 'div', className: 'uploader-inline', template: media.template('uploader-inline'), initialize: function() { _.defaults( this.options, { message: '', status: true }); if ( ! this.options.$browser && this.controller.uploader ) this.options.$browser = this.controller.uploader.$browser; if ( _.isUndefined( this.options.postId ) ) this.options.postId = media.view.settings.post.id; if ( this.options.status ) { this.views.set( '.upload-inline-status', new media.view.UploaderStatus({ controller: this.controller }) ); } }, dispose: function() { if ( this.disposing ) return media.View.prototype.dispose.apply( this, arguments ); // Run remove on `dispose`, so we can be sure to refresh the // uploader with a view-less DOM. Track whether we're disposing // so we don't trigger an infinite loop. this.disposing = true; return this.remove(); }, remove: function() { var result = media.View.prototype.remove.apply( this, arguments ); _.defer( _.bind( this.refresh, this ) ); return result; }, refresh: function() { var uploader = this.controller.uploader; if ( uploader ) uploader.refresh(); }, ready: function() { var $browser = this.options.$browser, $placeholder; if ( this.controller.uploader ) { $placeholder = this.$('.browser'); // Check if we've already replaced the placeholder. if ( $placeholder[0] === $browser[0] ) return; $browser.detach().text( $placeholder.text() ); $browser[0].className = $placeholder[0].className; $placeholder.replaceWith( $browser.show() ); } this.refresh(); return this; } }); /** * wp.media.view.UploaderStatus */ media.view.UploaderStatus = media.View.extend({ className: 'media-uploader-status', template: media.template('uploader-status'), events: { 'click .upload-dismiss-errors': 'dismiss' }, initialize: function() { this.queue = wp.Uploader.queue; this.queue.on( 'add remove reset', this.visibility, this ); this.queue.on( 'add remove reset change:percent', this.progress, this ); this.queue.on( 'add remove reset change:uploading', this.info, this ); this.errors = wp.Uploader.errors; this.errors.reset(); this.errors.on( 'add remove reset', this.visibility, this ); this.errors.on( 'add', this.error, this ); }, dispose: function() { wp.Uploader.queue.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, visibility: function() { this.$el.toggleClass( 'uploading', !! this.queue.length ); this.$el.toggleClass( 'errors', !! this.errors.length ); this.$el.toggle( !! this.queue.length || !! this.errors.length ); }, ready: function() { _.each({ '$bar': '.media-progress-bar div', '$index': '.upload-index', '$total': '.upload-total', '$filename': '.upload-filename' }, function( selector, key ) { this[ key ] = this.$( selector ); }, this ); this.visibility(); this.progress(); this.info(); }, progress: function() { var queue = this.queue, $bar = this.$bar, memo = 0; if ( ! $bar || ! queue.length ) return; $bar.width( ( queue.reduce( function( memo, attachment ) { if ( ! attachment.get('uploading') ) return memo + 100; var percent = attachment.get('percent'); return memo + ( _.isNumber( percent ) ? percent : 100 ); }, 0 ) / queue.length ) + '%' ); }, info: function() { var queue = this.queue, index = 0, active; if ( ! queue.length ) return; active = this.queue.find( function( attachment, i ) { index = i; return attachment.get('uploading'); }); this.$index.text( index + 1 ); this.$total.text( queue.length ); this.$filename.html( active ? this.filename( active.get('filename') ) : '' ); }, filename: function( filename ) { return media.truncate( _.escape( filename ), 24 ); }, error: function( error ) { this.views.add( '.upload-errors', new media.view.UploaderStatusError({ filename: this.filename( error.get('file').name ), message: error.get('message') }), { at: 0 }); }, dismiss: function( event ) { var errors = this.views.get('.upload-errors'); event.preventDefault(); if ( errors ) _.invoke( errors, 'remove' ); wp.Uploader.errors.reset(); } }); media.view.UploaderStatusError = media.View.extend({ className: 'upload-error', template: media.template('uploader-status-error') }); /** * wp.media.view.Toolbar */ media.view.Toolbar = media.View.extend({ tagName: 'div', className: 'media-toolbar', initialize: function() { var state = this.controller.state(), selection = this.selection = state.get('selection'), library = this.library = state.get('library'); this._views = {}; // The toolbar is composed of two `PriorityList` views. this.primary = new media.view.PriorityList(); this.secondary = new media.view.PriorityList(); this.primary.$el.addClass('media-toolbar-primary'); this.secondary.$el.addClass('media-toolbar-secondary'); this.views.set([ this.secondary, this.primary ]); if ( this.options.items ) this.set( this.options.items, { silent: true }); if ( ! this.options.silent ) this.render(); if ( selection ) selection.on( 'add remove reset', this.refresh, this ); if ( library ) library.on( 'add remove reset', this.refresh, this ); }, dispose: function() { if ( this.selection ) this.selection.off( null, null, this ); if ( this.library ) this.library.off( null, null, this ); return media.View.prototype.dispose.apply( this, arguments ); }, ready: function() { this.refresh(); }, set: function( id, view, options ) { var list; options = options || {}; // Accept an object with an `id` : `view` mapping. if ( _.isObject( id ) ) { _.each( id, function( view, id ) { this.set( id, view, { silent: true }); }, this ); } else { if ( ! ( view instanceof Backbone.View ) ) { view.classes = [ 'media-button-' + id ].concat( view.classes || [] ); view = new media.view.Button( view ).render(); } view.controller = view.controller || this.controller; this._views[ id ] = view; list = view.options.priority < 0 ? 'secondary' : 'primary'; this[ list ].set( id, view, options ); } if ( ! options.silent ) this.refresh(); return this; }, get: function( id ) { return this._views[ id ]; }, unset: function( id, options ) { delete this._views[ id ]; this.primary.unset( id, options ); this.secondary.unset( id, options ); if ( ! options || ! options.silent ) this.refresh(); return this; }, refresh: function() { var state = this.controller.state(), library = state.get('library'), selection = state.get('selection'); _.each( this._views, function( button ) { if ( ! button.model || ! button.options || ! button.options.requires ) return; var requires = button.options.requires, disabled = false; // Prevent insertion of attachments if any of them are still uploading disabled = _.some( selection.models, function( attachment ) { return attachment.get('uploading') === true; }); if ( requires.selection && selection && ! selection.length ) disabled = true; else if ( requires.library && library && ! library.length ) disabled = true; button.model.set( 'disabled', disabled ); }); } }); // wp.media.view.Toolbar.Select // ---------------------------- media.view.Toolbar.Select = media.view.Toolbar.extend({ initialize: function() { var options = this.options, controller = options.controller, selection = controller.state().get('selection'); _.bindAll( this, 'clickSelect' ); _.defaults( options, { event: 'select', state: false, reset: true, close: true, text: l10n.select, // Does the button rely on the selection? requires: { selection: true } }); options.items = _.defaults( options.items || {}, { select: { style: 'primary', text: options.text, priority: 80, click: this.clickSelect, requires: options.requires } }); media.view.Toolbar.prototype.initialize.apply( this, arguments ); }, clickSelect: function() { var options = this.options, controller = this.controller; if ( options.close ) controller.close(); if ( options.event ) controller.state().trigger( options.event ); if ( options.state ) controller.setState( options.state ); if ( options.reset ) controller.reset(); } }); // wp.media.view.Toolbar.Embed // --------------------------- media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({ initialize: function() { _.defaults( this.options, { text: l10n.insertIntoPost, requires: false }); media.view.Toolbar.Select.prototype.initialize.apply( this, arguments ); }, refresh: function() { var url = this.controller.state().props.get('url'); this.get('select').model.set( 'disabled', ! url || url === 'http://' ); media.view.Toolbar.Select.prototype.refresh.apply( this, arguments ); } }); /** * wp.media.view.Button */ media.view.Button = media.View.extend({ tagName: 'a', className: 'media-button', attributes: { href: '#' }, events: { 'click': 'click' }, defaults: { text: '', style: '', size: 'large', disabled: false }, initialize: function() { // Create a model with the provided `defaults`. this.model = new Backbone.Model( this.defaults ); // If any of the `options` have a key from `defaults`, apply its // value to the `model` and remove it from the `options object. _.each( this.defaults, function( def, key ) { var value = this.options[ key ]; if ( _.isUndefined( value ) ) return; this.model.set( key, value ); delete this.options[ key ]; }, this ); this.model.on( 'change', this.render, this ); }, render: function() { var classes = [ 'button', this.className ], model = this.model.toJSON(); if ( model.style ) classes.push( 'button-' + model.style ); if ( model.size ) classes.push( 'button-' + model.size ); classes = _.uniq( classes.concat( this.options.classes ) ); this.el.className = classes.join(' '); this.$el.attr( 'disabled', model.disabled ); this.$el.text( this.model.get('text') ); return this; }, click: function( event ) { if ( '#' === this.attributes.href ) event.preventDefault(); if ( this.options.click && ! this.model.get('disabled') ) this.options.click.apply( this, arguments ); } }); /** * wp.media.view.ButtonGroup */ media.view.ButtonGroup = media.View.extend({ tagName: 'div', className: 'button-group button-large media-button-group', initialize: function() { this.buttons = _.map( this.options.buttons || [], function( button ) { if ( button instanceof Backbone.View ) return button; else return new media.view.Button( button ).render(); }); delete this.options.buttons; if ( this.options.classes ) this.$el.addClass( this.options.classes ); }, render: function() { this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() ); return this; } }); /** * wp.media.view.PriorityList */ media.view.PriorityList = media.View.extend({ tagName: 'div', initialize: function() { this._views = {}; this.set( _.extend( {}, this._views, this.options.views ), { silent: true }); delete this.options.views; if ( ! this.options.silent ) this.render(); }, set: function( id, view, options ) { var priority, views, index; options = options || {}; // Accept an object with an `id` : `view` mapping. if ( _.isObject( id ) ) { _.each( id, function( view, id ) { this.set( id, view ); }, this ); return this; } if ( ! (view instanceof Backbone.View) ) view = this.toView( view, id, options ); view.controller = view.controller || this.controller; this.unset( id ); priority = view.options.priority || 10; views = this.views.get() || []; _.find( views, function( existing, i ) { if ( existing.options.priority > priority ) { index = i; return true; } }); this._views[ id ] = view; this.views.add( view, { at: _.isNumber( index ) ? index : views.length || 0 }); return this; }, get: function( id ) { return this._views[ id ]; }, unset: function( id ) { var view = this.get( id ); if ( view ) view.remove(); delete this._views[ id ]; return this; }, toView: function( options ) { return new media.View( options ); } }); /** * wp.media.view.MenuItem */ media.view.MenuItem = media.View.extend({ tagName: 'a', className: 'media-menu-item', attributes: { href: '#' }, events: { 'click': '_click' }, _click: function( event ) { var clickOverride = this.options.click; if ( event ) event.preventDefault(); if ( clickOverride ) clickOverride.call( this ); else this.click(); }, click: function() { var state = this.options.state; if ( state ) this.controller.setState( state ); }, render: function() { var options = this.options; if ( options.text ) this.$el.text( options.text ); else if ( options.html ) this.$el.html( options.html ); return this; } }); /** * wp.media.view.Menu */ media.view.Menu = media.view.PriorityList.extend({ tagName: 'div', className: 'media-menu', property: 'state', ItemView: media.view.MenuItem, region: 'menu', toView: function( options, id ) { options = options || {}; options[ this.property ] = options[ this.property ] || id; return new this.ItemView( options ).render(); }, ready: function() { media.view.PriorityList.prototype.ready.apply( this, arguments ); this.visibility(); }, set: function() { media.view.PriorityList.prototype.set.apply( this, arguments ); this.visibility(); }, unset: function() { media.view.PriorityList.prototype.unset.apply( this, arguments ); this.visibility(); }, visibility: function() { var region = this.region, view = this.controller[ region ].get(), views = this.views.get(), hide = ! views || views.length < 2; if ( this === view ) this.controller.$el.toggleClass( 'hide-' + region, hide ); }, select: function( id ) { var view = this.get( id ); if ( ! view ) return; this.deselect(); view.$el.addClass('active'); }, deselect: function() { this.$el.children().removeClass('active'); } }); /** * wp.media.view.RouterItem */ media.view.RouterItem = media.view.MenuItem.extend({ click: function() { var contentMode = this.options.contentMode; if ( contentMode ) this.controller.content.mode( contentMode ); } }); /** * wp.media.view.Router */ media.view.Router = media.view.Menu.extend({ tagName: 'div', className: 'media-router', property: 'contentMode', ItemView: media.view.RouterItem, region: 'router', initialize: function() { this.controller.on( 'content:render', this.update, this ); media.view.Menu.prototype.initialize.apply( this, arguments ); }, update: function() { var mode = this.controller.content.mode(); if ( mode ) this.select( mode ); } }); /** * wp.media.view.Sidebar */ media.view.Sidebar = media.view.PriorityList.extend({ className: 'media-sidebar' }); /** * wp.media.view.Attachment */ media.view.Attachment = media.View.extend({ tagName: 'li', className: 'attachment', template: media.template('attachment'), events: { 'click .attachment-preview': 'toggleSelectionHandler', 'change [data-setting]': 'updateSetting', 'change [data-setting] input': 'updateSetting', 'change [data-setting] select': 'updateSetting', 'change [data-setting] textarea': 'updateSetting', 'click .close': 'removeFromLibrary', 'click .check': 'removeFromSelection', 'click a': 'preventDefault' }, buttons: {}, initialize: function() { var selection = this.options.selection; this.model.on( 'change:sizes change:uploading', this.render, this ); this.model.on( 'change:title', this._syncTitle, this ); this.model.on( 'change:caption', this._syncCaption, this ); this.model.on( 'change:percent', this.progress, this ); // Update the selection. this.model.on( 'add', this.select, this ); this.model.on( 'remove', this.deselect, this ); if ( selection ) selection.on( 'reset', this.updateSelect, this ); // Update the model's details view. this.model.on( 'selection:single selection:unsingle', this.details, this ); this.details( this.model, this.controller.state().get('selection') ); }, dispose: function() { var selection = this.options.selection; // Make sure all settings are saved before removing the view. this.updateAll(); if ( selection ) selection.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, render: function() { var options = _.defaults( this.model.toJSON(), { orientation: 'landscape', uploading: false, type: '', subtype: '', icon: '', filename: '', caption: '', title: '', dateFormatted: '', width: '', height: '', compat: false, alt: '', description: '' }); options.buttons = this.buttons; options.describe = this.controller.state().get('describe'); if ( 'image' === options.type ) options.size = this.imageSize(); options.can = {}; if ( options.nonces ) { options.can.remove = !! options.nonces['delete']; options.can.save = !! options.nonces.update; } if ( this.controller.state().get('allowLocalEdits') ) options.allowLocalEdits = true; this.views.detach(); this.$el.html( this.template( options ) ); this.$el.toggleClass( 'uploading', options.uploading ); if ( options.uploading ) this.$bar = this.$('.media-progress-bar div'); else delete this.$bar; // Check if the model is selected. this.updateSelect(); // Update the save status. this.updateSave(); this.views.render(); return this; }, progress: function() { if ( this.$bar && this.$bar.length ) this.$bar.width( this.model.get('percent') + '%' ); }, toggleSelectionHandler: function( event ) { var method; if ( event.shiftKey ) method = 'between'; else if ( event.ctrlKey || event.metaKey ) method = 'toggle'; this.toggleSelection({ method: method }); }, toggleSelection: function( options ) { var collection = this.collection, selection = this.options.selection, model = this.model, method = options && options.method, single, between, models, singleIndex, modelIndex; if ( ! selection ) return; single = selection.single(); method = _.isUndefined( method ) ? selection.multiple : method; // If the `method` is set to `between`, select all models that // exist between the current and the selected model. if ( 'between' === method && single && selection.multiple ) { // If the models are the same, short-circuit. if ( single === model ) return; singleIndex = collection.indexOf( single ); modelIndex = collection.indexOf( this.model ); if ( singleIndex < modelIndex ) models = collection.models.slice( singleIndex, modelIndex + 1 ); else models = collection.models.slice( modelIndex, singleIndex + 1 ); selection.add( models ).single( model ); return; // If the `method` is set to `toggle`, just flip the selection // status, regardless of whether the model is the single model. } else if ( 'toggle' === method ) { selection[ this.selected() ? 'remove' : 'add' ]( model ).single( model ); return; } if ( method !== 'add' ) method = 'reset'; if ( this.selected() ) { // If the model is the single model, remove it. // If it is not the same as the single model, // it now becomes the single model. selection[ single === model ? 'remove' : 'single' ]( model ); } else { // If the model is not selected, run the `method` on the // selection. By default, we `reset` the selection, but the // `method` can be set to `add` the model to the selection. selection[ method ]( model ).single( model ); } }, updateSelect: function() { this[ this.selected() ? 'select' : 'deselect' ](); }, selected: function() { var selection = this.options.selection; if ( selection ) return !! selection.get( this.model.cid ); }, select: function( model, collection ) { var selection = this.options.selection; // Check if a selection exists and if it's the collection provided. // If they're not the same collection, bail; we're in another // selection's event loop. if ( ! selection || ( collection && collection !== selection ) ) return; this.$el.addClass('selected'); }, deselect: function( model, collection ) { var selection = this.options.selection; // Check if a selection exists and if it's the collection provided. // If they're not the same collection, bail; we're in another // selection's event loop. if ( ! selection || ( collection && collection !== selection ) ) return; this.$el.removeClass('selected'); }, details: function( model, collection ) { var selection = this.options.selection, details; if ( selection !== collection ) return; details = selection.single(); this.$el.toggleClass( 'details', details === this.model ); }, preventDefault: function( event ) { event.preventDefault(); }, imageSize: function( size ) { var sizes = this.model.get('sizes'); size = size || 'medium'; // Use the provided image size if possible. if ( sizes && sizes[ size ] ) { return _.clone( sizes[ size ] ); } else { return { url: this.model.get('url'), width: this.model.get('width'), height: this.model.get('height'), orientation: this.model.get('orientation') }; } }, updateSetting: function( event ) { var $setting = $( event.target ).closest('[data-setting]'), setting, value; if ( ! $setting.length ) return; setting = $setting.data('setting'); value = event.target.value; if ( this.model.get( setting ) !== value ) this.save( setting, value ); }, // Pass all the arguments to the model's save method. // // Records the aggregate status of all save requests and updates the // view's classes accordingly. save: function() { var view = this, save = this._save = this._save || { status: 'ready' }, request = this.model.save.apply( this.model, arguments ), requests = save.requests ? $.when( request, save.requests ) : request; // If we're waiting to remove 'Saved.', stop. if ( save.savedTimer ) clearTimeout( save.savedTimer ); this.updateSave('waiting'); save.requests = requests; requests.always( function() { // If we've performed another request since this one, bail. if ( save.requests !== requests ) return; view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' ); save.savedTimer = setTimeout( function() { view.updateSave('ready'); delete save.savedTimer; }, 2000 ); }); }, updateSave: function( status ) { var save = this._save = this._save || { status: 'ready' }; if ( status && status !== save.status ) { this.$el.removeClass( 'save-' + save.status ); save.status = status; } this.$el.addClass( 'save-' + save.status ); return this; }, updateAll: function() { var $settings = this.$('[data-setting]'), model = this.model, changed; changed = _.chain( $settings ).map( function( el ) { var $input = $('input, textarea, select, [value]', el ), setting, value; if ( ! $input.length ) return; setting = $(el).data('setting'); value = $input.val(); // Record the value if it changed. if ( model.get( setting ) !== value ) return [ setting, value ]; }).compact().object().value(); if ( ! _.isEmpty( changed ) ) model.save( changed ); }, removeFromLibrary: function( event ) { // Stop propagation so the model isn't selected. event.stopPropagation(); this.collection.remove( this.model ); }, removeFromSelection: function( event ) { var selection = this.options.selection; if ( ! selection ) return; // Stop propagation so the model isn't selected. event.stopPropagation(); selection.remove( this.model ); } }); // Ensure settings remain in sync between attachment views. _.each({ caption: '_syncCaption', title: '_syncTitle' }, function( method, setting ) { media.view.Attachment.prototype[ method ] = function( model, value ) { var $setting = this.$('[data-setting="' + setting + '"]'); if ( ! $setting.length ) return this; // If the updated value is in sync with the value in the DOM, there // is no need to re-render. If we're currently editing the value, // it will automatically be in sync, suppressing the re-render for // the view we're editing, while updating any others. if ( value === $setting.find('input, textarea, select, [value]').val() ) return this; return this.render(); }; }); /** * wp.media.view.Attachment.Library */ media.view.Attachment.Library = media.view.Attachment.extend({ buttons: { check: true } }); /** * wp.media.view.Attachment.EditLibrary */ media.view.Attachment.EditLibrary = media.view.Attachment.extend({ buttons: { close: true } }); /** * wp.media.view.Attachments */ media.view.Attachments = media.View.extend({ tagName: 'ul', className: 'attachments', cssTemplate: media.template('attachments-css'), events: { 'scroll': 'scroll' }, initialize: function() { this.el.id = _.uniqueId('__attachments-view-'); _.defaults( this.options, { refreshSensitivity: 200, refreshThreshold: 3, AttachmentView: media.view.Attachment, sortable: false, resize: true }); this._viewsByCid = {}; this.collection.on( 'add', function( attachment, attachments, options ) { this.views.add( this.createAttachmentView( attachment ), { at: this.collection.indexOf( attachment ) }); }, this ); this.collection.on( 'remove', function( attachment, attachments, options ) { var view = this._viewsByCid[ attachment.cid ]; delete this._viewsByCid[ attachment.cid ]; if ( view ) view.remove(); }, this ); this.collection.on( 'reset', this.render, this ); // Throttle the scroll handler. this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value(); this.initSortable(); _.bindAll( this, 'css' ); this.model.on( 'change:edge change:gutter', this.css, this ); this._resizeCss = _.debounce( _.bind( this.css, this ), this.refreshSensitivity ); if ( this.options.resize ) $(window).on( 'resize.attachments', this._resizeCss ); this.css(); }, dispose: function() { this.collection.props.off( null, null, this ); $(window).off( 'resize.attachments', this._resizeCss ); media.View.prototype.dispose.apply( this, arguments ); }, css: function() { var $css = $( '#' + this.el.id + '-css' ); if ( $css.length ) $css.remove(); media.view.Attachments.$head().append( this.cssTemplate({ id: this.el.id, edge: this.edge(), gutter: this.model.get('gutter') }) ); }, edge: function() { var edge = this.model.get('edge'), gutter, width, columns; if ( ! this.$el.is(':visible') ) return edge; gutter = this.model.get('gutter') * 2; width = this.$el.width() - gutter; columns = Math.ceil( width / ( edge + gutter ) ); edge = Math.floor( ( width - ( columns * gutter ) ) / columns ); return edge; }, initSortable: function() { var collection = this.collection; if ( ! this.options.sortable || ! $.fn.sortable ) return; this.$el.sortable( _.extend({ // If the `collection` has a `comparator`, disable sorting. disabled: !! collection.comparator, // Prevent attachments from being dragged outside the bounding // box of the list. containment: this.$el, // Change the position of the attachment as soon as the // mouse pointer overlaps a thumbnail. tolerance: 'pointer', // Record the initial `index` of the dragged model. start: function( event, ui ) { ui.item.data('sortableIndexStart', ui.item.index()); }, // Update the model's index in the collection. // Do so silently, as the view is already accurate. update: function( event, ui ) { var model = collection.at( ui.item.data('sortableIndexStart') ), comparator = collection.comparator; // Temporarily disable the comparator to prevent `add` // from re-sorting. delete collection.comparator; // Silently shift the model to its new index. collection.remove( model, { silent: true }).add( model, { silent: true, at: ui.item.index() }); // Restore the comparator. collection.comparator = comparator; // Fire the `reset` event to ensure other collections sync. collection.trigger( 'reset', collection ); // If the collection is sorted by menu order, // update the menu order. collection.saveMenuOrder(); } }, this.options.sortable ) ); // If the `orderby` property is changed on the `collection`, // check to see if we have a `comparator`. If so, disable sorting. collection.props.on( 'change:orderby', function() { this.$el.sortable( 'option', 'disabled', !! collection.comparator ); }, this ); this.collection.props.on( 'change:orderby', this.refreshSortable, this ); this.refreshSortable(); }, refreshSortable: function() { if ( ! this.options.sortable || ! $.fn.sortable ) return; // If the `collection` has a `comparator`, disable sorting. var collection = this.collection, orderby = collection.props.get('orderby'), enabled = 'menuOrder' === orderby || ! collection.comparator; this.$el.sortable( 'option', 'disabled', ! enabled ); }, createAttachmentView: function( attachment ) { var view = new this.options.AttachmentView({ controller: this.controller, model: attachment, collection: this.collection, selection: this.options.selection }); return this._viewsByCid[ attachment.cid ] = view; }, prepare: function() { // Create all of the Attachment views, and replace // the list in a single DOM operation. if ( this.collection.length ) { this.views.set( this.collection.map( this.createAttachmentView, this ) ); // If there are no elements, clear the views and load some. } else { this.views.unset(); this.collection.more().done( this.scroll ); } }, ready: function() { // Trigger the scroll event to check if we're within the // threshold to query for additional attachments. this.scroll(); }, scroll: function( event ) { // @todo: is this still necessary? if ( ! this.$el.is(':visible') ) return; if ( this.collection.hasMore() && this.el.scrollHeight < this.el.scrollTop + ( this.el.clientHeight * this.options.refreshThreshold ) ) { this.collection.more().done( this.scroll ); } } }, { $head: (function() { var $head; return function() { return $head = $head || $('head'); }; }()) }); /** * wp.media.view.Search */ media.view.Search = media.View.extend({ tagName: 'input', className: 'search', attributes: { type: 'search', placeholder: l10n.search }, events: { 'input': 'search', 'keyup': 'search', 'change': 'search', 'search': 'search' }, render: function() { this.el.value = this.model.escape('search'); return this; }, search: function( event ) { if ( event.target.value ) this.model.set( 'search', event.target.value ); else this.model.unset('search'); } }); /** * wp.media.view.AttachmentFilters */ media.view.AttachmentFilters = media.View.extend({ tagName: 'select', className: 'attachment-filters', events: { change: 'change' }, keys: [], initialize: function() { this.createFilters(); _.extend( this.filters, this.options.filters ); // Build `<option>` elements. this.$el.html( _.chain( this.filters ).map( function( filter, value ) { return { el: $('<option></option>').val(value).text(filter.text)[0], priority: filter.priority || 50 }; }, this ).sortBy('priority').pluck('el').value() ); this.model.on( 'change', this.select, this ); this.select(); }, createFilters: function() { this.filters = {}; }, change: function( event ) { var filter = this.filters[ this.el.value ]; if ( filter ) this.model.set( filter.props ); }, select: function() { var model = this.model, value = 'all', props = model.toJSON(); _.find( this.filters, function( filter, id ) { var equal = _.all( filter.props, function( prop, key ) { return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] ); }); if ( equal ) return value = id; }); this.$el.val( value ); } }); media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({ createFilters: function() { var type = this.model.get('type'), types = media.view.settings.mimeTypes, text; if ( types && type ) text = types[ type ]; this.filters = { all: { text: text || l10n.allMediaItems, props: { uploadedTo: null, orderby: 'date', order: 'DESC' }, priority: 10 }, uploaded: { text: l10n.uploadedToThisPost, props: { uploadedTo: media.view.settings.post.id, orderby: 'menuOrder', order: 'ASC' }, priority: 20 } }; } }); media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({ createFilters: function() { var filters = {}; _.each( media.view.settings.mimeTypes || {}, function( text, key ) { filters[ key ] = { text: text, props: { type: key, uploadedTo: null, orderby: 'date', order: 'DESC' } }; }); filters.all = { text: l10n.allMediaItems, props: { type: null, uploadedTo: null, orderby: 'date', order: 'DESC' }, priority: 10 }; filters.uploaded = { text: l10n.uploadedToThisPost, props: { type: null, uploadedTo: media.view.settings.post.id, orderby: 'menuOrder', order: 'ASC' }, priority: 20 }; this.filters = filters; } }); /** * wp.media.view.AttachmentsBrowser */ media.view.AttachmentsBrowser = media.View.extend({ tagName: 'div', className: 'attachments-browser', initialize: function() { _.defaults( this.options, { filters: false, search: true, display: false, AttachmentView: media.view.Attachment.Library }); this.createToolbar(); this.updateContent(); this.createSidebar(); this.collection.on( 'add remove reset', this.updateContent, this ); }, dispose: function() { this.options.selection.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, createToolbar: function() { var filters, FiltersConstructor; this.toolbar = new media.view.Toolbar({ controller: this.controller }); this.views.add( this.toolbar ); filters = this.options.filters; if ( 'uploaded' === filters ) FiltersConstructor = media.view.AttachmentFilters.Uploaded; else if ( 'all' === filters ) FiltersConstructor = media.view.AttachmentFilters.All; if ( FiltersConstructor ) { this.toolbar.set( 'filters', new FiltersConstructor({ controller: this.controller, model: this.collection.props, priority: -80 }).render() ); } if ( this.options.search ) { this.toolbar.set( 'search', new media.view.Search({ controller: this.controller, model: this.collection.props, priority: 60 }).render() ); } if ( this.options.dragInfo ) { this.toolbar.set( 'dragInfo', new media.View({ el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0], priority: -40 }) ); } }, updateContent: function() { var view = this; if( ! this.attachments ) this.createAttachments(); if ( ! this.collection.length ) { this.collection.more().done( function() { if ( ! view.collection.length ) view.createUploader(); }); } }, removeContent: function() { _.each(['attachments','uploader'], function( key ) { if ( this[ key ] ) { this[ key ].remove(); delete this[ key ]; } }, this ); }, createUploader: function() { this.removeContent(); this.uploader = new media.view.UploaderInline({ controller: this.controller, status: false, message: l10n.noItemsFound }); this.views.add( this.uploader ); }, createAttachments: function() { this.removeContent(); this.attachments = new media.view.Attachments({ controller: this.controller, collection: this.collection, selection: this.options.selection, model: this.model, sortable: this.options.sortable, // The single `Attachment` view to be used in the `Attachments` view. AttachmentView: this.options.AttachmentView }); this.views.add( this.attachments ); }, createSidebar: function() { var options = this.options, selection = options.selection, sidebar = this.sidebar = new media.view.Sidebar({ controller: this.controller }); this.views.add( sidebar ); if ( this.controller.uploader ) { sidebar.set( 'uploads', new media.view.UploaderStatus({ controller: this.controller, priority: 40 }) ); } selection.on( 'selection:single', this.createSingle, this ); selection.on( 'selection:unsingle', this.disposeSingle, this ); if ( selection.single() ) this.createSingle(); }, createSingle: function() { var sidebar = this.sidebar, single = this.options.selection.single(), views = {}; sidebar.set( 'details', new media.view.Attachment.Details({ controller: this.controller, model: single, priority: 80 }) ); sidebar.set( 'compat', new media.view.AttachmentCompat({ controller: this.controller, model: single, priority: 120 }) ); if ( this.options.display ) { sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({ controller: this.controller, model: this.model.display( single ), attachment: single, priority: 160, userSettings: this.model.get('displayUserSettings') }) ); } }, disposeSingle: function() { var sidebar = this.sidebar; sidebar.unset('details'); sidebar.unset('compat'); sidebar.unset('display'); } }); /** * wp.media.view.Selection */ media.view.Selection = media.View.extend({ tagName: 'div', className: 'media-selection', template: media.template('media-selection'), events: { 'click .edit-selection': 'edit', 'click .clear-selection': 'clear' }, initialize: function() { _.defaults( this.options, { editable: false, clearable: true }); this.attachments = new media.view.Attachments.Selection({ controller: this.controller, collection: this.collection, selection: this.collection, model: new Backbone.Model({ edge: 40, gutter: 5 }) }); this.views.set( '.selection-view', this.attachments ); this.collection.on( 'add remove reset', this.refresh, this ); this.controller.on( 'content:activate', this.refresh, this ); }, ready: function() { this.refresh(); }, refresh: function() { // If the selection hasn't been rendered, bail. if ( ! this.$el.children().length ) return; var collection = this.collection, editing = 'edit-selection' === this.controller.content.mode(); // If nothing is selected, display nothing. this.$el.toggleClass( 'empty', ! collection.length ); this.$el.toggleClass( 'one', 1 === collection.length ); this.$el.toggleClass( 'editing', editing ); this.$('.count').text( l10n.selected.replace('%d', collection.length) ); }, edit: function( event ) { event.preventDefault(); if ( this.options.editable ) this.options.editable.call( this, this.collection ); }, clear: function( event ) { event.preventDefault(); this.collection.reset(); } }); /** * wp.media.view.Attachment.Selection */ media.view.Attachment.Selection = media.view.Attachment.extend({ className: 'attachment selection', // On click, just select the model, instead of removing the model from // the selection. toggleSelection: function() { this.options.selection.single( this.model ); } }); /** * wp.media.view.Attachments.Selection */ media.view.Attachments.Selection = media.view.Attachments.extend({ events: {}, initialize: function() { _.defaults( this.options, { sortable: true, resize: false, // The single `Attachment` view to be used in the `Attachments` view. AttachmentView: media.view.Attachment.Selection }); return media.view.Attachments.prototype.initialize.apply( this, arguments ); } }); /** * wp.media.view.Attachments.EditSelection */ media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({ buttons: { close: true } }); /** * wp.media.view.Settings */ media.view.Settings = media.View.extend({ events: { 'click button': 'updateHandler', 'change input': 'updateHandler', 'change select': 'updateHandler', 'change textarea': 'updateHandler' }, initialize: function() { this.model = this.model || new Backbone.Model(); this.model.on( 'change', this.updateChanges, this ); }, prepare: function() { return _.defaults({ model: this.model.toJSON() }, this.options ); }, render: function() { media.View.prototype.render.apply( this, arguments ); // Select the correct values. _( this.model.attributes ).chain().keys().each( this.update, this ); return this; }, update: function( key ) { var value = this.model.get( key ), $setting = this.$('[data-setting="' + key + '"]'), $buttons, $value; // Bail if we didn't find a matching setting. if ( ! $setting.length ) return; // Attempt to determine how the setting is rendered and update // the selected value. // Handle dropdowns. if ( $setting.is('select') ) { $value = $setting.find('[value="' + value + '"]'); if ( $value.length ) { $setting.find('option').prop( 'selected', false ); $value.prop( 'selected', true ); } else { // If we can't find the desired value, record what *is* selected. this.model.set( key, $setting.find(':selected').val() ); } // Handle button groups. } else if ( $setting.hasClass('button-group') ) { $buttons = $setting.find('button').removeClass('active'); $buttons.filter( '[value="' + value + '"]' ).addClass('active'); // Handle text inputs and textareas. } else if ( $setting.is('input[type="text"], textarea') ) { if ( ! $setting.is(':focus') ) $setting.val( value ); // Handle checkboxes. } else if ( $setting.is('input[type="checkbox"]') ) { $setting.attr( 'checked', !! value ); } }, updateHandler: function( event ) { var $setting = $( event.target ).closest('[data-setting]'), value = event.target.value, userSetting; event.preventDefault(); if ( ! $setting.length ) return; // Use the correct value for checkboxes. if ( $setting.is('input[type="checkbox"]') ) value = $setting[0].checked; // Update the corresponding setting. this.model.set( $setting.data('setting'), value ); // If the setting has a corresponding user setting, // update that as well. if ( userSetting = $setting.data('userSetting') ) setUserSetting( userSetting, value ); }, updateChanges: function( model, options ) { if ( model.hasChanged() ) _( model.changed ).chain().keys().each( this.update, this ); } }); /** * wp.media.view.Settings.AttachmentDisplay */ media.view.Settings.AttachmentDisplay = media.view.Settings.extend({ className: 'attachment-display-settings', template: media.template('attachment-display-settings'), initialize: function() { var attachment = this.options.attachment; _.defaults( this.options, { userSettings: false }); media.view.Settings.prototype.initialize.apply( this, arguments ); this.model.on( 'change:link', this.updateLinkTo, this ); if ( attachment ) attachment.on( 'change:uploading', this.render, this ); }, dispose: function() { var attachment = this.options.attachment; if ( attachment ) attachment.off( null, null, this ); media.view.Settings.prototype.dispose.apply( this, arguments ); }, render: function() { var attachment = this.options.attachment; if ( attachment ) { _.extend( this.options, { sizes: attachment.get('sizes'), type: attachment.get('type') }); } media.view.Settings.prototype.render.call( this ); this.updateLinkTo(); return this; }, updateLinkTo: function() { var linkTo = this.model.get('link'), $input = this.$('.link-to-custom'), attachment = this.options.attachment; if ( 'none' === linkTo || 'embed' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) { $input.hide(); return; } if ( attachment ) { if ( 'post' === linkTo ) { $input.val( attachment.get('link') ); } else if ( 'file' === linkTo ) { $input.val( attachment.get('url') ); } else if ( ! this.model.get('linkUrl') ) { $input.val('http://'); } $input.prop( 'readonly', 'custom' !== linkTo ); } $input.show(); // If the input is visible, focus and select its contents. if ( $input.is(':visible') ) $input.focus()[0].select(); } }); /** * wp.media.view.Settings.Gallery */ media.view.Settings.Gallery = media.view.Settings.extend({ className: 'gallery-settings', template: media.template('gallery-settings') }); /** * wp.media.view.Attachment.Details */ media.view.Attachment.Details = media.view.Attachment.extend({ tagName: 'div', className: 'attachment-details', template: media.template('attachment-details'), events: { 'change [data-setting]': 'updateSetting', 'change [data-setting] input': 'updateSetting', 'change [data-setting] select': 'updateSetting', 'change [data-setting] textarea': 'updateSetting', 'click .delete-attachment': 'deleteAttachment', 'click .edit-attachment': 'editAttachment', 'click .refresh-attachment': 'refreshAttachment' }, initialize: function() { this.focusManager = new media.view.FocusManager({ el: this.el }); media.view.Attachment.prototype.initialize.apply( this, arguments ); }, render: function() { media.view.Attachment.prototype.render.apply( this, arguments ); this.focusManager.focus(); return this; }, deleteAttachment: function( event ) { event.preventDefault(); if ( confirm( l10n.warnDelete ) ) this.model.destroy(); }, editAttachment: function( event ) { this.$el.addClass('needs-refresh'); }, refreshAttachment: function( event ) { this.$el.removeClass('needs-refresh'); event.preventDefault(); this.model.fetch(); } }); /** * wp.media.view.AttachmentCompat */ media.view.AttachmentCompat = media.View.extend({ tagName: 'form', className: 'compat-item', events: { 'submit': 'preventDefault', 'change input': 'save', 'change select': 'save', 'change textarea': 'save' }, initialize: function() { this.focusManager = new media.view.FocusManager({ el: this.el }); this.model.on( 'change:compat', this.render, this ); }, dispose: function() { if ( this.$(':focus').length ) this.save(); return media.View.prototype.dispose.apply( this, arguments ); }, render: function() { var compat = this.model.get('compat'); if ( ! compat || ! compat.item ) return; this.views.detach(); this.$el.html( compat.item ); this.views.render(); this.focusManager.focus(); return this; }, preventDefault: function( event ) { event.preventDefault(); }, save: function( event ) { var data = {}; if ( event ) event.preventDefault(); _.each( this.$el.serializeArray(), function( pair ) { data[ pair.name ] = pair.value; }); this.model.saveCompat( data ); } }); /** * wp.media.view.Iframe */ media.view.Iframe = media.View.extend({ className: 'media-iframe', render: function() { this.views.detach(); this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' ); this.views.render(); return this; } }); /** * wp.media.view.Embed */ media.view.Embed = media.View.extend({ className: 'media-embed', initialize: function() { this.url = new media.view.EmbedUrl({ controller: this.controller, model: this.model.props }).render(); this.views.set([ this.url ]); this.refresh(); this.model.on( 'change:type', this.refresh, this ); this.model.on( 'change:loading', this.loading, this ); }, settings: function( view ) { if ( this._settings ) this._settings.remove(); this._settings = view; this.views.add( view ); }, refresh: function() { var type = this.model.get('type'), constructor; if ( 'image' === type ) constructor = media.view.EmbedImage; else if ( 'link' === type ) constructor = media.view.EmbedLink; else return; this.settings( new constructor({ controller: this.controller, model: this.model.props, priority: 40 }) ); }, loading: function() { this.$el.toggleClass( 'embed-loading', this.model.get('loading') ); } }); /** * wp.media.view.EmbedUrl */ media.view.EmbedUrl = media.View.extend({ tagName: 'label', className: 'embed-url', events: { 'input': 'url', 'keyup': 'url', 'change': 'url' }, initialize: function() { this.$input = $('<input/>').attr( 'type', 'text' ).val( this.model.get('url') ); this.input = this.$input[0]; this.spinner = $('<span class="spinner" />')[0]; this.$el.append([ this.input, this.spinner ]); this.model.on( 'change:url', this.render, this ); }, render: function() { var $input = this.$input; if ( $input.is(':focus') ) return; this.input.value = this.model.get('url') || 'http://'; media.View.prototype.render.apply( this, arguments ); return this; }, ready: function() { this.focus(); }, url: function( event ) { this.model.set( 'url', event.target.value ); }, focus: function() { var $input = this.$input; // If the input is visible, focus and select its contents. if ( $input.is(':visible') ) $input.focus()[0].select(); } }); /** * wp.media.view.EmbedLink */ media.view.EmbedLink = media.view.Settings.extend({ className: 'embed-link-settings', template: media.template('embed-link-settings') }); /** * wp.media.view.EmbedImage */ media.view.EmbedImage = media.view.Settings.AttachmentDisplay.extend({ className: 'embed-image-settings', template: media.template('embed-image-settings'), initialize: function() { media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments ); this.model.on( 'change:url', this.updateImage, this ); }, updateImage: function() { this.$('img').attr( 'src', this.model.get('url') ); } }); }(jQuery));
JavaScript
window.wp = window.wp || {}; (function ($) { // Check for the utility settings. var settings = typeof _wpUtilSettings === 'undefined' ? {} : _wpUtilSettings; /** * wp.template( id ) * * Fetches a template by id. * * @param {string} id A string that corresponds to a DOM element with an id prefixed with "tmpl-". * For example, "attachment" maps to "tmpl-attachment". * @return {function} A function that lazily-compiles the template requested. */ wp.template = _.memoize(function ( id ) { var compiled, options = { evaluate: /<#([\s\S]+?)#>/g, interpolate: /\{\{\{([\s\S]+?)\}\}\}/g, escape: /\{\{([^\}]+?)\}\}(?!\})/g, variable: 'data' }; return function ( data ) { compiled = compiled || _.template( $( '#tmpl-' + id ).html(), null, options ); return compiled( data ); }; }); // wp.ajax // ------ // // Tools for sending ajax requests with JSON responses and built in error handling. // Mirrors and wraps jQuery's ajax APIs. wp.ajax = { settings: settings.ajax || {}, /** * wp.ajax.post( [action], [data] ) * * Sends a POST request to WordPress. * * @param {string} action The slug of the action to fire in WordPress. * @param {object} data The data to populate $_POST with. * @return {$.promise} A jQuery promise that represents the request. */ post: function( action, data ) { return wp.ajax.send({ data: _.isObject( action ) ? action : _.extend( data || {}, { action: action }) }); }, /** * wp.ajax.send( [action], [options] ) * * Sends a POST request to WordPress. * * @param {string} action The slug of the action to fire in WordPress. * @param {object} options The options passed to jQuery.ajax. * @return {$.promise} A jQuery promise that represents the request. */ send: function( action, options ) { if ( _.isObject( action ) ) { options = action; } else { options = options || {}; options.data = _.extend( options.data || {}, { action: action }); } options = _.defaults( options || {}, { type: 'POST', url: wp.ajax.settings.url, context: this }); return $.Deferred( function( deferred ) { // Transfer success/error callbacks. if ( options.success ) deferred.done( options.success ); if ( options.error ) deferred.fail( options.error ); delete options.success; delete options.error; // Use with PHP's wp_send_json_success() and wp_send_json_error() $.ajax( options ).done( function( response ) { // Treat a response of `1` as successful for backwards // compatibility with existing handlers. if ( response === '1' || response === 1 ) response = { success: true }; if ( _.isObject( response ) && ! _.isUndefined( response.success ) ) deferred[ response.success ? 'resolveWith' : 'rejectWith' ]( this, [response.data] ); else deferred.rejectWith( this, [response] ); }).fail( function() { deferred.rejectWith( this, arguments ); }); }).promise(); } }; }(jQuery));
JavaScript
jQuery(document).ready(function () { jQuery( '.switch-have-key' ).click( function() { var no_key = jQuery( this ).parents().find('div.no-key'); var have_key = jQuery( this ).parents().find('div.have-key'); no_key.addClass( 'hidden' ); have_key.removeClass( 'hidden' ); return false; }); jQuery( 'p.need-key a' ).click( function(){ document.akismet_activate.submit(); }); jQuery('.akismet-status').each(function () { var thisId = jQuery(this).attr('commentid'); jQuery(this).prependTo('#comment-' + thisId + ' .column-comment div:first-child'); }); jQuery('.akismet-user-comment-count').each(function () { var thisId = jQuery(this).attr('commentid'); jQuery(this).insertAfter('#comment-' + thisId + ' .author strong:first').show(); }); jQuery('#the-comment-list tr.comment .column-author a[title ^= "http://"]').each(function () { var thisTitle = jQuery(this).attr('title'); thisCommentId = jQuery(this).parents('tr:first').attr('id').split("-"); jQuery(this).attr("id", "author_comment_url_"+ thisCommentId[1]); if (thisTitle) { jQuery(this).after(' <a href="#" class="remove_url" commentid="'+ thisCommentId[1] +'" title="Remove this URL">x</a>'); } }); jQuery('.remove_url').live('click', function () { var thisId = jQuery(this).attr('commentid'); var data = { action: 'comment_author_deurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId }; jQuery.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Removes "x" link jQuery("a[commentid='"+ thisId +"']").hide(); // Show temp status jQuery("#author_comment_url_"+ thisId).html('<span>Removing...</span>'); }, success: function (response) { if (response) { // Show status/undo link jQuery("#author_comment_url_"+ thisId).attr('cid', thisId).addClass('akismet_undo_link_removal').html('<span>URL removed (</span>undo<span>)</span>'); } } }); return false; }); jQuery('.akismet_undo_link_removal').live('click', function () { var thisId = jQuery(this).attr('cid'); var thisUrl = jQuery(this).attr('href').replace("http://www.", "").replace("http://", ""); var data = { action: 'comment_author_reurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId, url: thisUrl }; jQuery.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Show temp status jQuery("#author_comment_url_"+ thisId).html('<span>Re-adding…</span>'); }, success: function (response) { if (response) { // Add "x" link jQuery("a[commentid='"+ thisId +"']").show(); // Show link jQuery("#author_comment_url_"+ thisId).removeClass('akismet_undo_link_removal').html(thisUrl); } } }); return false; }); jQuery('a[id^="author_comment_url"]').mouseover(function () { var wpcomProtocol = ( 'https:' === location.protocol ) ? 'https://' : 'http://'; // Need to determine size of author column var thisParentWidth = jQuery(this).parent().width(); // It changes based on if there is a gravatar present thisParentWidth = (jQuery(this).parent().find('.grav-hijack').length) ? thisParentWidth - 42 + 'px' : thisParentWidth + 'px'; if (jQuery(this).find('.mShot').length == 0 && !jQuery(this).hasClass('akismet_undo_link_removal')) { var thisId = jQuery(this).attr('id').replace('author_comment_url_', ''); jQuery('.widefat td').css('overflow', 'visible'); jQuery(this).css('position', 'relative'); var thisHref = jQuery.URLEncode(jQuery(this).attr('href')); jQuery(this).append('<div class="mShot mshot-container" style="left: '+thisParentWidth+'"><div class="mshot-arrow"></div><img src="'+wpcomProtocol+'s0.wordpress.com/mshots/v1/'+thisHref+'?w=450" width="450" class="mshot-image_'+thisId+'" style="margin: 0;" /></div>'); setTimeout(function () { jQuery('.mshot-image_'+thisId).attr('src', wpcomProtocol+'s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=2'); }, 6000); setTimeout(function () { jQuery('.mshot-image_'+thisId).attr('src', wpcomProtocol+'s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=3'); }, 12000); } else { jQuery(this).find('.mShot').css('left', thisParentWidth).show(); } }).mouseout(function () { jQuery(this).find('.mShot').hide(); }); }); // URL encode plugin jQuery.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/; while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;} }); // Preload mshot images after everything else has loaded jQuery(window).load(function() { var wpcomProtocol = ( 'https:' === location.protocol ) ? 'https://' : 'http://'; jQuery('a[id^="author_comment_url"]').each(function () { jQuery.get(wpcomProtocol+'s0.wordpress.com/mshots/v1/'+jQuery.URLEncode(jQuery(this).attr('href'))+'?w=450'); }); });
JavaScript
/** * navigation.js * * Handles toggling the navigation menu for small screens. */ ( function() { var nav = document.getElementById( 'site-navigation' ), button, menu; if ( ! nav ) return; button = nav.getElementsByTagName( 'h3' )[0]; menu = nav.getElementsByTagName( 'ul' )[0]; if ( ! button ) return; // Hide button if menu is missing or empty. if ( ! menu || ! menu.childNodes.length ) { button.style.display = 'none'; return; } button.onclick = function() { if ( -1 == menu.className.indexOf( 'nav-menu' ) ) menu.className = 'nav-menu'; if ( -1 != button.className.indexOf( 'toggled-on' ) ) { button.className = button.className.replace( ' toggled-on', '' ); menu.className = menu.className.replace( ' toggled-on', '' ); } else { button.className += ' toggled-on'; menu.className += ' toggled-on'; } }; } )();
JavaScript
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. * Things like site title, description, and background color changes. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' === to ) { $( '.site-title, .site-title a, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.site-title, .site-title a, .site-description' ).css( { 'clip': 'auto', 'color': to, 'position': 'relative' } ); } } ); } ); // Hook into background color/image change and adjust body class value as needed. wp.customize( 'background_color', function( value ) { value.bind( function( to ) { var body = $( 'body' ); if ( ( '#ffffff' == to || '#fff' == to ) && 'none' == body.css( 'background-image' ) ) body.addClass( 'custom-background-white' ); else if ( '' == to && 'none' == body.css( 'background-image' ) ) body.addClass( 'custom-background-empty' ); else body.removeClass( 'custom-background-empty custom-background-white' ); } ); } ); wp.customize( 'background_image', function( value ) { value.bind( function( to ) { var body = $( 'body' ); if ( '' != to ) body.removeClass( 'custom-background-empty custom-background-white' ); else if ( 'rgb(255, 255, 255)' == body.css( 'background-color' ) ) body.addClass( 'custom-background-white' ); else if ( 'rgb(230, 230, 230)' == body.css( 'background-color' ) && '' == _wpCustomizeSettings.values.background_color ) body.addClass( 'custom-background-empty' ); } ); } ); } )( jQuery );
JavaScript
/** * Functionality specific to Twenty Thirteen. * * Provides helper functions to enhance the theme experience. */ ( function( $ ) { var body = $( 'body' ), _window = $( window ); /** * Adds a top margin to the footer if the sidebar widget area is higher * than the rest of the page, to help the footer always visually clear * the sidebar. */ $( function() { if ( body.is( '.sidebar' ) ) { var sidebar = $( '#secondary .widget-area' ), secondary = ( 0 == sidebar.length ) ? -40 : sidebar.height(), margin = $( '#tertiary .widget-area' ).height() - $( '#content' ).height() - secondary; if ( margin > 0 && _window.innerWidth() > 999 ) $( '#colophon' ).css( 'margin-top', margin + 'px' ); } } ); /** * Enables menu toggle for small screens. */ ( function() { var nav = $( '#site-navigation' ), button, menu; if ( ! nav ) return; button = nav.find( '.menu-toggle' ); if ( ! button ) return; // Hide button if menu is missing or empty. menu = nav.find( '.nav-menu' ); if ( ! menu || ! menu.children().length ) { button.hide(); return; } $( '.menu-toggle' ).on( 'click.twentythirteen', function() { nav.toggleClass( 'toggled-on' ); } ); } )(); /** * Makes "skip to content" link work correctly in IE9 and Chrome for better * accessibility. * * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/ */ _window.on( 'hashchange.twentythirteen', function() { var element = document.getElementById( location.hash.substring( 1 ) ); if ( element ) { if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) element.tabIndex = -1; element.focus(); } } ); /** * Arranges footer widgets vertically. */ if ( $.isFunction( $.fn.masonry ) ) { var columnWidth = body.is( '.sidebar' ) ? 228 : 245; $( '#secondary .widget-area' ).masonry( { itemSelector: '.widget', columnWidth: columnWidth, gutterWidth: 20, isRTL: body.is( '.rtl' ) } ); } } )( jQuery );
JavaScript
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. * Things like site title and description changes. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color. wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' == to ) { if ( 'remove-header' == _wpCustomizeSettings.values.header_image ) $( '.home-link' ).css( 'min-height', '0' ); $( '.site-title, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.home-link' ).css( 'min-height', '230px' ); $( '.site-title, .site-description' ).css( { 'clip': 'auto', 'color': to, 'position': 'relative' } ); } } ); } ); } )( jQuery );
JavaScript
var ws; var t; function init() { document.getElementById('updateme').innerHTML = "connecting to websocket"; OpenWebSocket(); } function OpenWebSocket() { if ("WebSocket" in window) { ws = new WebSocket("%%WEBSOCKET_URL%%"); ws.onopen = function() { // Web Socket is connected document.getElementById('updateme').innerHTML = "websocket is open"; t=setTimeout("SendMessage()",1000); }; ws.onmessage = function(evt) { document.getElementById('updateme').innerHTML = evt.data; }; ws.onclose = function() { document.getElementById('updateme').innerHTML = "websocket is closed"; OpenWebSocket(); }; ws.onerror = function(evt) { alert("onerror: " + evt); }; } else { alert("Browser doesn't support WebSocket!"); } } function SendMessage() { if ("WebSocket" in window) { ws.send("time"); t=setTimeout("SendMessage()",1000); } else { alert("Browser doesn't support WebSocket!"); } }
JavaScript
function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket supported here! :)\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } else { // Browser doesn't support WebSocket alert("WebSocket NOT supported here! :(\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } }
JavaScript
function WebSocketTest2() { if ("WebSocket" in window) { var ws = new WebSocket("%%WEBSOCKET_URL%%"); ws.onopen = function() { // Web Socket is connected alert("websocket is open"); // You can send data now ws.send("Hey man, you got the time?"); }; ws.onmessage = function(evt) { alert("received: " + evt.data); }; ws.onclose = function() { alert("websocket is closed"); }; } else { alert("Browser doesn't support WebSocket!"); } }
JavaScript
function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket supported here! :)\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } else { // Browser doesn't support WebSocket alert("WebSocket NOT supported here! :(\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } }
JavaScript
/* */ function getHTML(p_url){ debug("Get code from "+p_url); try{ var xml_envelope="<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:q0='http://analizer.thirtywords.com' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"; xml_envelope+="<soapenv:Body>"; xml_envelope+="<q0:analize>"; xml_envelope+="<q0:url>"+p_url+"</q0:url>"; xml_envelope+="</q0:analize>"; xml_envelope+="</soapenv:Body>"; xml_envelope+="</soapenv:Envelope>"; $.ajax({ type: "POST", timeout:60000, url: "http://localhost:8080/30words/services/Analyzer", contentType:"text/xml; charset='utf-8'", data:xml_envelope, dataType:'xml', beforeSend: function( xhr ){ xhr.setRequestHeader( "SOAPAction", "analise" ); }, success: function(response, result, xhr) { var page = new Object(); page.url = p_url; var xml = $( response ); page.html=xml.find("analizeReturn").text(); debug("Web Service "+result); analize_results(page); }, error: function(response, status, xhr) { debug("Web Service " +status+ " " + data.responseText); } }); }catch(e){ debug(e.description); } } function error(p_message){ logger("Error",p_message,false); } function debug(p_message){ logger("Debug",p_message,false); } function logger(p_level, p_message, p_verbose){ if(p_verbose) alert("Verbose: "+p_message); var console = $("#console"); console.html(""); debugs[debugs.length]=p_level+": "+p_message; var i=0; var j=debugs.length-1; while(i<max_debugs && i<debugs.length){ console.append(debugs[j]+"<br>"); i++; j--; } } function showWait(){ $("#wait").show(); } function hideWait(){ $("#wait").hide(); }
JavaScript
function start(){ trendLoader(); prepareServices(1); sourceLoader(); } function sourceLoader(){ try{ var source=new Object(); source.name="Globo.com"; source.url="http://www.globo.com"; source.url="http://www.globo.com"; source.language="pt"; sources[sources.length]=source; /* source=new Object(); source.name="Folha"; source.url="http://www.folha.com.br"; source.language="pt"; sources[sources.length]=source; source=new Object(); source.name="Zero Hora"; source.url="http://www.zerohora.com.br"; source.language="pt"; sources[sources.length]=source; source=new Object(); source.name="Estadao"; source.url="http://www.estadao.com.br"; source.language="pt"; sources[sources.length]=source; */ }catch(e){ error("sourceLoader"+e.description); } } function trendLoader(){ try{ //from consumer getTrends(1); var html=""; for(var i=0;i<trends.length;i++){ var trend=trends[i]; html+="<p class='trend' onclick=addFilterSocial('"+trend.name+"')>"+unescape(trend.name)+"</p>"; } var social = $("#socialwords"); social.html(html); }catch(e){ error("trendLoader"+e.description); } } //THIS IS A FUCKING MOCK function prepareServices(local){ try{ try{ services=new Array(); //alert(1); var service = new Object(); service.name="Facebook"; service.url="http://www.facebook.com"; service.description="The largest social network"; services[services.length]=service; //alert(2); service = new Object(); service.name=escape("Hostel World"); service.url= "http://www.hostelworld.com/"; service.description="The most used hostel"; services[services.length]=service; service = new Object(); service.name=escape("Ebay"); service.url= "http://www.ebay.com/"; service.description="Sell or buy anything"; services[services.length]=service; service = new Object(); service.name=escape("Amazon"); service.url= "http://www.amazon.com/"; service.description="Buy books"; services[services.length]=service; }catch(e){ error("searchServices"+e.description); } }catch(e){ error("prepareServices"+e.description); } }
JavaScript
/* 2 - Searching page_results that can match the word filters */ function searchpage_results(){ try{ debug("Searching pages"); for(var i=0;i<sources.length;i++){ debug("Checking source "+sources[i].name); getHTML(sources[i].url); page_results=new Array(); } pageResults(); }catch(e){ error("filterpage_results"+e.description); } } function analize_results(p_page){ var result=analizeContent(p_page); if(result){ var page_result=new Object(); page_result.url=p_page.url; page_result.sumary=result; page_results[page_results.length]=page_result; } pageResults(); } /* 4 - Renderize the page_results results */ function pageResults(){ try{ var page_resultsresult = $("#pagesresult"); page_resultsresult.html(""); debug("Loading page results"); var html=""; for(var i=0;i<page_results.length;i++){ html+="<div>"; html+="<p class='result'>"; html+=page_results[i].sumary; html+="</p>"; html+="<div class='links'>"; html+=page_results[i].url + "<br>"; for(var j=0;j<3&&j<services.length;j++){ var service=services[j]; html+="<b class='service' onclick=addFilterService('"+service.name+"')> "+unescape(service.name)+" </b> |"; } html+="</div>"; html+="</div>"; html+="<br>"; } page_resultsresult.html(html); }catch(e){ error(e.description); } } /* 7 - Searching for the available services */ function searchServices(){ try{ debug("Searching services"); filterServices(); debug("Loading services results"); var serviceresult = $("#serviceresults"); serviceresult.html("No results found for this service(s)..."); var html=""; for(var i=0;i<10&&i<services_results.length;i++){ html+="<div>"; html+="<p class='result'>"; html+=services_results[i].sumary; html+="</p>"; html+="</div>"; html+="<br>"; } serviceresult.html(html); }catch(e){ error(e.description); } } //THIS IS A FUCKING MOCK /* 8 - Filtering for the found services that fits on the filter */ function filterServices(){ try{ debug("Filtering services"); var service = new Object(); service.url = "www.globo.com"; service.sumary = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat."; service.icon = "globo.com"; for(var i=0;i<9;i++){ services_results[i]=service; } debug(services_results.length+" services found"); }catch(e){ error(e.description); } }
JavaScript
/* 1 - Entry of the page interaction after loding the words, the user must to add words for the filter */ function addFilterSocial(word){ try{ debug("Adding a new filter"); page_results_filters[word]=word; var html=""; for(word in page_results_filters){ html+="<div class='filter' onclick=removeFilterSocial('"+word+"')>"; html+=unescape(word)+""; html+="</div>"; } var page_resultsfilter = $("#mediafilter"); page_resultsfilter.html(html); showWait(); searchpage_results(); hideWait(); }catch(e){ error("addFilterSocial"+e.description); } } /* 5 - Adding a new service to filter the results */ function addFilterService(service){ try{ debug("Adding a new service filter"); services_filters[service]=service; var html=""; for(service in services_filters){ html+="<div class='filter' onclick=removeFilterService('"+service+"')>"; html+=unescape(service)+""; html+="</div>"; } var servicefilter = $("#servicefilter"); servicefilter.html(html); showWait(); searchServices(); //hideWait(); }catch(e){ error("addFilterService"+e.description); } } /* 2.5. - Filter the page_results with words */ function analizeContent(p_page){ try{ var positions=new Array(); var position=0; //if one of the words is present, the pages is added for(word in page_results_filters){ debug("Analize content "+unescape(word)+" for "+p_page.url); debug("Searching "+unescape(word)); position=p_page.html.toUpperCase().search(unescape(word.toUpperCase())); if(position==-1){ debug(unescape(word)+" not exists"); return false; }else{ debug(word+" is at "+position); positions[positions.length]=position; } } var result=getLink(p_page.html,position); return result; }catch(e){ error("analizeContent"+e.description); } }
JavaScript
//configuration arrays var trends=new Array(); var debugs = new Array(); var sources=new Array(); var pages=new Array(); var page_results=new Array(); var page_results_filters=new Array(); var services=new Array(); var services_results=new Array(); var services_filters=new Array(); //numeric values var max_debugs=10; var max_errors=10;
JavaScript
//THIS IS A FUCKING MOCK //var twitter-trends="https://api.twitter.com/1.1/trends/place.json?id=";// function getTrends(place){ //var trends = getTrends(1); var trend=new Object(); trend.name="Papa"; trends[trends.length]=trend; trend=new Object(); trend.name="Fidel"; trends[trends.length]=trend; trend=new Object(); trend.name=escape("Fernando Henrique"); trends[trends.length]=trend; trend=new Object(); trend.name="Lula"; trends[trends.length]=trend; trend=new Object(); trend.name="Lorem"; trends[trends.length]=trend; trend=new Object(); trend.name="LOREM"; trends[trends.length]=trend; trend=new Object(); trend.name="congresso"; trends[trends.length]=trend; trend=new Object(); trend.name="protesto"; trends[trends.length]=trend; trend=new Object(); trend.name="Paulo"; trends[trends.length]=trend; trend=new Object(); trend.name="Bambam"; trends[trends.length]=trend; trend=new Object(); trend.name="Investiga"; trends[trends.length]=trend; /* alert(1); $.ajax({ type: "GET", url : twitter-trends+place, dataType: "json", data: { oauth_token : "myTokenHere", }, error: function(){ alert('you loooose, sucka'); }, success: function(){ alert('in like Flynn'); } }) */ }
JavaScript
$(document).ready(function () { counter = 0; $('.folder').click(function (event, getAlbum) { $('.folder').css("text-decoration", "none"); if (getAlbum != undefined) { if ($('#album_' + getAlbum).length == 0) { $('#info').html('<li><h1 style="font-weight: bold; font-size: 25px; padding: 10px;">No such album</h1><li>'); return false; } $('#album_' + getAlbum).css("text-decoration", "underline"); var href = $('#album_' + getAlbum).attr('href'); album_id = href.substring(1); } else { $(this).css("text-decoration", "underline"); var href = $(this).attr('href'); album_id = href.substring(1); } $.ajax({ url:'get_pics.php', type:"POST", data:{ album_id:album_id }, success:function (res) { $('#info').html(res); } }); return false; }); $('.folder').first().trigger('click', [getAlbum]); $('#left').click(function () { counter++; if (counter % 20 == 0) { var small = $('#banner_s').html(); var large = $('#banner_l').html(); $('#banner_s').html(large); $('#banner_l').html(small); } var first = $('#info > li:first'); var last = $('#info > li:last'); var active = $('#info > li:visible'); var prev = active.prev(); if (first[0] == active[0]) { active.hide(); last.show(); } else { active.hide(); prev.show(); } return false; }); $('#right').click(function () { counter++; if (counter % 20 == 0) { var small = $('#banner_s').html(); var large = $('#banner_l').html(); $('#banner_s').html(large); $('#banner_l').html(small); } var first = $('#info > li:first'); var last = $('#info > li:last'); var active = $('#info > li:visible'); var next = active.next(); if (last[0] == active[0]) { active.hide(); first.show(); } else { active.hide(); next.show(); } return false; }); });
JavaScript
function ajaxChangeImage(params, callback) { if(params.button == undefined) { var btn = document.getElementById(params.file); var eventType = 'change'; } else { var btn = document.getElementById(params.button); var eventType = 'click'; } var input = document.getElementById(params.file); formdata = false; if (window.FormData) { formdata = new FormData(); } btn.addEventListener(eventType, function (evt) { var reader, file; file = input.files[0]; if (!!file.type.match(/image.*/)) { if ( window.FileReader ) { reader = new FileReader(); reader.readAsDataURL(file); } if (formdata) { formdata.append("image", file); } } if(params.picId != undefined) { formdata.append('picId', params.picId); } if(params.title != undefined) { formdata.append('title', params.title); } if(params.albumId != undefined) { formdata.append('albumId', params.albumId); } if (formdata) { $.ajax({ url: params.url, type: "POST", data: formdata, processData: false, contentType: false, success: function (res) { // $('#info').html(res) } }).done(function() { callback(params.image); }); } }, false); }
JavaScript
function ajaxUpload(params, callback) { console.log(params); // return false; var input = document.getElementById(params.file); formdata = false; if (window.FormData) { formdata = new FormData(); } var reader, file; file = input.files[0]; if (!!file.type.match(/image.*/)) { if ( window.FileReader ) { reader = new FileReader(); reader.readAsDataURL(file); } if (formdata) { formdata.append("image", file); } } formdata.append('title', params.title); formdata.append('albumId', params.albumId); if (formdata) { $.ajax({ url: params.url, type: "POST", data: formdata, processData: false, contentType: false, success: function (res) { // $('#info').append(res) } }).done(function() { callback($(this)); // console.log('test'); }); } }
JavaScript
$("input:file").each(function() { params = { file : $(this).attr('id'), button : 'btn', picId : 69 }; ajaxUpload(params); });
JavaScript
$(document).ready(function () { // var test = JSON.parse(<?php echo $counter; ?>); // var counter = "<?php echo $counter; ?>"; // if (counter % 20 == 0) { // var small = $('#banner_s').html(); // var large = $('#banner_l').html(); // $('#banner_s').html(large); // $('#banner_l').html(small); // } /* $('.folder').click(function (event, getAlbum) { $('.folder').css("text-decoration", "none"); if (getAlbum != undefined) { if ($('#album_' + getAlbum).length == 0) { $('#info').html('<li><h1 style="font-weight: bold; font-size: 25px; padding: 10px;">No such album</h1><li>'); return false; } $('#album_' + getAlbum).css("text-decoration", "underline"); var href = $('#album_' + getAlbum).attr('href'); album_id = href.substring(1); } else { $(this).css("text-decoration", "underline"); var href = $(this).attr('href'); album_id = href.substring(1); } $.ajax({ url:'get_pics.php', type:"POST", data:{ album_id:album_id }, success:function (res) { $('#info').html(res); } }); return false; }); */ /* $('.folder').first().trigger('click', [getAlbum]); */ /* $('#left').click(function () { counter++; if (counter % 20 == 0) { var small = $('#banner_s').html(); var large = $('#banner_l').html(); $('#banner_s').html(large); $('#banner_l').html(small); } var first = $('#info > li:first'); var last = $('#info > li:last'); var active = $('#info > li:visible'); var prev = active.prev(); if (first[0] == active[0]) { active.hide(); last.show(); } else { active.hide(); prev.show(); } return false; }); $('#right').click(function () { counter++; if (counter % 20 == 0) { var small = $('#banner_s').html(); var large = $('#banner_l').html(); $('#banner_s').html(large); $('#banner_l').html(small); } var first = $('#info > li:first'); var last = $('#info > li:last'); var active = $('#info > li:visible'); var next = active.next(); if (last[0] == active[0]) { active.hide(); first.show(); } else { active.hide(); next.show(); } return false; }); */ });
JavaScript
function ajaxChangeImage(params, callback) { if(params.button == undefined) { var btn = document.getElementById(params.file); var eventType = 'change'; } else { var btn = document.getElementById(params.button); var eventType = 'click'; } var input = document.getElementById(params.file); formdata = false; if (window.FormData) { formdata = new FormData(); } btn.addEventListener(eventType, function (evt) { var reader, file; file = input.files[0]; if (!!file.type.match(/image.*/)) { if ( window.FileReader ) { reader = new FileReader(); reader.readAsDataURL(file); } if (formdata) { formdata.append("image", file); } } if(params.picId != undefined) { formdata.append('picId', params.picId); } if(params.title != undefined) { formdata.append('title', params.title); } if(params.albumId != undefined) { formdata.append('albumId', params.albumId); } if (formdata) { $.ajax({ url: params.url, type: "POST", data: formdata, processData: false, contentType: false, success: function (res) { // $('#info').html(res) } }).done(function() { callback(params.image); }); } }, false); }
JavaScript
function ajaxUpload(params, callback) { console.log(params); // return false; var input = document.getElementById(params.file); formdata = false; if (window.FormData) { formdata = new FormData(); } var reader, file; file = input.files[0]; if (!!file.type.match(/image.*/)) { if ( window.FileReader ) { reader = new FileReader(); reader.readAsDataURL(file); } if (formdata) { formdata.append("image", file); } } formdata.append('title', params.title); formdata.append('albumId', params.albumId); if (formdata) { $.ajax({ url: params.url, type: "POST", data: formdata, processData: false, contentType: false, success: function (res) { // $('#info').append(res) } }).done(function() { callback($(this)); // console.log('test'); }); } }
JavaScript
$("input:file").each(function() { params = { file : $(this).attr('id'), button : 'btn', picId : 69 }; ajaxUpload(params); });
JavaScript
/*! * jQuery Cookie Plugin v1.3.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2013 Klaus Hartl * Released under the MIT license */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as anonymous module. define(['jquery'], factory); } else { // Browser globals. factory(jQuery); } }(function ($) { var pluses = /\+/g; function raw(s) { return s; } function decoded(s) { return decodeURIComponent(s.replace(pluses, ' ')); } function converted(s) { if (s.indexOf('"') === 0) { // This is a quoted cookie as according to RFC2068, unescape s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } try { return config.json ? JSON.parse(s) : s; } catch(er) {} } var config = $.cookie = function (key, value, options) { // write if (value !== undefined) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = config.json ? JSON.stringify(value) : String(value); return (document.cookie = [ config.raw ? key : encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // read var decode = config.raw ? raw : decoded; var cookies = document.cookie.split('; '); var result = key ? undefined : {}; for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); var name = decode(parts.shift()); var cookie = decode(parts.join('=')); if (key && key === name) { result = converted(cookie); break; } if (!key) { result[name] = converted(cookie); } } return result; }; config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) !== undefined) { // Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return true; } return false; }; }));
JavaScript
// Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generic helpers /** * Create a new XMLHttpRequest in a cross-browser-compatible way. * @return XMLHttpRequest object */ function M_getXMLHttpRequest() { try { return new XMLHttpRequest(); } catch (e) { } try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { } try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } return null; } /** * Finds the element's parent in the DOM tree. * @param {Element} element The element whose parent we want to find * @return The parent element of the given element */ function M_getParent(element) { if (element.parentNode) { return element.parentNode; } else if (element.parentElement) { // IE compatibility. Why follow standards when you can make up your own? return element.parentElement; } return null; } /** * Finds the event's target in a way that works on all browsers. * @param {Event} e The event object whose target we want to find * @return The element receiving the event */ function M_getEventTarget(e) { var src = e.srcElement ? e.srcElement : e.target; return src; } /** * Function to determine if we are in a KHTML-based browser(Konq/Safari). * @return Boolean of whether we are in a KHTML browser */ function M_isKHTML() { var agt = navigator.userAgent.toLowerCase(); return (agt.indexOf("safari") != -1) || (agt.indexOf("khtml") != -1); } /** * Function to determine if we are running in an IE browser. * @return Boolean of whether we are running in IE */ function M_isIE() { return (navigator.userAgent.toLowerCase().indexOf("msie") != -1) && !window.opera; } /** * Function to determine if we are in a WebKit-based browser (Chrome/Safari). * @return Boolean of whether we are in a WebKit browser */ function M_isWebKit() { return navigator.userAgent.toLowerCase().indexOf("webkit") != -1; } /** * Stop the event bubbling in a browser-independent way. Sometimes required * when it is not easy to return true when an event is handled. * @param {Window} win The window in which this event is happening * @param {Event} e The event that we want to cancel */ function M_stopBubble(win, e) { if (!e) { e = win.event; } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } } /** * Return distance in pixels from the top of the document to the given element. * @param {Element} element The element whose offset we want to find * @return Integer value of the height of the element from the top */ function M_getPageOffsetTop(element) { var y = element.offsetTop; if (element.offsetParent != null) { y += M_getPageOffsetTop(element.offsetParent); } return y; } /** * Return distance in pixels of the given element from the left of the document. * @param {Element} element The element whose offset we want to find * @return Integer value of the horizontal position of the element */ function M_getPageOffsetLeft(element) { var x = element.offsetLeft; if (element.offsetParent != null) { x += M_getPageOffsetLeft(element.offsetParent); } return x; } /** * Find the height of the window viewport. * @param {Window} win The window whose viewport we would like to measure * @return Integer value of the height of the given window */ function M_getWindowHeight(win) { return M_getWindowPropertyByBrowser_(win, M_getWindowHeightGetters_); } /** * Find the vertical scroll position of the given window. * @param {Window} win The window whose scroll position we want to find * @return Integer value of the scroll position of the given window */ function M_getScrollTop(win) { return M_getWindowPropertyByBrowser_(win, M_getScrollTopGetters_); } /** * Scroll the target element into view at 1/3rd of the window height only if * the scrolling direction matches the direction that was asked for. * @param {Window} win The window in which the element resides * @param {Element} element The element that we want to bring into view * @param {Integer} direction Positive for scroll down, negative for scroll up */ function M_scrollIntoView(win, element, direction) { var elTop = M_getPageOffsetTop(element); var winHeight = M_getWindowHeight(win); var targetScroll = elTop - winHeight / 3; var scrollTop = M_getScrollTop(win); if ((direction > 0 && scrollTop < targetScroll) || (direction < 0 && scrollTop > targetScroll)) { win.scrollTo(M_getPageOffsetLeft(element), targetScroll); } } /** * Returns whether the element is visible. * @param {Window} win The window that the element resides in * @param {Element} element The element whose visibility we want to determine * @return Boolean of whether the element is visible in the window or not */ function M_isElementVisible(win, element) { var elTop = M_getPageOffsetTop(element); var winHeight = M_getWindowHeight(win); var winTop = M_getScrollTop(win); if (elTop < winTop || elTop > winTop + winHeight) { return false; } return true; } // Cross-browser compatibility quirks and methodology borrowed from // common.js var M_getWindowHeightGetters_ = { ieQuirks_: function(win) { return win.document.body.clientHeight; }, ieStandards_: function(win) { return win.document.documentElement.clientHeight; }, dom_: function(win) { return win.innerHeight; } }; var M_getScrollTopGetters_ = { ieQuirks_: function(win) { return win.document.body.scrollTop; }, ieStandards_: function(win) { return win.document.documentElement.scrollTop; }, dom_: function(win) { return win.pageYOffset; } }; /** * Slightly modified from common.js: Konqueror has the CSS1Compat property * but requires the standard DOM functionlity, not the IE one. */ function M_getWindowPropertyByBrowser_(win, getters) { try { if (!M_isKHTML() && "compatMode" in win.document && win.document.compatMode == "CSS1Compat") { return getters.ieStandards_(win); } else if (M_isIE()) { return getters.ieQuirks_(win); } } catch (e) { // Ignore for now and fall back to DOM method } return getters.dom_(win); } // Global search box magic (global.html) /** * Handle the onblur action of the search box, replacing it with greyed out * instruction text when it is empty. * @param {Element} element The search box element */ function M_onSearchBlur(element) { var defaultMsg = "Enter a changelist#, user, or group"; if (element.value.length == 0 || element.value == defaultMsg) { element.style.color = "gray"; element.value = defaultMsg; } else { element.style.color = ""; } } /** * Handle the onfocus action of the search box, emptying it out if no new text * was entered. * @param {Element} element The search box element */ function M_onSearchFocus(element) { if (element.style.color == "gray") { element.style.color = ""; element.value = ""; } } // Inline diffs (changelist.html) /** * Creates an iframe to load the diff in the background and when that's done, * calls a function to transfer the contents of the iframe into the current DOM. * @param {Integer} suffix The number associated with that diff * @param {String} url The URL that the diff should be fetched from * @return false (for event bubbling purposes) */ function M_showInlineDiff(suffix, url) { var hide = document.getElementById("hide-" + suffix); var show = document.getElementById("show-" + suffix); var frameDiv = document.getElementById("frameDiv-" + suffix); var dumpDiv = document.getElementById("dumpDiv-" + suffix); var diffTR = document.getElementById("diffTR-" + suffix); var hideAll = document.getElementById("hide-alldiffs"); var showAll = document.getElementById("show-alldiffs"); /* Twiddle the "show/hide all diffs" link */ if (hide.style.display != "") { M_CL_hiddenInlineDiffCount -= 1; if (M_CL_hiddenInlineDiffCount == M_CL_maxHiddenInlineDiffCount) { showAll.style.display = "inline"; hideAll.style.display = "none"; } else { showAll.style.display = "none"; hideAll.style.display = "inline"; } } hide.style.display = ""; show.style.display = "none"; dumpDiv.style.display = "block"; // XXX why not ""? diffTR.style.display = ""; if (!frameDiv.innerHTML) { if (M_isKHTML()) { frameDiv.style.display = "block"; // XXX why not ""? } frameDiv.innerHTML = "<iframe src='" + url + "'" + " onload='M_dumpInlineDiffContent(this, \"" + suffix + "\")'"+ "height=1>your browser does not support iframes!</iframe>"; } return false; } /** * Hides the diff that was retrieved with M_showInlineDiff. * @param {Integer} suffix The number associated with the diff we want to hide */ function M_hideInlineDiff(suffix) { var hide = document.getElementById("hide-" + suffix); var show = document.getElementById("show-" + suffix); var dumpDiv = document.getElementById("dumpDiv-" + suffix); var diffTR = document.getElementById("diffTR-" + suffix); var hideAll = document.getElementById("hide-alldiffs"); var showAll = document.getElementById("show-alldiffs"); /* Twiddle the "show/hide all diffs" link */ if (hide.style.display != "none") { M_CL_hiddenInlineDiffCount += 1; if (M_CL_hiddenInlineDiffCount == M_CL_maxHiddenInlineDiffCount) { showAll.style.display = "inline"; hideAll.style.display = "none"; } else { showAll.style.display = "none"; hideAll.style.display = "inline"; } } hide.style.display = "none"; show.style.display = "inline"; diffTR.style.display = "none"; dumpDiv.style.display = "none"; return false; } /** * Dumps the content of the given iframe into the appropriate div in order * for the diff to be displayed. * @param {Element} iframe The IFRAME that contains the diff data * @param {Integer} suffix The number associated with the diff */ function M_dumpInlineDiffContent(iframe, suffix) { var dumpDiv = document.getElementById("dumpDiv-" + suffix); dumpDiv.style.display = "block"; // XXX why not ""? dumpDiv.innerHTML = iframe.contentWindow.document.body.innerHTML; // TODO: The following should work on all browsers instead of the // innerHTML hack above. At this point I don't remember what the exact // problem was, but it didn't work for some reason. // dumpDiv.appendChild(iframe.contentWindow.document.body); if (M_isKHTML()) { var frameDiv = document.getElementById("frameDiv-" + suffix); frameDiv.style.display = "none"; } } /** * Goes through all the diffs and triggers the onclick action on them which * should start the mechanism for displaying them. * @param {Integer} num The number of diffs to display (0-indexed) */ function M_showAllDiffs(num) { for (var i = 0; i < num; i++) { var link = document.getElementById('show-' + i); // Since the user may not have JS, the template only shows the diff inline // for the onclick action, not the href. In order to activate it, we must // call the link's onclick action. if (link.className.indexOf("reverted") == -1) { link.onclick(); } } } /** * Goes through all the diffs and hides them by triggering the hide link. * @param {Integer} num The number of diffs to hide (0-indexed) */ function M_hideAllDiffs(num) { for (var i = 0; i < num; i++) { var link = document.getElementById('hide-' + i); // If the user tries to hide, that means they have JS, which in turn means // that we can just set href in the href of the hide link. link.onclick(); } } // Inline comment submission forms (changelist.html, file.html) /** * Changes the elements display style to "" which renders it visible. * @param {String|Element} elt The id of the element or the element itself */ function M_showElement(elt) { if (typeof elt == "string") { elt = document.getElementById(elt); } if (elt) elt.style.display = ""; } /** * Changes the elements display style to "none" which renders it invisible. * @param {String|Element} elt The id of the element or the element itself */ function M_hideElement(elt) { if (typeof elt == "string") { elt = document.getElementById(elt); } if (elt) elt.style.display = "none"; } /** * Toggle the visibility of a section. The little indicator triangle will also * be toggled. * @param {String} id The id of the target element */ function M_toggleSection(id) { var sectionStyle = document.getElementById(id).style; var pointerStyle = document.getElementById(id + "-pointer").style; if (sectionStyle.display == "none") { sectionStyle.display = ""; pointerStyle.backgroundImage = "url('" + media_url + "opentriangle.gif')"; } else { sectionStyle.display = "none"; pointerStyle.backgroundImage = "url('" + media_url + "closedtriangle.gif')"; } } /** * Callback for XMLHttpRequest. */ function M_PatchSetFetched() { if (http_request.readyState != 4) return; var section = document.getElementById(http_request.div_id); if (http_request.status == 200) { section.innerHTML = http_request.responseText; /* initialize dashboardState again to update cached patch rows */ if (dashboardState) dashboardState.initialize(); } else { section.innerHTML = '<div style="color:red">Could not load the patchset (' + http_request.status + ').</div>'; } } /** * Toggle the visibility of a patchset, and fetches it if necessary. * @param {String} issue The issue key * @param {String} id The patchset key */ function M_toggleSectionForPS(issue, patchset) { var id = 'ps-' + patchset; M_toggleSection(id); var section = document.getElementById(id); if (section.innerHTML.search("<div") != -1) return; section.innerHTML = "<div>Loading...</div>" http_request = M_getXMLHttpRequest(); if (!http_request) return; http_request.open('GET', base_url + issue + "/patchset/" + patchset, true); http_request.onreadystatechange = M_PatchSetFetched; http_request.div_id = id; http_request.send(null); } /** * Toggle the visibility of the "Quick LGTM" link on the changelist page. * @param {String} id The id of the target element */ function M_toggleQuickLGTM(id) { M_toggleSection(id); window.scrollTo(0, document.body.offsetHeight); } // Comment expand/collapse /** * Toggles whether the specified changelist comment is expanded/collapsed. * @param {Integer} cid The comment id, 0-indexed */ function M_switchChangelistComment(cid) { M_switchCommentCommon_('cl', String(cid)); } /** * Toggles a comment if the anchor is of the form '#msgNUMBER'. */ function M_toggleIssueMessageByAnchor() { var href = window.location.href; var idx_hash = href.lastIndexOf('#'); if (idx_hash != -1) { var anchor = href.slice(idx_hash+1, href.length); if (anchor.slice(0, 3) == 'msg') { var elem = document.getElementById(anchor); elem.className += ' referenced'; var num = elem.getAttribute('name'); M_switchChangelistComment(num); } } } /** * Toggles whether the specified file comment is expanded/collapsed. * @param {Integer} cid The comment id, 0-indexed */ function M_switchFileComment(cid) { M_switchCommentCommon_('file', String(cid)); } /** * Toggles whether the specified inline comment is expanded/collapsed. * @param {Integer} cid The comment id, 0-indexed * @param {Integer} lineno The lineno associated with the comment * @param {String} side The side (a/b) associated with the comment */ function M_switchInlineComment(cid, lineno, side) { M_switchCommentCommon_('inline', String(cid) + "-" + lineno + "-" + side); } /** * Toggles whether the specified comment is expanded/collapsed on * comment_form.html. * @param {Integer} cid The comment id, 0-indexed */ function M_switchReviewComment(cid) { M_switchCommentCommon_('cl', String(cid)); } /** * Toggle whether a moved_out region is expanded/collapsed. * @param {Integer} start_line the line number of the first line to toggle * @param {Integer} end_line the line number of the first line not to toggle * We toggle all lines in [first_line, end_line). */ function M_switchMoveOut(start_line, end_line) { for (var x = start_line; x < end_line; x++) { var regionname = "move_out-" + x; var region = document.getElementById(regionname); if (region.style.display == "none") { region.style.display = ""; } else { region.style.display = "none"; } } hookState.gotoHook(0); } /** * Used to expand all comments, hiding the preview and showing the comment. * @param {String} prefix The level of the comment -- one of * ('cl', 'file', 'inline') * @param {Integer} num_comments The number of comments to show */ function M_showAllComments(prefix, num_comments) { for (var i = 0; i < num_comments; i++) { M_hideElement(prefix + "-preview-" + i); M_showElement(prefix + "-comment-" + i); } } /** * Used to collpase all comments, showing the preview and hiding the comment. * @param {String} prefix The level of the comment -- one of * ('cl', 'file', 'inline') * @param {Integer} num_comments The number of comments to hide */ function M_hideAllComments(prefix, num_comments) { for (var i = 0; i < num_comments; i++) { M_showElement(prefix + "-preview-" + i); M_hideElement(prefix + "-comment-" + i); } } // Common methods for comment handling (changelist.html, file.html, // comment_form.html) /** * Toggles whether the specified comment is expanded/collapsed. Works in * the review form. * @param {String} prefix The prefix of the comment element name. * @param {String} suffix The suffix of the comment element name. */ function M_switchCommentCommon_(prefix, suffix) { prefix && (prefix += '-'); suffix && (suffix = '-' + suffix); var previewSpan = document.getElementById(prefix + 'preview' + suffix); var commentDiv = document.getElementById(prefix + 'comment' + suffix); if (!previewSpan || !commentDiv) { alert('Failed to find comment element: ' + prefix + 'comment' + suffix + '. Please send ' + 'this message with the URL to the app owner'); return; } if (previewSpan.style.display == 'none') { M_showElement(previewSpan); M_hideElement(commentDiv); } else { M_hideElement(previewSpan); M_showElement(commentDiv); } } /** * Expands all inline comments. */ function M_expandAllInlineComments() { M_showAllInlineComments(); var comments = document.getElementsByName("inline-comment"); var commentsLength = comments.length; for (var i = 0; i < commentsLength; i++) { comments[i].style.display = ""; } var previews = document.getElementsByName("inline-preview"); var previewsLength = previews.length; for (var i = 0; i < previewsLength; i++) { previews[i].style.display = "none"; } } /** * Collapses all inline comments. */ function M_collapseAllInlineComments() { M_showAllInlineComments(); var comments = document.getElementsByName("inline-comment"); var commentsLength = comments.length; for (var i = 0; i < commentsLength; i++) { comments[i].style.display = "none"; } var previews = document.getElementsByName("inline-preview"); var previewsLength = previews.length; for (var i = 0; i < previewsLength; i++) { previews[i].style.display = ""; } } // Non-inline comment actions /** * Sets up a reply form for a given comment (non-inline). * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {Integer} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} prefix The level of the comment -- one of * ('cl', 'file', 'inline') * @param {Integer} opt_lineno (optional) The line number the comment should be * attached to * @param {String} opt_snapshot (optional) The snapshot ID of the comment being * replied to */ function M_replyToComment(author, written_time, ccs, cid, prefix, opt_lineno, opt_snapshot) { var form = document.getElementById("comment-form-" + cid); if (!form) { form = document.getElementById("dareplyform"); if (!form) { form = document.getElementById("daform"); // XXX for file.html } form = form.cloneNode(true); form.name = form.id = "comment-form-" + cid; M_createResizer_(form, cid); document.getElementById(prefix + "-comment-" + cid).appendChild(form); } form.style.display = ""; form.reply_to.value = cid; form.ccs.value = ccs; if (typeof opt_lineno != 'undefined' && typeof opt_snapshot != 'undefined') { form.lineno.value = opt_lineno; form.snapshot.value = opt_snapshot; } form.text.value = "On " + written_time + ", " + author + " wrote:\n"; var divs = document.getElementsByName("comment-text-" + cid); M_setValueFromDivs(divs, form.text); form.text.value += "\n"; form.text.focus(); } /** /* TODO(andi): docstring */ function M_replyToMessage(message_id, written_time, author) { var form = document.getElementById('message-reply-form'); form = form.cloneNode(true); var container = document.getElementById('message-reply-'+message_id); var replyLink = document.getElementById('message-reply-href-'+message_id); var msgTextarea = replyLink.nextSibling.nextSibling; form.insertBefore(msgTextarea, form.firstChild); M_showElement(msgTextarea); container.appendChild(form); M_showElement(container); form.discard.onclick = function () { form.message.value = ""; M_getParent(container).insertBefore(msgTextarea, replyLink.nextSibling.nextSibling); M_showElement(replyLink); M_hideElement(msgTextarea); container.innerHTML = ""; } form.send_mail.id = 'message-reply-send-mail-'+message_id; var lbl = document.getElementById(form.send_mail.id).nextSibling.nextSibling; lbl.setAttribute('for', form.send_mail.id); if (!form.message.value) { form.message.value = "On " + written_time + ", " + author + " wrote:\n"; var divs = document.getElementsByName("cl-message-" + message_id); form.message.focus(); M_setValueFromDivs(divs, form.message); form.message.value += "\n"; } M_addTextResizer_(form); M_hideElement(replyLink); } /** * Edits a non-inline draft comment. * @param {Integer} cid The number of the comment to be edited */ function M_editComment(cid) { var suffix = String(cid); var form = document.getElementById("comment-form-" + suffix); if (!form) { alert("Form " + suffix + " does not exist. Please send this message " + "with the URL to the app owner"); return false; } var texts = document.getElementsByName("comment-text-" + suffix); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { texts[i].style.display = "none"; } M_hideElement("edit-link-" + suffix); M_hideElement("undo-link-" + suffix); form.style.display = ""; form.text.focus(); } /** * Used to cancel comment editing, this will revert the text of the comment * and hide its form. * @param {Element} form The form that contains this comment * @param {Integer} cid The number of the comment being hidden */ function M_resetAndHideComment(form, cid) { form.text.blur(); form.text.value = form.oldtext.value; form.style.display = "none"; var texts = document.getElementsByName("comment-text-" + cid); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { texts[i].style.display = ""; } M_showElement("edit-link-" + cid); } /** * Removing a draft comment is the same as setting its text contents to nothing. * @param {Element} form The form containing the draft comment to be discarded * @return true in order for the form submission to continue */ function M_removeComment(form) { form.text.value = ""; return true; } // Inline comments (file.html) /** * Helper method to assign an onclick handler to an inline 'Cancel' button. * @param {Element} form The form containing the cancel button * @param {Function} cancelHandler A function with one 'form' argument * @param {Array} opt_handlerParams An array whose first three elements are: * {String} cid The number of the comment * {String} lineno The line number of the comment * {String} side 'a' or 'b' */ function M_assignToCancel_(form, cancelHandler, opt_handlerParams) { var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { if (form.elements[i].getAttribute("name") == "cancel") { form.elements[i].onclick = function() { if (typeof opt_handlerParams != "undefined") { var cid = opt_handlerParams[0]; var lineno = opt_handlerParams[1]; var side = opt_handlerParams[2]; cancelHandler(form, cid, lineno, side); } else { cancelHandler(form); } }; return; } } } /** * Helper method to assign an onclick handler to an inline '[+]' link. * @param {Element} form The form containing the resizer * @param {String} suffix The suffix of the comment form id: lineno-side */ function M_createResizer_(form, suffix) { if (!form.hasResizer) { var resizer = document.getElementById("resizer").cloneNode(true); resizer.onclick = function() { var form = document.getElementById("comment-form-" + suffix); if (!form) return; form.text.rows += 5; form.text.focus(); }; var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { var node = form.elements[i]; if (node.nodeName == "TEXTAREA") { var parent = M_getParent(node); parent.insertBefore(resizer, node.nextSibling); resizer.style.display = ""; form.hasResizer = true; } } } } /** * Like M_createResizer_(), but updates the form's first textarea field. * This is assumed not to be the last field. * @param {Element} form The form whose textarea field to update. */ function M_addTextResizer_(form) { if (M_isWebKit()) { return; // WebKit has its own resizer. } var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { var node = form.elements[i]; if (node.nodeName == "TEXTAREA") { var parent = M_getParent(node); var resizer = document.getElementById("resizer").cloneNode(true); var next = node.nextSibling; parent.insertBefore(resizer, next); resizer.onclick = function() { node.rows += 5; node.focus(); }; resizer.style.display = ""; if (next && next.className == "resizer") { // Remove old resizer. parent.removeChild(next); } break; } } } /** * Helper method to assign an onclick handler to an inline 'Save' button. * @param {Element} form The form containing the save button * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_assignToSave_(form, cid, lineno, side) { var elementsLength = form.elements.length; for (var i = 0; i < elementsLength; ++i) { if (form.elements[i].getAttribute("name") == "save") { form.elements[i].onclick = function() { return M_submitInlineComment(form, cid, lineno, side); }; return; } } } /** * Creates an inline comment at the given line number and side of the diff. * @param {String} lineno The line number of the new comment * @param {String} side Either 'a' or 'b' signifying the side of the diff */ function M_createInlineComment(lineno, side) { // The first field of the suffix is typically the cid, but we choose '-1' // here since the backend has not assigned the new comment a cid yet. var suffix = "-1-" + lineno + "-" + side; var form = document.getElementById("comment-form-" + suffix); if (!form) { form = document.getElementById("dainlineform").cloneNode(true); form.name = form.id = "comment-form-" + suffix; M_assignToCancel_(form, M_removeTempInlineComment); M_createResizer_(form, suffix); M_assignToSave_(form, "-1", lineno, side); // There is a "text" node before the "div" node form.childNodes[1].setAttribute("name", "comment-border"); var id = (side == 'a' ? "old" : "new") + "-line-" + lineno; var td = document.getElementById(id); td.appendChild(form); var tr = M_getParent(td); tr.setAttribute("name", "hook"); hookState.updateHooks(); } form.style.display = ""; form.lineno.value = lineno; if (side == 'b') { form.snapshot.value = new_snapshot; } else { form.snapshot.value = old_snapshot; } form.side.value = side; var savedDraftKey = "new-" + form.lineno.value + "-" + form.snapshot.value; M_restoreDraftText_(savedDraftKey, form); form.text.focus(); hookState.gotoHook(0); } /** * Removes a never-submitted 'Reply' inline comment from existence (created via * M_replyToInlineComment). * @param {Element} form The form that contains the comment to be removed * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_removeTempReplyInlineComment(form, cid, lineno, side) { var divInlineComment = M_getParent(form); var divCommentBorder = M_getParent(divInlineComment); var td = M_getParent(divCommentBorder); var tr = M_getParent(td); form.cancel.blur(); // The order of the subsequent lines is sensitive to browser compatibility. var suffix = cid + "-" + lineno + "-" + side; M_saveDraftText_("reply-" + suffix, form.text.value); divInlineComment.removeChild(form); M_updateRowHook(tr); } /** * Removes a never-submitted inline comment from existence (created via * M_createInlineComment). Saves the existing text for the next time a draft is * created on the same line. * @param {Element} form The form that contains the comment to be removed */ function M_removeTempInlineComment(form) { var td = M_getParent(form); var tr = M_getParent(td); // The order of the subsequent lines is sensitive to browser compatibility. var savedDraftKey = "new-" + form.lineno.value + "-" + form.snapshot.value; M_saveDraftText_(savedDraftKey, form.text.value); form.cancel.blur(); td.removeChild(form); M_updateRowHook(tr); } /** * Helper to edit a draft inline comment. * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @return {Element} The form that contains the comment */ function M_editInlineCommentCommon_(cid, lineno, side) { var suffix = cid + "-" + lineno + "-" + side; var form = document.getElementById("comment-form-" + suffix); if (!form) { alert("Form " + suffix + " does not exist. Please send this message " + "with the URL to the app owner"); return false; } M_createResizer_(form, suffix); var texts = document.getElementsByName("comment-text-" + suffix); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { texts[i].style.display = "none"; } var hides = document.getElementsByName("comment-hide-" + suffix); var hidesLength = hides.length; for (var i = 0; i < hidesLength; i++) { hides[i].style.display = "none"; var links = hides[i].getElementsByTagName("A"); if (links && links.length > 0) { var link = links[0]; link.innerHTML = "Show quoted text"; } } M_hideElement("edit-link-" + suffix); M_hideElement("undo-link-" + suffix); form.style.display = ""; var parent = document.getElementById("inline-comment-" + suffix); if (parent && parent.style.display == "none") { M_switchInlineComment(cid, lineno, side); } form.text.focus(); hookState.gotoHook(0); return form; } /** * Edits a draft inline comment. * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_editInlineComment(cid, lineno, side) { M_editInlineCommentCommon_(cid, lineno, side); } /** * Restores a canceled draft inline comment for editing. * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_restoreEditInlineComment(cid, lineno, side) { var form = M_editInlineCommentCommon_(cid, lineno, side); var savedDraftKey = "edit-" + cid + "-" + lineno + "-" + side; M_restoreDraftText_(savedDraftKey, form, false); } /** * Helper to reply to an inline comment. * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {String} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @param {String} opt_reply The response to pre-fill with. * @param {Boolean} opt_submit This will submit the comment right after * creation. Only makes sense when opt_reply is set * @return {Element} The form that contains the comment */ function M_replyToInlineCommentCommon_(author, written_time, cid, lineno, side, opt_reply, opt_submit) { var suffix = cid + "-" + lineno + "-" + side; var form = document.getElementById("comment-form-" + suffix); if (!form) { form = document.getElementById("dainlineform").cloneNode(true); form.name = form.id = "comment-form-" + suffix; M_assignToCancel_(form, M_removeTempReplyInlineComment, [cid, lineno, side]); M_assignToSave_(form, cid, lineno, side); M_createResizer_(form, suffix); var parent = document.getElementById("inline-comment-" + suffix); if (parent.style.display == "none") { M_switchInlineComment(cid, lineno, side); } parent.appendChild(form); } form.style.display = ""; form.lineno.value = lineno; if (side == 'b') { form.snapshot.value = new_snapshot; } else { form.snapshot.value = old_snapshot; } form.side.value = side; if (!M_restoreDraftText_("reply-" + suffix, form, false) || typeof opt_reply != "undefined") { form.text.value = "On " + written_time + ", " + author + " wrote:\n"; var divs = document.getElementsByName("comment-text-" + suffix); M_setValueFromDivs(divs, form.text); form.text.value += "\n"; if (typeof opt_reply != "undefined") { form.text.value += opt_reply; } if (opt_submit) { M_submitInlineComment(form, cid, lineno, side); return; } } form.text.focus(); hookState.gotoHook(0); return form; } /** * Replies to an inline comment. * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {String} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @param {String} opt_reply The response to pre-fill with. * @param {Boolean} opt_submit This will submit the comment right after * creation. Only makes sense when opt_reply is set */ function M_replyToInlineComment(author, written_time, cid, lineno, side, opt_reply, opt_submit) { M_replyToInlineCommentCommon_(author, written_time, cid, lineno, side, opt_reply, opt_submit); } /** * Restores a canceled draft inline comment for reply. * @param {String} author The author of the comment being replied to * @param {String} written_time The formatted time when that comment was written * @param {String} ccs A string containing the ccs to default to * @param {String} cid The number of the comment being replied to, so that the * form may be placed in the appropriate location * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_restoreReplyInlineComment(author, written_time, cid, lineno, side) { var form = M_replyToInlineCommentCommon_(author, written_time, cid, lineno, side); var savedDraftKey = "reply-" + cid + "-" + lineno + "-" + side; M_restoreDraftText_(savedDraftKey, form, false); } /** * Updates an inline comment td with the given HTML. * @param {Element} td The TD that contains the inline comment * @param {String} html The text to be put into .innerHTML of the td */ function M_updateInlineComment(td, html) { var tr = M_getParent(td); if (!tr) { alert("TD had no parent. Please notify the app owner."); return; } // The server sends back " " to make things empty, for Safari if (html.length <= 1) { td.innerHTML = ""; M_updateRowHook(tr); } else { td.innerHTML = html; tr.name = "hook"; hookState.updateHooks(); } } /** * Updates a comment tr's name, depending on whether there are now comments * in it or not. Also updates the hook cache if required. Assumes that the * given TR already has name == "hook" and only tries to remove it if all * are empty. * @param {Element} tr The TR containing the potential comments */ function M_updateRowHook(tr) { if (!(tr && tr.cells)) return; // If all of the TR's cells are empty, remove the hook name var i = 0; var numCells = tr.cells.length; for (i = 0; i < numCells; i++) { if (tr.cells[i].innerHTML != "") { break; } } if (i == numCells) { tr.setAttribute("name", ""); hookState.updateHooks(); } hookState.gotoHook(0); } /** * Submits an inline comment and updates the DOM in AJAX fashion with the new * comment data for that line. * @param {Element} form The form containing the submitting comment * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' * @return true if AJAX fails and the form should be submitted the "old" way, * or false if the form is submitted using AJAX, preventing the regular * form submission from proceeding */ function M_submitInlineComment(form, cid, lineno, side) { var td = null; if (form.side.value == 'a') { td = document.getElementById("old-line-" + form.lineno.value); } else { td = document.getElementById("new-line-" + form.lineno.value); } if (!td) { alert("Could not find snapshot " + form.snapshot.value + "! Please let " + "the app owner know."); return true; } if (typeof side == "undefined") { side = form.side.value; } // Clear saved draft state for affected new, edited, and replied comments if (typeof cid != "undefined" && typeof lineno != "undefined" && side) { var suffix = cid + "-" + lineno + "-" + side; M_clearDraftText_("new-" + lineno + "-" + form.snapshot.value); M_clearDraftText_("edit-" + suffix); M_clearDraftText_("reply-" + suffix); M_hideElement("undo-link-" + suffix); } var httpreq = M_getXMLHttpRequest(); if (!httpreq) { // No AJAX. Oh well. Go ahead and submit this the old way. return true; } // Konqueror jumps to a random location for some reason var scrollTop = M_getScrollTop(window); var aborted = false; reenable_form = function() { form.save.disabled = false; form.cancel.disabled = false; if (form.discard != null) { form.discard.disabled = false; } form.text.disabled = false; form.style.cursor = "auto"; }; // This timeout can potentially race with the request coming back OK. In // general, if it hasn't come back for 60 seconds, it won't ever come back. var httpreq_timeout = setTimeout(function() { aborted = true; httpreq.abort(); reenable_form(); alert("Comment could not be submitted for 60 seconds. Please ensure " + "connectivity (and that the server is up) and try again."); }, 60000); httpreq.onreadystatechange = function () { // Firefox 2.0, at least, runs this with readyState = 4 but all other // fields unset when the timeout aborts the request, against all // documentation. if (httpreq.readyState == 4 && !aborted) { clearTimeout(httpreq_timeout); if (httpreq.status == 200) { M_updateInlineComment(td, httpreq.responseText); } else { reenable_form(); alert("An error occurred while trying to submit the comment: " + httpreq.statusText); } if (M_isKHTML()) { window.scrollTo(0, scrollTop); } } } httpreq.open("POST", base_url + "inline_draft", true); httpreq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var req = []; var len = form.elements.length; for (var i = 0; i < len; i++) { var element = form.elements[i]; if (element.type == "hidden" || element.type == "textarea") { req.push(element.name + "=" + encodeURIComponent(element.value)); } } req.push("side=" + side); // Disable forever. If this succeeds, then the form will end up getting // rewritten, and if it fails, the page should get a refresh anyways. form.save.blur(); form.save.disabled = true; form.cancel.blur(); form.cancel.disabled = true; if (form.discard != null) { form.discard.blur(); form.discard.disabled = true; } form.text.blur(); form.text.disabled = true; form.style.cursor = "wait"; // Send the request httpreq.send(req.join("&")); // No need to resubmit this form. return false; } /** * Removes a draft inline comment. * @param {Element} form The form that contains the comment to be removed * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_removeInlineComment(form, cid, lineno, side) { // Update state to save the canceled edit text var snapshot = side == "a" ? old_snapshot : new_snapshot; var savedDraftKey = "new-" + lineno + "-" + snapshot; var savedText = form.text.value; form.text.value = ""; var ret = M_submitInlineComment(form, cid, lineno, side); M_saveDraftText_(savedDraftKey, savedText); return ret; } /** * Combines all the divs from a single comment (generated by multiple buckets) * and undoes the escaping work done by Django filters, and inserts the result * into a given textarea. * @param {Array} divs An array of div elements to be combined * @param {Element} text The textarea whose value needs to be updated */ function M_setValueFromDivs(divs, text) { var lines = []; var divsLength = divs.length; for (var i = 0; i < divsLength; i++) { lines = lines.concat(divs[i].innerHTML.split("\n")); // It's _fairly_ certain that the last line in the div will be // empty, based on how the template works. If the last line in the // array is empty, then ignore it. if (lines.length > 0 && lines[lines.length - 1] == "") { lines.length = lines.length - 1; } } for (var i = 0; i < lines.length; i++) { // Undo the <a> tags added by urlize and urlizetrunc lines[i] = lines[i].replace(/<a (.*?)href=[\'\"]([^\'\"]+?)[\'\"](.*?)>(.*?)<\/a>/ig, '$2'); // Undo the escape Django filter lines[i] = lines[i].replace(/&gt;/ig, ">"); lines[i] = lines[i].replace(/&lt;/ig, "<"); lines[i] = lines[i].replace(/&quot;/ig, "\""); lines[i] = lines[i].replace(/&#39;/ig, "'"); lines[i] = lines[i].replace(/&amp;/ig, "&"); // Must be last text.value += "> " + lines[i] + "\n"; } } /** * Undo an edit of a draft inline comment, i.e. discard changes. * @param {Element} form The form containing the edits * @param {String} cid The number of the comment * @param {String} lineno The line number of the comment * @param {String} side 'a' or 'b' */ function M_resetAndHideInlineComment(form, cid, lineno, side) { // Update canceled edit state var suffix = cid + "-" + lineno + "-" + side; M_saveDraftText_("edit-" + suffix, form.text.value); if (form.text.value != form.oldtext.value) { M_showElement("undo-link-" + suffix); } form.text.blur(); form.text.value = form.oldtext.value; form.style.display = "none"; var texts = document.getElementsByName("comment-text-" + suffix); var textsLength = texts.length; for (var i = 0; i < textsLength; i++) { if (texts[i].className.indexOf("comment-text-quoted") < 0) { texts[i].style.display = ""; } } var hides = document.getElementsByName("comment-hide-" + suffix); var hidesLength = hides.length; for (var i = 0; i < hidesLength; i++) { hides[i].style.display = ""; } M_showElement("edit-link-" + suffix); hookState.gotoHook(0); } /** * Toggles whether we display quoted text or not, both for inline and regular * comments. Inline comments will have lineno and side defined. * @param {String} cid The comment number * @param {String} bid The bucket number in that comment * @param {String} lineno (optional) Line number of the comment * @param {String} side (optional) 'a' or 'b' */ function M_switchQuotedText(cid, bid, lineno, side) { var tmp = "" if (typeof lineno != 'undefined' && typeof side != 'undefined') tmp = "-" + lineno + "-" + side; var extra = cid + tmp + "-" + bid; var div = document.getElementById("comment-text-" + extra); var a = document.getElementById("comment-hide-link-" + extra); if (div.style.display == "none") { div.style.display = ""; a.innerHTML = "Hide quoted text"; } else { div.style.display = "none"; a.innerHTML = "Show quoted text"; } if (tmp != "") { hookState.gotoHook(0); } } /** * Handler for the double click event in the code table element. Creates a new * inline comment for that line of code on the right side of the diff. * @param {Event} evt The event object for this double-click event */ function M_handleTableDblClick(evt) { if (!logged_in) { if (!login_warned) { login_warned = true; alert("Please sign in to enter inline comments."); } return; } var evt = evt ? evt : (event ? event : null); var target = M_getEventTarget(evt); if (target.tagName == 'INPUT' || target.tagName == 'TEXTAREA') { return; } while (target != null && target.tagName != 'TD') { target = M_getParent(target); } if (target == null) { return; } var side = null; if (target.id.substr(0, 7) == "newcode") { side = 'b'; } else if (target.id.substr(0, 7) == "oldcode") { side = 'a'; } if (side != null) { M_createInlineComment(parseInt(target.id.substr(7)), side); } } var M_timerLongTap = null; /** * Resets the long tap timer iff activated. */ function M_clearTableTouchTimeout() { if (M_timerLongTap) { clearTimeout(M_timerLongTap); } M_timerLongTap = null; } /** * Handles long tap events on mobile devices (touchstart). * * This function activates a 1sec timeout that redirects the event to * M_handleTableDblClick(). */ function M_handleTableTouchStart(evt) { if (evt.touches && evt.touches.length == 1) { // 1 finger touch M_clearTableTouchTimeout(); M_timerLongTap = setTimeout(function() { M_clearTableTouchTimeout(); M_handleTableDblClick(evt); }, 1000); } } /** * Handles touchend event for long taps on mobile devices. */ function M_handleTableTouchEnd(evt) { M_clearTableTouchTimeout(); } /** * Makes all inline comments visible. This is the default view. */ function M_showAllInlineComments() { var hide_elements = document.getElementsByName("hide-all-inline"); var show_elements = document.getElementsByName("show-all-inline"); for (var i = 0; i < hide_elements.length; i++) { hide_elements[i].style.display = ""; } var elements = document.getElementsByName("comment-border"); var elementsLength = elements.length; for (var i = 0; i < elementsLength; i++) { var tr = M_getParent(M_getParent(elements[i])); tr.style.display = ""; tr.name = "hook"; } for (var i = 0; i < show_elements.length; i++) { show_elements[i].style.display = "none"; } hookState.updateHooks(); } /** * Hides all inline comments, to make code easier ot read. */ function M_hideAllInlineComments() { var hide_elements = document.getElementsByName("hide-all-inline"); var show_elements = document.getElementsByName("show-all-inline"); for (var i = 0; i < show_elements.length; i++) { show_elements[i].style.display = ""; } var elements = document.getElementsByName("comment-border"); var elementsLength = elements.length; for (var i = 0; i < elementsLength; i++) { var tr = M_getParent(M_getParent(elements[i])); tr.style.display = "none"; tr.name = ""; } for (var i = 0; i < hide_elements.length; i++) { hide_elements[i].style.display = "none"; } hookState.updateHooks(); } /** * Flips between making inline comments visible and invisible. */ function M_toggleAllInlineComments() { var show_elements = document.getElementsByName("show-all-inline"); if (!show_elements) { return; } if (show_elements[0].style.display == "none") { M_hideAllInlineComments(); } else { M_showAllInlineComments(); } } /** * Navigates to the diff with the requested versions on left/right */ function M_navigateDiff(issueid, filename) { var left = document.getElementById('left').value; var right = document.getElementById('right').value; if (left == '-1') { window.location.href = base_url + issueid + '/diff/' + right + '/' + filename; } else { window.location.href = base_url + issueid + '/diff2/' + left + ':' + right + '/' + filename; } } // File view keyboard navigation /** * M_HookState class. Keeps track of the current 'hook' that we are on and * responds to n/p/N/P events. * @param {Window} win The window that the table is in. * @constructor */ function M_HookState(win) { /** * -2 == top of page; -1 == diff; or index into hooks array * @type Integer */ this.hookPos = -2; /** * A cache of visible table rows with tr.name == "hook" * @type Array */ this.visibleHookCache = []; /** * The indicator element that we move around * @type Element */ this.indicator = document.getElementById("hook-sel"); /** * Caches whether we are in an IE browser * @type Boolean */ this.isIE = M_isIE(); /** * The window that the table with the hooks is in * @type Window */ this.win = win; } /** * Find all the hook locations in a browser-portable fashion, and store them * in a cache. * @return Array of TR elements. */ M_HookState.prototype.computeHooks_ = function() { var allHooks = null; if (this.isIE) { // IE only recognizes the 'name' attribute on tags that are supposed to // have one, such as... not TR. var tmpHooks = document.getElementsByTagName("TR"); var tmpHooksLength = tmpHooks.length; allHooks = []; for (var i = 0; i < tmpHooksLength; i++) { if (tmpHooks[i].name == "hook") { allHooks.push(tmpHooks[i]); } } } else { allHooks = document.getElementsByName("hook"); } var visibleHooks = []; var allHooksLength = allHooks.length; for (var i = 0; i < allHooksLength; i++) { var hook = allHooks[i]; if (hook.style.display == "") { visibleHooks.push(hook); } } this.visibleHookCache = visibleHooks; return visibleHooks; }; /** * Recompute all the hook positions, update the hookPos, and update the * indicator's position if necessary, but do not scroll. */ M_HookState.prototype.updateHooks = function() { var curHook = null; if (this.hookPos >= 0 && this.hookPos < this.visibleHookCache.length) { curHook = this.visibleHookCache[this.hookPos]; } this.computeHooks_(); var newHookPos = -1; if (curHook != null) { for (var i = 0; i < this.visibleHookCache.length; i++) { if (this.visibleHookCache[i] == curHook) { newHookPos = i; break; } } } if (newHookPos != -1) { this.hookPos = newHookPos; } this.gotoHook(0); }; /** * Update the indicator's position to be at the top of the table row. * @param {Element} tr The tr whose top the indicator will be lined up with. */ M_HookState.prototype.updateIndicator_ = function(tr) { // Find out where the table's top is, and add one so that when we align // the position indicator, it takes off 1px from one tr and 1px from another. // This must be computed every time since the top of the table may move due // to window resizing. var tableTop = M_getPageOffsetTop(document.getElementById("table-top")) + 1; this.indicator.style.top = String(M_getPageOffsetTop(tr) - tableTop) + "px"; var totWidth = 0; var numCells = tr.cells.length; for (var i = 0; i < numCells; i++) { totWidth += tr.cells[i].clientWidth; } this.indicator.style.left = "0px"; this.indicator.style.width = totWidth + "px"; this.indicator.style.display = ""; }; /** * Update the indicator's position, and potentially scroll to the proper * location. Computes the new position based on current scroll position, and * whether the previously selected hook was visible. * @param {Integer} direction Scroll direction: -1 for up only, 1 for down only, * 0 for no scrolling. */ M_HookState.prototype.gotoHook = function(direction) { var hooks = this.visibleHookCache; // Hide the current selection image this.indicator.style.display = "none"; // Add a border to all td's in the selected row if (this.hookPos < -1) { if (direction != 0) { window.scrollTo(0, 0); } this.hookPos = -2; } else if (this.hookPos == -1) { var diffs = document.getElementsByName("diffs"); if (diffs && diffs.length >= 1) { diffs = diffs[0]; } if (diffs && direction != 0) { window.scrollTo(0, M_getPageOffsetTop(diffs)); } this.updateIndicator_(document.getElementById("thecode").rows[0]); } else { if (this.hookPos < hooks.length) { var hook = hooks[this.hookPos]; for (var i = 0; i < hook.cells.length; i++) { var td = hook.cells[i]; if (td.id != null && td.id != "") { if (direction != 0) { M_scrollIntoView(this.win, td, direction); } break; } } // Found one! this.updateIndicator_(hook); } else { if (direction != 0) { window.scrollTo(0, document.body.offsetHeight); } this.hookPos = hooks.length; var thecode = document.getElementById("thecode"); this.updateIndicator_(thecode.rows[thecode.rows.length - 1]); } } }; /** * Set this.hookPos to the next desired hook. * @param {Boolean} findComment Whether to look only for comment hooks */ M_HookState.prototype.incrementHook_ = function(findComment) { var hooks = this.visibleHookCache; if (findComment) { this.hookPos = Math.max(0, this.hookPos + 1); while (this.hookPos < hooks.length && hooks[this.hookPos].className != "inline-comments") { this.hookPos++; } } else { this.hookPos = Math.min(hooks.length, this.hookPos + 1); } }; /** * Set this.hookPos to the previous desired hook. * @param {Boolean} findComment Whether to look only for comment hooks */ M_HookState.prototype.decrementHook_ = function(findComment) { var hooks = this.visibleHookCache; if (findComment) { this.hookPos = Math.min(hooks.length - 1, this.hookPos - 1); while (this.hookPos >= 0 && hooks[this.hookPos].className != "inline-comments") { this.hookPos--; } } else { this.hookPos = Math.max(-2, this.hookPos - 1); } }; /** * Find the first document element in sorted array elts whose vertical position * is greater than the given height from the top of the document. Optionally * look only for comment elements. * * @param {Integer} height The height in pixels from the top * @param {Array.<Element>} elts Document elements * @param {Boolean} findComment Whether to look only for comment elements * @return {Integer} The index of such an element, or elts.length otherwise */ function M_findElementAfter_(height, elts, findComment) { for (var i = 0; i < elts.length; ++i) { if (M_getPageOffsetTop(elts[i]) > height) { if (!findComment || elts[i].className == "inline-comments") { return i; } } } return elts.length; } /** * Find the last document element in sorted array elts whose vertical position * is less than the given height from the top of the document. Optionally * look only for comment elements. * * @param {Integer} height The height in pixels from the top * @param {Array.<Element>} elts Document elements * @param {Boolean} findComment Whether to look only for comment elements * @return {Integer} The index of such an element, or -1 otherwise */ function M_findElementBefore_(height, elts, findComment) { for (var i = elts.length - 1; i >= 0; --i) { if (M_getPageOffsetTop(elts[i]) < height) { if (!findComment || elts[i].className == "inline-comments") { return i; } } } return -1; } /** * Move to the next hook indicator and scroll. * @param opt_findComment {Boolean} Whether to look only for comment hooks */ M_HookState.prototype.gotoNextHook = function(opt_findComment) { // If the current hook is not on the page, select the first hook that is // either on the screen or below. var hooks = this.visibleHookCache; var diffs = document.getElementsByName("diffs"); var thecode = document.getElementById("thecode"); var findComment = Boolean(opt_findComment); if (diffs && diffs.length >= 1) { diffs = diffs[0]; } if (this.hookPos >= 0 && this.hookPos < hooks.length && M_isElementVisible(this.win, hooks[this.hookPos].cells[0])) { this.incrementHook_(findComment); } else if (this.hookPos == -2 && (M_isElementVisible(this.win, diffs) || M_getScrollTop(this.win) < M_getPageOffsetTop(diffs))) { this.incrementHook_(findComment) } else if (this.hookPos < hooks.length || (this.hookPos >= hooks.length && !M_isElementVisible( this.win, thecode.rows[thecode.rows.length - 1].cells[0]))) { var scrollTop = M_getScrollTop(this.win); this.hookPos = M_findElementAfter_(scrollTop, hooks, findComment); } this.gotoHook(1); }; /** * Move to the previous hook indicator and scroll. * @param opt_findComment {Boolean} Whether to look only for comment hooks */ M_HookState.prototype.gotoPrevHook = function(opt_findComment) { // If the current hook is not on the page, select the last hook that is // above the bottom of the screen window. var hooks = this.visibleHookCache; var diffs = document.getElementsByName("diffs"); var findComment = Boolean(opt_findComment); if (diffs && diffs.length >= 1) { diffs = diffs[0]; } if (this.hookPos == 0 && findComment) { this.hookPos = -2; } else if (this.hookPos >= 0 && this.hookPos < hooks.length && M_isElementVisible(this.win, hooks[this.hookPos].cells[0])) { this.decrementHook_(findComment); } else if (this.hookPos > hooks.length) { this.hookPos = hooks.length; } else if (this.hookPos == -1 && M_isElementVisible(this.win, diffs)) { this.decrementHook_(findComment); } else if (this.hookPos == -2 && M_getScrollTop(this.win) == 0) { } else { var scrollBot = M_getScrollTop(this.win) + M_getWindowHeight(this.win); this.hookPos = M_findElementBefore_(scrollBot, hooks, findComment); } // The top of the diffs table is irrelevant if we want comment hooks. if (findComment && this.hookPos <= -1) { this.hookPos = -2; } this.gotoHook(-1); }; /** * If the currently selected hook is a comment, either respond to it or edit * the draft if there is one already. Prefer the right side of the table. */ M_HookState.prototype.respond = function() { var hooks = this.visibleHookCache; if (this.hookPos >= 0 && this.hookPos < hooks.length && M_isElementVisible(this.win, hooks[this.hookPos].cells[0])) { // Go through this tr and try responding to the last comment. The general // hope is that these are returned in DOM order var comments = hooks[this.hookPos].getElementsByTagName("div"); var commentsLength = comments.length; if (comments && commentsLength == 0) { // Don't give up too early and look a bit forward var sibling = hooks[this.hookPos].nextSibling; while (sibling && sibling.tagName != "TR") { sibling = sibling.nextSibling; } comments = sibling.getElementsByTagName("div"); commentsLength = comments.length; } if (comments && commentsLength > 0) { var last = null; for (var i = commentsLength - 1; i >= 0; i--) { if (comments[i].getAttribute("name") == "comment-border") { last = comments[i]; break; } } if (last) { var links = last.getElementsByTagName("a"); if (links) { for (var i = links.length - 1; i >= 0; i--) { if (links[i].getAttribute("name") == "comment-reply" && links[i].style.display != "none") { document.location.href = links[i].href; return; } } } } } else { // Create a comment at this line // TODO: Implement this in a sane fashion, e.g. opens up a comment // at the end of the diff chunk. var tr = hooks[this.hookPos]; for (var i = tr.cells.length - 1; i >= 0; i--) { if (tr.cells[i].id.substr(0, 7) == "newcode") { M_createInlineComment(parseInt(tr.cells[i].id.substr(7)), 'b'); return; } else if (tr.cells[i].id.substr(0, 7) == "oldcode") { M_createInlineComment(parseInt(tr.cells[i].id.substr(7)), 'a'); return; } } } } }; // Intra-line diff handling /** * IntraLineDiff class. Initializes structures to keep track of highlighting * state. * @constructor */ function M_IntraLineDiff() { /** * Whether we are showing intra-line changes or not * @type Boolean */ this.intraLine = true; /** * "oldreplace" css rule * @type CSSStyleRule */ this.oldReplace = null; /** * "oldlight" css rule * @type CSSStyleRule */ this.oldLight = null; /** * "newreplace" css rule * @type CSSStyleRule */ this.newReplace = null; /** * "newlight" css rule * @type CSSStyleRule */ this.newLight = null; /** * backup of the "oldreplace" css rule's background color * @type DOMString */ this.saveOldReplaceBkgClr = null; /** * backup of the "newreplace" css rule's background color * @type DOMString */ this.saveNewReplaceBkgClr = null; /** * "oldreplace1" css rule's background color * @type DOMString */ this.oldIntraBkgClr = null; /** * "newreplace1" css rule's background color * @type DOMString */ this.newIntraBkgClr = null; this.findStyles_(); } /** * Finds the styles in the document and keeps references to them in this class * instance. */ M_IntraLineDiff.prototype.findStyles_ = function() { var ss = document.styleSheets[0]; var rules = []; if (ss.cssRules) { rules = ss.cssRules; } else if (ss.rules) { rules = ss.rules; } for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (rule.selectorText == ".oldreplace1") { this.oldIntraBkgClr = rule.style.backgroundColor; } else if (rule.selectorText == ".newreplace1") { this.newIntraBkgClr = rule.style.backgroundColor; } else if (rule.selectorText == ".oldreplace") { this.oldReplace = rule; this.saveOldReplaceBkgClr = this.oldReplace.style.backgroundColor; } else if (rule.selectorText == ".newreplace") { this.newReplace = rule; this.saveNewReplaceBkgClr = this.newReplace.style.backgroundColor; } else if (rule.selectorText == ".oldlight") { this.oldLight = rule; } else if (rule.selectorText == ".newlight") { this.newLight = rule; } } }; /** * Toggle the highlighting of the intra line diffs, alternatively turning * them on and off. */ M_IntraLineDiff.prototype.toggle = function() { if (this.intraLine) { this.oldReplace.style.backgroundColor = this.oldIntraBkgClr; this.oldLight.style.backgroundColor = this.oldIntraBkgClr; this.newReplace.style.backgroundColor = this.newIntraBkgClr; this.newLight.style.backgroundColor = this.newIntraBkgClr; this.intraLine = false; } else { this.oldReplace.style.backgroundColor = this.saveOldReplaceBkgClr; this.oldLight.style.backgroundColor = this.saveOldReplaceBkgClr; this.newReplace.style.backgroundColor = this.saveNewReplaceBkgClr; this.newLight.style.backgroundColor = this.saveNewReplaceBkgClr; this.intraLine = true; } }; /** * A click handler common to just about every page, set in global.html. * @param {Event} evt The event object that triggered this handler. * @return false if the event was handled. */ function M_clickCommon(evt) { if (helpDisplayed) { var help = document.getElementById("help"); help.style.display = "none"; helpDisplayed = false; return false; } return true; } /** * Get a name for key combination of keydown event. * * See also http://unixpapa.com/js/key.html */ function M_getKeyName(evt) { var name = ""; if (evt.ctrlKey) { name += "Ctrl-" } if (evt.altKey) { name += "Alt-" } if (evt.shiftKey) { name += "Shift-" } if (evt.metaKey) { name += "Meta-" } // Character keys have codes of corresponding ASCII symbols if (evt.keyCode >= 65 && evt.keyCode <= 90) { return name + String.fromCharCode(evt.keyCode); } // Numeric keys seems to have codes of corresponding ASCII symbols too if (evt.keyCode >= 48 && evt.keyCode <= 57) { return name + String.fromCharCode(evt.keyCode); } // Handling special keys switch (evt.keyCode) { case 27: return name + "Esc"; case 13: return name + "Enter"; case 188: return name + ","; // [,<] case 190: return name + "."; // [.>] case 191: return name + "/"; // [/?] case 17: // Ctrl case 18: // Alt case 16: // Shift // case ??: Meta ? return name.substr(0, name.lenght-1); default: name += "<"+evt.keyCode+">"; } return name; } /** * Common keydown handler for all pages. * @param {Event} evt The event object that triggered this callback * @param {function(string)} handler Handles the specific key name; * returns false if the key was handled. * @param {function(Event, Node, int, string)} input_handler * Handles the event in case that the event source is an input field. * returns false if the key press was handled. * @return false if the event was handled */ function M_keyDownCommon(evt, handler, input_handler) { if (!evt) var evt = window.event; // for IE var target = M_getEventTarget(evt); var keyName = M_getKeyName(evt); if (target.nodeName == "TEXTAREA" || target.nodeName == "INPUT") { if (input_handler) { return input_handler(target, keyName); } return true; } if (keyName == 'Shift-/' /* '?' */ || keyName == 'Esc') { var help = document.getElementById("help"); if (help) { // Only allow the help to be turned on with the ? key. if (helpDisplayed || keyName == 'Shift-/') { helpDisplayed = !helpDisplayed; help.style.display = helpDisplayed ? "" : "none"; return false; } } return true; } return handler(keyName); } /** * Helper event handler for the keydown event in a comment textarea. * @param {Event} evt The event object that triggered this callback * @param {Node} src The textarea document element * @param {String} key The string with combination name * @return false if the event was handled */ function M_commentTextKeyDown_(src, key) { if (src.nodeName == "TEXTAREA") { if (key == 'Ctrl-S') { // Save the form corresponding to this text area. M_disableCarefulUnload(); if (src.form.save.onclick) { return src.form.save.onclick(); } else { src.form.submit(); return false; } } if (key == 'Esc') { if (src.getAttribute('id') == draftMessage.id_textarea) { draftMessage.dialog_hide(true); src.blur(); return false; } else { // textarea of inline comment return src.form.cancel.onclick(); } } } return true; } /** * Helper to find an item by its elementId and jump to it. If the item * cannot be found this will jump to the changelist instead. * @param {elementId} the id of an element an href */ function M_jumpToHrefOrChangelist(elementId) { var hrefElement = document.getElementById(elementId); if (hrefElement) { document.location.href = hrefElement.href; } else { M_upToChangelist(); } } /** * Event handler for the keydown event in the file view. * @param {Event} evt The event object that triggered this callback * @return false if the event was handled */ function M_keyDown(evt) { return M_keyDownCommon(evt, function(key) { if (key == 'N') { // next diff if (hookState) hookState.gotoNextHook(); } else if (key == 'P') { // previous diff if (hookState) hookState.gotoPrevHook(); } else if (key == 'Shift-N') { // next comment if (hookState) hookState.gotoNextHook(true); } else if (key == 'Shift-P') { // previous comment if (hookState) hookState.gotoPrevHook(true); } else if (key == 'J') { // next file M_jumpToHrefOrChangelist('nextFile') } else if (key == 'K') { // prev file M_jumpToHrefOrChangelist('prevFile') } else if (key == 'Shift-J') { // next file with comment M_jumpToHrefOrChangelist('nextFileWithComment') } else if (key == 'Shift-K') { // prev file with comment M_jumpToHrefOrChangelist('prevFileWithComment') } else if (key == 'M') { document.location.href = publish_link; } else if (key == 'Shift-M') { if (draftMessage) { draftMessage.dialog_show(); } } else if (key == 'U') { // up to CL M_upToChangelist(); } else if (key == 'I') { // toggle intra line diff if (intraLineDiff) intraLineDiff.toggle(); } else if (key == 'S') { // toggle show/hide inline comments M_toggleAllInlineComments(); } else if (key == 'E') { M_expandAllInlineComments(); } else if (key == 'C') { M_collapseAllInlineComments(); } else if (key == 'Enter') { // respond to current comment if (hookState) hookState.respond(); } else { return true; } return false; }, M_commentTextKeyDown_); } /** * Event handler for the keydown event in the changelist (issue) view. * @param {Event} evt The event object that triggered this callback * @return false if the event was handled */ function M_changelistKeyDown(evt) { return M_keyDownCommon(evt, function(key) { if (key == 'O' || key == 'Enter') { if (dashboardState) { var child = dashboardState.curTR.cells[3].firstChild; while (child && child.nextSibling && child.nodeName != "A") { child = child.nextSibling; } if (child && child.nodeName == "A") { location.href = child.href; } } } else if (key == 'I') { if (dashboardState) { var child = dashboardState.curTR.cells[2].firstChild; while (child && child.nextSibling && (child.nodeName != "A" || child.style.display == "none")) { child = child.nextSibling; } if (child && child.nodeName == "A") { location.href = child.href; } } } else if (key == 'K') { if (dashboardState) dashboardState.gotoPrev(); } else if (key == 'J') { if (dashboardState) dashboardState.gotoNext(); } else if (key == 'M') { document.location.href = publish_link; } else if (key == 'U') { // back to dashboard document.location.href = base_url; } else { return true; } return false; }); } /** * Goes from the file view back up to the changelist view. */ function M_upToChangelist() { var upCL = document.getElementById('upCL'); if (upCL) { document.location.href = upCL.href; } } /** * Asynchronously request static analysis warnings as comments. * @param {String} cl The current changelist * @param {String} depot_path The id of the target element * @param {String} a The version number of the left side to be analyzed * @param {String} b The version number of the right side to be analyzed */ function M_getBugbotComments(cl, depot_path, a, b) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return; } // Konqueror jumps to a random location for some reason var scrollTop = M_getScrollTop(window); httpreq.onreadystatechange = function () { // Firefox 2.0, at least, runs this with readyState = 4 but all other // fields unset when the timeout aborts the request, against all // documentation. if (httpreq.readyState == 4) { if (httpreq.status == 200) { M_updateWarningStatus(httpreq.responseText); } if (M_isKHTML()) { window.scrollTo(0, scrollTop); } } } httpreq.open("GET", base_url + "warnings/" + cl + "/" + depot_path + "?a=" + a + "&b=" + b, true); httpreq.send(null); } /** * Updates a warning status td with the given HTML. * @param {String} result The new html to replace the existing content */ function M_updateWarningStatus(result) { var elem = document.getElementById("warnings"); elem.innerHTML = result; if (hookState) hookState.updateHooks(); } /* Ripped off from Caribou */ var M_CONFIRM_DISCARD_NEW_MSG = "Your draft comment has not been saved " + "or sent.\n\nDiscard your comment?"; var M_useCarefulUnload = true; /** * Return an alert if the specified textarea is visible and non-empty. */ function M_carefulUnload(text_area_id) { return function () { var text_area = document.getElementById(text_area_id); if (!text_area) return; var text_parent = M_getParent(text_area); if (M_useCarefulUnload && text_area.style.display != "none" && text_parent.style.display != "none" && goog.string.trim(text_area.value)) { return M_CONFIRM_DISCARD_NEW_MSG; } }; } function M_disableCarefulUnload() { M_useCarefulUnload = false; } // History Table /** * Toggles visibility of the snapshots that belong to the given parent. * @param {String} parent The parent's index * @param {Boolean} opt_show If present, whether to show or hide the group */ function M_toggleGroup(parent, opt_show) { var children = M_historyChildren[parent]; if (children.length == 1) { // No children. return; } var show = (typeof opt_show != "undefined") ? opt_show : (document.getElementById("history-" + children[1]).style.display != ""); for (var i = 1; i < children.length; i++) { var child = document.getElementById("history-" + children[i]); child.style.display = show ? "" : "none"; } var arrow = document.getElementById("triangle-" + parent); if (arrow) { arrow.className = "triangle-" + (show ? "open" : "closed"); } } /** * Makes the given groups visible. * @param {Array.<Number>} parents The indexes of the parents of the groups * to show. */ function M_expandGroups(parents) { for (var i = 0; i < parents.length; i++) { M_toggleGroup(parents[i], true); } document.getElementById("history-expander").style.display = "none"; document.getElementById("history-collapser").style.display = ""; } /** * Hides the given parents, except for groups that contain the * selected radio buttons. * @param {Array.<Number>} parents The indexes of the parents of the groups * to hide. */ function M_collapseGroups(parents) { // Find the selected snapshots var parentsToLeaveOpen = {}; var form = document.getElementById("history-form"); var formLength = form.a.length; for (var i = 0; i < formLength; i++) { if (form.a[i].checked || form.b[i].checked) { var element = "history-" + form.a[i].value; var name = document.getElementById(element).getAttribute("name"); if (name != "parent") { // The name of a child is "parent-%d" % parent_index. var parentIndex = Number(name.match(/parent-(\d+)/)[1]); parentsToLeaveOpen[parentIndex] = true; } } } // Collapse the parents we need to collapse. for (var i = 0; i < parents.length; i++) { if (!(parents[i] in parentsToLeaveOpen)) { M_toggleGroup(parents[i], false); } } document.getElementById("history-expander").style.display = ""; document.getElementById("history-collapser").style.display = "none"; } /** * Expands the reverted files section of the files list in the changelist view. * * @param {String} tableid The id of the table element that contains hidden TR's * @param {String} hide The id of the element to hide after this is completed. */ function M_showRevertedFiles(tableid, hide) { var table = document.getElementById(tableid); if (!table) return; var rowsLength = table.rows.length; for (var i = 0; i < rowsLength; i++) { var row = table.rows[i]; if (row.getAttribute("name") == "afile") row.style.display = ""; } if (dashboardState) dashboardState.initialize(); var h = document.getElementById(hide); if (h) h.style.display = "none"; } // Undo draft cancel /** * An associative array mapping keys that identify inline comments to draft * text values. * New inline comments have keys 'new-lineno-snapshot_id' * Edit inline comments have keys 'edit-cid-lineno-side' * Reply inline comments have keys 'reply-cid-lineno-side' * @type Object */ var M_savedInlineDrafts = new Object(); /** * Saves draft text from a form. * @param {String} draftKey The key identifying the saved draft text * @param {String} text The draft text to be saved */ function M_saveDraftText_(draftKey, text) { M_savedInlineDrafts[draftKey] = text; } /** * Clears saved draft text. Does nothing with an invalid key. * @param {String} draftKey The key identifying the saved draft text */ function M_clearDraftText_(draftKey) { delete M_savedInlineDrafts[draftKey]; } /** * Restores saved draft text to a form. Does nothing with an invalid key. * @param {String} draftKey The key identifying the saved draft text * @param {Element} form The form that contains the comment to be restored * @param {Element} opt_selectAll Whether the restored text should be selected. * True by default. * @return {Boolean} true if we found a saved draft and false otherwise */ function M_restoreDraftText_(draftKey, form, opt_selectAll) { if (M_savedInlineDrafts[draftKey]) { form.text.value = M_savedInlineDrafts[draftKey]; if (typeof opt_selectAll == 'undefined' || opt_selectAll) { form.text.select(); } return true; } return false; } // Dashboard CL navigation /** * M_DashboardState class. Keeps track of the current position of * the selector on the dashboard, and moves it on keydown. * @param {Window} win The window that the dashboard table is in. * @param {String} trName The name of TRs that we will move between. * @param {String} cookieName The cookie name to store the marker position into. * @constructor */ function M_DashboardState(win, trName, cookieName) { /** * The position of the marker, 0-indexed into the trCache array. * @ype Integer */ this.trPos = 0; /** * The current TR object that the marker is pointing at. * @type Element */ this.curTR = null; /** * Array of tr rows that we are moving between. Computed once (updateable). * @type Array */ this.trCache = []; /** * The window that the table is in, used for positioning information. * @type Window */ this.win = win; /** * The expected name of tr's that we are going to cache. * @type String */ this.trName = trName; /** * The name of the cookie value where the marker position is stored. * @type String */ this.cookieName = cookieName; this.initialize(); } /** * Initializes the clCache array, and moves the marker into the first position. */ M_DashboardState.prototype.initialize = function() { var filter = function(arr, lambda) { var ret = []; var arrLength = arr.length; for (var i = 0; i < arrLength; i++) { if (lambda(arr[i])) { ret.push(arr[i]); } } return ret; }; var cache; if (M_isIE()) { // IE does not recognize the 'name' attribute on TR tags cache = filter(document.getElementsByTagName("TR"), function (elem) { return elem.name == this.trName; }); } else { cache = document.getElementsByName(this.trName); } this.trCache = filter(cache, function (elem) { return elem.style.display != "none"; }); if (document.cookie && this.cookieName) { cookie_values = document.cookie.split(";"); for (var i=0; i<cookie_values.length; i++) { name = cookie_values[i].split("=")[0].replace(/ /g, ''); if (name == this.cookieName) { pos = cookie_values[i].split("=")[1]; /* Make sure that the saved position is valid. */ if (pos > this.trCache.length-1) { pos = 0; } this.trPos = pos; } } } this.goto_(0); } /** * Moves the cursor to the curCL position, and potentially scrolls the page to * bring the cursor into view. * @param {Integer} direction Positive for scrolling down, negative for * scrolling up, and 0 for no scrolling. */ M_DashboardState.prototype.goto_ = function(direction) { var oldTR = this.curTR; if (oldTR) { oldTR.cells[0].firstChild.style.visibility = "hidden"; } this.curTR = this.trCache[this.trPos]; this.curTR.cells[0].firstChild.style.visibility = ""; if (this.cookieName) { document.cookie = this.cookieName+'='+this.trPos; } if (!M_isElementVisible(this.win, this.curTR)) { M_scrollIntoView(this.win, this.curTR, direction); } } /** * Moves the cursor up one. */ M_DashboardState.prototype.gotoPrev = function() { if (this.trPos > 0) this.trPos--; this.goto_(-1); } /** * Moves the cursor down one. */ M_DashboardState.prototype.gotoNext = function() { if (this.trPos < this.trCache.length - 1) this.trPos++; this.goto_(1); } /** * Event handler for dashboard hot keys. Dispatches cursor moves, as well as * opening CLs. */ function M_dashboardKeyDown(evt) { return M_keyDownCommon(evt, function(key) { if (key == 'K') { if (dashboardState) dashboardState.gotoPrev(); } else if (key == 'J') { if (dashboardState) dashboardState.gotoNext(); } else if (key == 'Shift-3' /* '#' */) { if (dashboardState) { var child = dashboardState.curTR.cells[1].firstChild; while (child && child.className != "issue-close") { child = child.nextSibling; } if (child) { child = child.firstChild; } while (child && child.nodeName != "A") { child = child.nextSibling; } if (child) { location.href = child.href; } } } else if (key == 'O' || key == 'Enter') { if (dashboardState) { var child = dashboardState.curTR.cells[2].firstChild; while (child && child.nodeName != "A") { child = child.firstChild; } if (child) { location.href = child.href; } } } else { return true; } return false; }); } /** * Helper to fill a table cell element. * @param {Array} attrs An array of attributes to be applied * @param {String} text The content of the table cell * @return {Element} */ function M_fillTableCell_(attrs, text) { var td = document.createElement("td"); for (var j=0; j<attrs.length; j++) { if (attrs[j][0] == "class" && M_isIE()) { td.setAttribute("className", attrs[j][1]); } else { td.setAttribute(attrs[j][0], attrs[j][1]); } } if (!text) text = ""; if (M_isIE()) { td.innerText = text; } else { td.textContent = text; } return td; } /* * Function to request more context between diff chunks. * See _ShortenBuffer() in codereview/engine.py. */ function M_expandSkipped(id_before, id_after, where, id_skip) { links = document.getElementById('skiplinks-'+id_skip).getElementsByTagName('a'); for (var i=0; i<links.length; i++) { links[i].href = '#skiplinks-'+id_skip; } tr = document.getElementById('skip-'+id_skip); var httpreq = M_getXMLHttpRequest(); if (!httpreq) { html = '<td colspan="2" style="text-align: center;">'; html = html + 'Failed to retrieve additional lines. '; html = html + 'Please update your context settings.'; html = html + '</td>'; tr.innerHTML = html; } document.getElementById('skiploading-'+id_skip).style.visibility = 'visible'; var context_select = document.getElementById('id_context'); var context = null; if (context_select) { context = context_select.value; } aborted = false; httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && !aborted) { if (httpreq.status == 200) { response = eval('('+httpreq.responseText+')'); var last_row = null; for (var i=0; i<response.length; i++) { var data = response[i]; var row = document.createElement("tr"); for (var j=0; j<data[0].length; j++) { if (data[0][j][0] == "class" && M_isIE()) { row.setAttribute("className", data[0][j][1]); } else { row.setAttribute(data[0][j][0], data[0][j][1]); } } if ( where == 't' || where == 'a') { tr.parentNode.insertBefore(row, tr); } else { if (last_row) { tr.parentNode.insertBefore(row, last_row.nextSibling); } else { tr.parentNode.insertBefore(row, tr.nextSibling); } } var left = M_fillTableCell_(data[1][0][0], data[1][0][1]); var right = M_fillTableCell_(data[1][1][0], data[1][1][1]); row.appendChild(left); row.appendChild(right); last_row = row; } var curr = document.getElementById('skipcount-'+id_skip); var new_count = parseInt(curr.innerHTML)-response.length/2; if ( new_count > 0 ) { if ( where == 'b' ) { var new_before = id_before; var new_after = id_after-response.length/2; } else { var new_before = id_before+response.length/2; var new_after = id_after; } curr.innerHTML = new_count; html = ''; if ( new_count > 3*context ) { html += '<a href="javascript:M_expandSkipped('+new_before; html += ','+new_after+',\'t\', '+id_skip+');">'; html += 'Expand '+context+' before'; html += '</a> | '; } html += '<a href="javascript:M_expandSkipped('+new_before; html += ','+new_after+',\'a\','+id_skip+');">Expand all</a>'; if ( new_count > 3*context ) { var val = parseInt(new_after); html += ' | <a href="javascript:M_expandSkipped('+new_before; html += ','+val+',\'b\','+id_skip+');">'; html += 'Expand '+context+' after'; html += '</a>'; } document.getElementById('skiplinks-'+(id_skip)).innerHTML = html; var loading_node = document.getElementById('skiploading-'+id_skip); loading_node.style.visibility = 'hidden'; } else { tr.parentNode.removeChild(tr); } hookState.updateHooks(); if (hookState.hookPos != -2 && M_isElementVisible(window, hookState.indicator)) { // Restore indicator position on screen, but only if the indicator // is visible. We don't know if we have to scroll up or down to // make the indicator visible. Therefore the current hook is // internally set to the previous hook and // then gotoNextHook() does everything needed to end up with a // clean hookState and the indicator visible on screen. hookState.hookPos = hookState.hookPos - 1; hookState.gotoNextHook(); } } else { msg = '<td colspan="2" align="center"><span style="color:red;">'; msg += 'An error occurred ['+httpreq.status+']. '; msg += 'Please report.'; msg += '</span></td>'; tr.innerHTML = msg; } } } colwidth = document.getElementById('id_column_width').value; url = skipped_lines_url+id_before+'/'+id_after+'/'+where+'/'+colwidth; if (context) { url += '?context='+context; } httpreq.open('GET', url, true); httpreq.send(''); } /** * Finds the element position. */ function M_getElementPosition(obj) { var curleft = curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft,curtop]; } /** * Position the user info popup according to the mouse event coordinates */ function M_positionUserInfoPopup(obj, userPopupDiv) { pos = M_getElementPosition(obj); userPopupDiv.style.left = pos[0] + "px"; userPopupDiv.style.top = pos[1] + 20 + "px"; } /** * Brings up user info popup using ajax */ function M_showUserInfoPopup(obj) { var DIV_ID = "userPopupDiv"; var userPopupDiv = document.getElementById(DIV_ID); var url = obj.getAttribute("href") var index = url.indexOf("/user/"); var user_key = url.substring(index + 6); if (!userPopupDiv) { var userPopupDiv = document.createElement("div"); userPopupDiv.className = "popup"; userPopupDiv.id = DIV_ID; userPopupDiv.filter = 'alpha(opacity=85)'; userPopupDiv.opacity = '0.85'; userPopupDiv.innerHTML = ""; userPopupDiv.onmouseout = function() { userPopupDiv.style.visibility = 'hidden'; } document.body.appendChild(userPopupDiv); } M_positionUserInfoPopup(obj, userPopupDiv); var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } var aborted = false; var httpreq_timeout = setTimeout(function() { aborted = true; httpreq.abort(); }, 5000); httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && !aborted) { clearTimeout(httpreq_timeout); if (httpreq.status == 200) { userPopupDiv = document.getElementById(DIV_ID); userPopupDiv.innerHTML=httpreq.responseText; userPopupDiv.style.visibility = "visible"; } else { //Better fail silently here because it's not //critical functionality } } } httpreq.open("GET", base_url + "user_popup/" + user_key, true); httpreq.send(null); obj.onmouseout = function() { aborted = true; userPopupDiv.style.visibility = 'hidden'; obj.onmouseout = null; } } /** * TODO(jiayao,andi): docstring */ function M_showPopUp(obj, id) { var popup = document.getElementById(id); var pos = M_getElementPosition(obj); popup.style.left = pos[0]+'px'; popup.style.top = pos[1]+20+'px'; popup.style.visibility = 'visible'; obj.onmouseout = function() { popup.style.visibility = 'hidden'; obj.onmouseout = null; } } /** * Jump to a patch in the changelist. * @param {Element} select The select form element. * @param {Integer} issue The issue id. * @param {Integer} patchset The patchset id. * @param {Boolean} unified If True show unified diff else s-b-s view. * @param {String} opt_part The type of diff to jump to -- diff/diff2/patch */ function M_jumpToPatch(select, issue, patchset, unified, opt_part) { var part = opt_part; if (!part) { if (unified) { part = 'patch'; } else { part = 'diff'; } } var url = base_url+issue+'/'+part+'/'+patchset+'/'+select.value; var context = document.getElementById('id_context'); var colwidth = document.getElementById('id_column_width'); if (context && colwidth) { url = url+'?context='+context.value+'&column_width='+colwidth.value; } document.location.href = url; } /** * Add or remove a star to/from the given issue. * @param {Integer} id The issue id. * @param {String} url The url fragment to append: "/star" or "/unstar". */ function M_setIssueStar_(id, url) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4) { if (httpreq.status == 200) { var elem = document.getElementById("issue-star-" + id); elem.innerHTML = httpreq.responseText; } } } httpreq.open("POST", base_url + id + url, true); httpreq.send("xsrf_token=" + xsrfToken); } /** * Add a star to the given issue. * @param {Integer} id The issue id. */ function M_addIssueStar(id) { return M_setIssueStar_(id, "/star"); } /** * Remove the star from the given issue. * @param {Integer} id The issue id. */ function M_removeIssueStar(id) { return M_setIssueStar_(id, "/unstar"); } /** * Close a given issue. * @param {Integer} id The issue id. */ function M_closeIssue(id) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4) { if (httpreq.status == 200) { var elem = document.getElementById("issue-close-" + id); elem.innerHTML = ''; var elem = document.getElementById("issue-title-" + id); elem.innerHTML += ' (' + httpreq.responseText + ')'; } } } httpreq.open("POST", base_url + id + "/close", true); httpreq.send("xsrf_token=" + xsrfToken); } /** * Generic callback when page is unloaded. */ function M_unloadPage() { if (draftMessage) { draftMessage.save(); } } /** * Draft message dialog class. * @param {Integer} issue_id ID of current issue. * @param {Boolean} headless If true, the dialog is not initialized (default: false). */ var draftMessage = null; function M_draftMessage(issue_id, headless) { this.issue_id = issue_id; this.id_dlg_container = 'reviewmsgdlg'; this.id_textarea = 'reviewmsg'; this.id_hidden = 'reviewmsgorig'; this.id_status = 'reviewmsgstatus'; this.is_modified = false; if (! headless) { this.initialize(); } } /** * Constructor. * Sets keydown callback and loads draft message if any. */ M_draftMessage.prototype.initialize = function() { this.load(); } /** * Shows the dialog and focusses on textarea. */ M_draftMessage.prototype.dialog_show = function() { dlg = this.get_dialog_(); dlg.style.display = ""; this.set_status(''); textarea = document.getElementById(this.id_textarea); textarea.focus(); } /** * Hides the dialog and optionally saves the current content. * @param {Boolean} save If true, the content is saved. */ M_draftMessage.prototype.dialog_hide = function(save) { if (save) { this.save(); } dlg = this.get_dialog_(); dlg.style.display = "none"; } /** * Discards draft message. */ M_draftMessage.prototype.dialog_discard = function() { this.discard(function(response) { draftMessage.set_status('OK'); textarea = document.getElementById(draftMessage.id_textarea); textarea.value = ''; }); return false; } /** * Saves the content without closing the dialog. */ M_draftMessage.prototype.dialog_save = function() { this.set_status(''); textarea = document.getElementById(this.id_textarea); this.save(function(response) { if (response.status != 200) { draftMessage.set_status('An error occurred.'); } else { draftMessage.set_status('Message saved.'); } textarea.focus(); return false; }); return false; } /** * Sets a status message in the dialog. * Additionally a timeout function is created to hide the message again. * @param {String} msg The message to display. */ M_draftMessage.prototype.set_status = function(msg) { var statusSpan = document.getElementById(this.id_status); if (statusSpan) { statusSpan.innerHTML = msg; if (msg) { this.status_timeout = setTimeout(function() { draftMessage.set_status(''); }, 3000); } } } /** * Saves the content of the draft message. * @param {Function} cb A function called with the response object. */ M_draftMessage.prototype.save = function(cb) { textarea = document.getElementById(this.id_textarea); hidden = document.getElementById(this.id_hidden); if (textarea == null || textarea.value == hidden.value || textarea.value == "") { return; } text = textarea.value; var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && cb) { /* XXX set hidden before cb */ hidden = document.getElementById(draftMessage.id_hidden); hidden.value = text; cb(httpreq); } } httpreq.open("POST", base_url + this.issue_id + "/draft_message", true); httpreq.send("reviewmsg="+encodeURIComponent(text)); } /** * Loads the content of the draft message from the datastore. */ M_draftMessage.prototype.load = function() { elem = document.getElementById(this.id_textarea); elem.disabled = "disabled"; this.set_status("Loading..."); if (elem) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4) { if (httpreq.status != 200) { draftMessage.set_status('An error occurred.'); } else { if (elem) { elem.value = httpreq.responseText; hidden = document.getElementById(draftMessage.id_hidden); hidden.value = elem.value; } } elem.removeAttribute("disabled"); draftMessage.set_status(''); elem.focus(); } } httpreq.open("GET", base_url + this.issue_id + "/draft_message", true); httpreq.send(""); } } /** * Discards the draft message. * @param {Function} cb A function called with response object. */ M_draftMessage.prototype.discard = function(cb) { var httpreq = M_getXMLHttpRequest(); if (!httpreq) { return true; } httpreq.onreadystatechange = function () { if (httpreq.readyState == 4 && cb) { elem = document.getElementById(this.id_textarea); if (elem) { elem.value = ""; hidden = document.getElementById(this.id_hidden); hidden.value = elem.value; } cb(httpreq); } } httpreq.open("DELETE", base_url + this.issue_id + "/draft_message", true); httpreq.send(""); } /** * Helper function that returns the dialog's HTML container. */ M_draftMessage.prototype.get_dialog_ = function() { return document.getElementById(this.id_dlg_container); }
JavaScript
/* * Autocomplete - jQuery plugin 1.0.2 * * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $ * */ ;(function($) { $.fn.extend({ autocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); // if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; }; // if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem; return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } }); $.Autocompleter = function(input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; // Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) { case KEY.UP: event.preventDefault(); if ( select.visible() ) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if ( select.visible() ) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if ( select.visible() ) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if ( select.visible() ) { select.pageDown(); } else { onChange(0, true); } break; // matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if( selectCurrent() ) { // stop default to prevent a form submit, Opera needs special handling event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) { for (var i=0; i < data.length; i++) { if( data[i].result.toLowerCase() == q.toLowerCase() ) { result = data[i]; break; } } } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if( !selected ) return false; var v = selected.result; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v; } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; } var currentValue = $input.val(); if ( !skipPrevCheck && currentValue == previousValue ) return; previousValue = currentValue; currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if ( !value ) { return [""]; } var words = value.split( options.multipleSeparator ); var result = []; $.each(words, function(i, value) { if ( $.trim(value) ) result[i] = $.trim(value); }); return result; } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search( function (result){ // if no value found, clear the input box if( !result ) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); } else $input.val( "" ); } } ); } if (wasVisible) // position cursor at end of input field $.Autocompleter.Selection(input, input.value.length, input.value.length); }; function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){ var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function(key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function(data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function(options) { var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0; // no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1; // track all options for minChars = 0 stMatchSets[""] = []; // loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false ) continue; var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] ) stMatchSets[firstChar] = []; // if the match is a string var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; // push the current match into the set list stMatchSets[firstChar].push(row); // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets[""].push(row); } }; // add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length) return null; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if( !options.url && options.matchContains ){ // track all matches var csub = []; // loop through all the data grids for matches for( var k in data ){ // don't search through the stMatchSets[""] (minChars: 0) cache // this prevents duplicates if( k.length > 0 ){ var c = data[k]; $.each(c, function(i, x) { // if we've got a match, add it to the array if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else // if the exact item exists, use it if (data[q]){ return data[q]; } else if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function(i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null; } }; }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; }); if( options.width > 0 ) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if(options.scroll) { var offset = 0; listItems.slice(0, active).each(function() { offset += this.offsetHeight; }); if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if(offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false ) continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) { moveSelect( -active ); } else { moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect( listItems.size() - 1 - active ); } else { moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if(options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function() { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); if (!scrollbarsVisible) { // IE doesn't recalculate width when scrollbar disappears listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); } } } }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; }; $.Autocompleter.Selection = function(field, start, end) { if( field.createTextRange ){ var selRange = field.createTextRange(); selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } else if( field.setSelectionRange ){ field.setSelectionRange(start, end); } else { if( field.selectionStart ){ field.selectionStart = start; field.selectionEnd = end; } } field.focus(); }; })(jQuery);
JavaScript
/** * Ajax Queue Plugin * * Homepage: http://jquery.com/plugins/project/ajaxqueue * Documentation: http://docs.jquery.com/AjaxQueue */ /** <script> $(function(){ jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); }); </script> <ul style="position: absolute; top: 5px; right: 5px;"></ul> */ /* * Queued Ajax requests. * A new Ajax request won't be started until the previous queued * request has finished. */ /* * Synced Ajax requests. * The Ajax request will happen as soon as you call this method, but * the callbacks (success/error/complete) won't fire until all previous * synced requests have been completed. */ (function($) { var ajax = $.ajax; var pendingRequests = {}; var synced = []; var syncedData = []; $.ajax = function(settings) { // create settings for compatibility with ajaxSetup settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings)); var port = settings.port; switch(settings.mode) { case "abort": if ( pendingRequests[port] ) { pendingRequests[port].abort(); } return pendingRequests[port] = ajax.apply(this, arguments); case "queue": var _old = settings.complete; settings.complete = function(){ if ( _old ) _old.apply( this, arguments ); jQuery([ajax]).dequeue("ajax" + port );; }; jQuery([ ajax ]).queue("ajax" + port, function(){ ajax( settings ); }); return; case "sync": var pos = synced.length; synced[ pos ] = { error: settings.error, success: settings.success, complete: settings.complete, done: false }; syncedData[ pos ] = { error: [], success: [], complete: [] }; settings.error = function(){ syncedData[ pos ].error = arguments; }; settings.success = function(){ syncedData[ pos ].success = arguments; }; settings.complete = function(){ syncedData[ pos ].complete = arguments; synced[ pos ].done = true; if ( pos == 0 || !synced[ pos-1 ] ) for ( var i = pos; i < synced.length && synced[i].done; i++ ) { if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error ); if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success ); if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete ); synced[i] = null; syncedData[i] = null; } }; } return ajax.apply(this, arguments); }; })(jQuery);
JavaScript
/*---------------------------------------------------\ | Table Sorter | |----------------------------------------------------| | Author: Vinay Srinivasaiah (vsrini@spikesource.com)| | SpikeSource (http://www.spikesource.com) | | - DOM 1 based script that makes the table sortable.| | - Copyright (c) 2004 SpikeSource Inc. | |---------------------------------------------------*/ //http://www.w3.org/TR/REC-DOM-Level-1/java-language-binding.html var tableBody; var table2sort; var imgUp; var imgDown; function TableSorter(table) { this.table2sort = table; this.tableBody = this.table2sort.getElementsByTagName("tbody")[0]; this.imgUp = document.createElement("img"); this.imgUp.src = "images/arrow_up.gif"; this.imgDown = document.createElement("img"); this.imgDown.src = "images/arrow_down.gif"; } var lastSortCol = -1; var lastSortOrderAsc = true; var origChildRows; function createImgLink(row, imageSrc) { var cell = row.cells[0]; var id = _getInnerText(cell) + "_" + imageSrc; imgExpand = document.createElement("img"); imgExpand.src = "images" + imageSrc + ".gif"; imgExpand.border="0"; imgBlank = document.createElement("img"); imgBlank.src = "results/images/transdot.gif"; imgBlank.border="0"; imgBlank2 = imgBlank.cloneNode(false); imgBlank3 = imgBlank.cloneNode(false); anchorTag = document.createElement("a"); anchorTag.href="javascript:toggleShowChildren('" + id + "');" anchorTag.appendChild(imgExpand); anchorTag.appendChild(imgBlank); anchorTag.appendChild(imgBlank2); anchorTag.appendChild(imgBlank3); anchorTag.id = id; cell.id = id + "_cell"; row.id = id + "_row"; cell.insertBefore(anchorTag, cell.firstChild); } TableSorter.prototype.initTable = function () { this.populateChildRowsMap(); for (i = 0; i < origChildRows.length; i++) { if (origChildRows[i].id != "indented_row") { createImgLink(origChildRows[i], "minus"); } } } TableSorter.prototype.collapseAllChildren = function () { for (i = 0; i < origChildRows.length; i++) { if (origChildRows[i].id != "indented_row") { id = _getInnerText(origChildRows[i].cells[0]) + "_" + "minus"; var anchorTag = document.getElementById(id); if (anchorTag != null) { this.togglechildren(id); } } } } TableSorter.prototype.expandAllChildren = function () { for (i = 0; i < origChildRows.length; i++) { if (origChildRows[i].id != "indented_row") { id = _getInnerText(origChildRows[i].cells[0]) + "_" + "plus"; var anchorTag = document.getElementById(id); if (anchorTag != null) { this.togglechildren(id); } } } } TableSorter.prototype.togglechildren = function (id) { anchorTag = document.getElementById(id); anchorParent = document.getElementById((id + "_cell")); anchorParent.removeChild(anchorTag); row = document.getElementById((id + "_row")); nextRow = row.nextSibling; var addChildren = false; if (anchorTag.firstChild.src.indexOf("plus") != -1) { addChildren = true; createImgLink(row, "minus"); } else if (anchorTag.firstChild.src.indexOf("minus") != -1) { addChildren = false; createImgLink(row, "plus"); } for (i = 0; i < origChildRows.length; i++) { //alert("comparing " + _getInnerText(origChildRows[i].cells[0]) // + " and " + _getInnerText(row.cells[0])); if (_getInnerText(origChildRows[i].cells[0]) == _getInnerText(row.cells[0])) { for (j = i + 1; j < origChildRows.length; j++) { if (origChildRows[j].id == "indented_row") { if (addChildren) { this.tableBody.insertBefore(origChildRows[j], nextRow); } else { this.tableBody.removeChild(origChildRows[j]); } } else { // done; break; } } break; } } } TableSorter.prototype.populateChildRowsMap = function () { var rows = this.tableBody.rows; origChildRows = new Array(); var count = 0; var newRowsCount = 0; for (i = 0; i < rows.length; i ++) { if (rows[i].id == "indented_row") { if (parentRow != null) { origChildRows[count++] = parentRow; parentRow = null; } origChildRows[count++] = rows[i]; } else { parentRow = rows[i]; } } } TableSorter.prototype.sort = function (col, type) { if (lastSortCol != -1) { sortCell = document.getElementById("sortCell" + lastSortCol); if (sortCell != null) { if (lastSortOrderAsc == true) { sortCell.removeChild(this.imgUp); } else { sortCell.removeChild(this.imgDown); } } sortLink = document.getElementById("sortCellLink" + lastSortCol); if(sortLink != null) { sortLink.title = "Sort Ascending"; } } if (lastSortCol == col) { lastSortOrderAsc = !lastSortOrderAsc; } else { lastSortCol = col; lastSortOrderAsc = true; } var rows = this.tableBody.rows; var newRows = new Array(); var parentRow; var childRows = new Array(); var count = 0; var newRowsCount = 0; for (i = 0; i < rows.length; i ++) { if (rows[i].id == "indented_row") { if (parentRow != null) { childRows[count++] = parentRow; parentRow = null; } childRows[count++] = rows[i]; } else { newRows[newRowsCount++] = rows[i]; parentRow = rows[i]; } } // default sortFunction = sort_caseInsensitive; if (type == "string") sortFunction = sort_caseSensitive; if (type == "percentage") sortFunction = sort_numericPercentage; if (type == "number") sortFunction = sort_numeric; newRows.sort(sortFunction); if (lastSortOrderAsc == false) { newRows.reverse(); } for (i = 0; i < newRows.length; i ++) { this.table2sort.tBodies[0].appendChild(newRows[i]); var parentRowText = _getInnerText(newRows[i].cells[0]); var match = -1; for (j = 0; j < childRows.length; j++) { var childRowText = _getInnerText(childRows[j].cells[0]); if (childRowText == parentRowText) { match = j; break; } } if (match != -1) { for (j = match + 1; j < childRows.length; j++) { if (childRows[j].id == "indented_row") { this.table2sort.tBodies[0].appendChild(childRows[j]); } else { break; } } } } sortCell = document.getElementById("sortCell" + col); if (sortCell == null) { } else { if (lastSortOrderAsc == true) { sortCell.appendChild(this.imgUp); } else { sortCell.appendChild(this.imgDown); } } sortLink = document.getElementById("sortCellLink" + col); if (sortLink == null) { } else { if (lastSortOrderAsc == true) { sortLink.title = "Sort Descending"; } else { sortLink.title = "Sort Ascending"; } } } function sort_caseSensitive(a, b) { aa = _getInnerText(a.cells[lastSortCol]); bb = _getInnerText(b.cells[lastSortCol]); return compareString(aa, bb); } function sort_caseInsensitive(a,b) { aa = _getInnerText(a.cells[lastSortCol]).toLowerCase(); bb = _getInnerText(b.cells[lastSortCol]).toLowerCase(); return compareString(aa, bb); } function sort_numeric(a,b) { aa = _getInnerText(a.cells[lastSortCol]); bb = _getInnerText(b.cells[lastSortCol]); return compareNumber(aa, bb); } function sort_numericPercentage(a,b) { aa = _getInnerText(a.cells[lastSortCol]); bb = _getInnerText(b.cells[lastSortCol]); var aaindex = aa.indexOf("%"); var bbindex = bb.indexOf("%"); if (aaindex != -1 && bbindex != -1) { aa = aa.substring(0, aaindex); bb = bb.substring(0, bbindex); return compareNumber(aa, bb); } return compareString(aa, bb); } function compareString(a, b) { if (a == b) return 0; if (a < b) return -1; return 1; } function compareNumber(a, b) { aa = parseFloat(a); if (isNaN(aa)) aa = 0; bb = parseFloat(b); if (isNaN(bb)) bb = 0; return aa-bb; } function _getInnerText(el) { if (typeof el == "string") return el; if (typeof el == "undefined") { return el }; if (el.innerText) return el.innerText; var str = ""; var cs = el.childNodes; var l = cs.length; for (var i = 0; i < l; i++) { switch (cs[i].nodeType) { case 1: //ELEMENT_NODE str += _getInnerText(cs[i]); break; case 3: //TEXT_NODE str += cs[i].nodeValue; break; } } return str; }
JavaScript
/*---------------------------------------------------\ | Table Sorter | |----------------------------------------------------| | Author: Vinay Srinivasaiah (vsrini@spikesource.com)| | SpikeSource (http://www.spikesource.com) | | - DOM 1 based script that makes the table sortable.| | - Copyright (c) 2004 SpikeSource Inc. | |---------------------------------------------------*/ //http://www.w3.org/TR/REC-DOM-Level-1/java-language-binding.html var tableBody; var table2sort; var imgUp; var imgDown; function TableSorter(table) { this.table2sort = table; this.tableBody = this.table2sort.getElementsByTagName("tbody")[0]; this.imgUp = document.createElement("img"); this.imgUp.src = "images/arrow_up.gif"; this.imgDown = document.createElement("img"); this.imgDown.src = "images/arrow_down.gif"; } var lastSortCol = -1; var lastSortOrderAsc = true; var origChildRows; function createImgLink(row, imageSrc) { var cell = row.cells[0]; var id = _getInnerText(cell) + "_" + imageSrc; imgExpand = document.createElement("img"); imgExpand.src = "images" + imageSrc + ".gif"; imgExpand.border="0"; imgBlank = document.createElement("img"); imgBlank.src = "results/images/transdot.gif"; imgBlank.border="0"; imgBlank2 = imgBlank.cloneNode(false); imgBlank3 = imgBlank.cloneNode(false); anchorTag = document.createElement("a"); anchorTag.href="javascript:toggleShowChildren('" + id + "');" anchorTag.appendChild(imgExpand); anchorTag.appendChild(imgBlank); anchorTag.appendChild(imgBlank2); anchorTag.appendChild(imgBlank3); anchorTag.id = id; cell.id = id + "_cell"; row.id = id + "_row"; cell.insertBefore(anchorTag, cell.firstChild); } TableSorter.prototype.initTable = function () { this.populateChildRowsMap(); for (i = 0; i < origChildRows.length; i++) { if (origChildRows[i].id != "indented_row") { createImgLink(origChildRows[i], "minus"); } } } TableSorter.prototype.collapseAllChildren = function () { for (i = 0; i < origChildRows.length; i++) { if (origChildRows[i].id != "indented_row") { id = _getInnerText(origChildRows[i].cells[0]) + "_" + "minus"; var anchorTag = document.getElementById(id); if (anchorTag != null) { this.togglechildren(id); } } } } TableSorter.prototype.expandAllChildren = function () { for (i = 0; i < origChildRows.length; i++) { if (origChildRows[i].id != "indented_row") { id = _getInnerText(origChildRows[i].cells[0]) + "_" + "plus"; var anchorTag = document.getElementById(id); if (anchorTag != null) { this.togglechildren(id); } } } } TableSorter.prototype.togglechildren = function (id) { anchorTag = document.getElementById(id); anchorParent = document.getElementById((id + "_cell")); anchorParent.removeChild(anchorTag); row = document.getElementById((id + "_row")); nextRow = row.nextSibling; var addChildren = false; if (anchorTag.firstChild.src.indexOf("plus") != -1) { addChildren = true; createImgLink(row, "minus"); } else if (anchorTag.firstChild.src.indexOf("minus") != -1) { addChildren = false; createImgLink(row, "plus"); } for (i = 0; i < origChildRows.length; i++) { //alert("comparing " + _getInnerText(origChildRows[i].cells[0]) // + " and " + _getInnerText(row.cells[0])); if (_getInnerText(origChildRows[i].cells[0]) == _getInnerText(row.cells[0])) { for (j = i + 1; j < origChildRows.length; j++) { if (origChildRows[j].id == "indented_row") { if (addChildren) { this.tableBody.insertBefore(origChildRows[j], nextRow); } else { this.tableBody.removeChild(origChildRows[j]); } } else { // done; break; } } break; } } } TableSorter.prototype.populateChildRowsMap = function () { var rows = this.tableBody.rows; origChildRows = new Array(); var count = 0; var newRowsCount = 0; for (i = 0; i < rows.length; i ++) { if (rows[i].id == "indented_row") { if (parentRow != null) { origChildRows[count++] = parentRow; parentRow = null; } origChildRows[count++] = rows[i]; } else { parentRow = rows[i]; } } } TableSorter.prototype.sort = function (col, type) { if (lastSortCol != -1) { sortCell = document.getElementById("sortCell" + lastSortCol); if (sortCell != null) { if (lastSortOrderAsc == true) { sortCell.removeChild(this.imgUp); } else { sortCell.removeChild(this.imgDown); } } sortLink = document.getElementById("sortCellLink" + lastSortCol); if(sortLink != null) { sortLink.title = "Sort Ascending"; } } if (lastSortCol == col) { lastSortOrderAsc = !lastSortOrderAsc; } else { lastSortCol = col; lastSortOrderAsc = true; } var rows = this.tableBody.rows; var newRows = new Array(); var parentRow; var childRows = new Array(); var count = 0; var newRowsCount = 0; for (i = 0; i < rows.length; i ++) { if (rows[i].id == "indented_row") { if (parentRow != null) { childRows[count++] = parentRow; parentRow = null; } childRows[count++] = rows[i]; } else { newRows[newRowsCount++] = rows[i]; parentRow = rows[i]; } } // default sortFunction = sort_caseInsensitive; if (type == "string") sortFunction = sort_caseSensitive; if (type == "percentage") sortFunction = sort_numericPercentage; if (type == "number") sortFunction = sort_numeric; newRows.sort(sortFunction); if (lastSortOrderAsc == false) { newRows.reverse(); } for (i = 0; i < newRows.length; i ++) { this.table2sort.tBodies[0].appendChild(newRows[i]); var parentRowText = _getInnerText(newRows[i].cells[0]); var match = -1; for (j = 0; j < childRows.length; j++) { var childRowText = _getInnerText(childRows[j].cells[0]); if (childRowText == parentRowText) { match = j; break; } } if (match != -1) { for (j = match + 1; j < childRows.length; j++) { if (childRows[j].id == "indented_row") { this.table2sort.tBodies[0].appendChild(childRows[j]); } else { break; } } } } sortCell = document.getElementById("sortCell" + col); if (sortCell == null) { } else { if (lastSortOrderAsc == true) { sortCell.appendChild(this.imgUp); } else { sortCell.appendChild(this.imgDown); } } sortLink = document.getElementById("sortCellLink" + col); if (sortLink == null) { } else { if (lastSortOrderAsc == true) { sortLink.title = "Sort Descending"; } else { sortLink.title = "Sort Ascending"; } } } function sort_caseSensitive(a, b) { aa = _getInnerText(a.cells[lastSortCol]); bb = _getInnerText(b.cells[lastSortCol]); return compareString(aa, bb); } function sort_caseInsensitive(a,b) { aa = _getInnerText(a.cells[lastSortCol]).toLowerCase(); bb = _getInnerText(b.cells[lastSortCol]).toLowerCase(); return compareString(aa, bb); } function sort_numeric(a,b) { aa = _getInnerText(a.cells[lastSortCol]); bb = _getInnerText(b.cells[lastSortCol]); return compareNumber(aa, bb); } function sort_numericPercentage(a,b) { aa = _getInnerText(a.cells[lastSortCol]); bb = _getInnerText(b.cells[lastSortCol]); var aaindex = aa.indexOf("%"); var bbindex = bb.indexOf("%"); if (aaindex != -1 && bbindex != -1) { aa = aa.substring(0, aaindex); bb = bb.substring(0, bbindex); return compareNumber(aa, bb); } return compareString(aa, bb); } function compareString(a, b) { if (a == b) return 0; if (a < b) return -1; return 1; } function compareNumber(a, b) { aa = parseFloat(a); if (isNaN(aa)) aa = 0; bb = parseFloat(b); if (isNaN(bb)) bb = 0; return aa-bb; } function _getInnerText(el) { if (typeof el == "string") return el; if (typeof el == "undefined") { return el }; if (el.innerText) return el.innerText; var str = ""; var cs = el.childNodes; var l = cs.length; for (var i = 0; i < l; i++) { switch (cs[i].nodeType) { case 1: //ELEMENT_NODE str += _getInnerText(cs[i]); break; case 3: //TEXT_NODE str += cs[i].nodeValue; break; } } return str; }
JavaScript
// mredkj.com // created: 2001-07-11 // last updated: 2001-09-07 var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5); function addOption(theSel, theText, theValue) { var newOpt = new Option(theText, theValue); var selLength = theSel.length; theSel.options[selLength] = newOpt; } function deleteOption(theSel, theIndex) { var selLength = theSel.length; if(selLength>0) { theSel.options[theIndex] = null; } } function moveOptions(theSelFrom, theSelTo) { var selLength = theSelFrom.length; var selectedText = new Array(); var selectedValues = new Array(); var selectedCount = 0; var i; // Find the selected Options in reverse order // and delete them from the 'from' Select. for(i=selLength-1; i>=0; i--) { if(theSelFrom.options[i].selected) { selectedText[selectedCount] = theSelFrom.options[i].text; selectedValues[selectedCount] = theSelFrom.options[i].value; deleteOption(theSelFrom, i); selectedCount++; } } // Add the selected text/values in reverse order. // This will add the Options to the 'to' Select // in the same order as they were in the 'from' Select. for(i=selectedCount-1; i>=0; i--) { addOption(theSelTo, selectedText[i], selectedValues[i]); } if(NS4) history.go(0); }
JavaScript
function getXMLHttp() { var xmlHttp; try { //Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch(e) { //Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { alert("Your browser does not support AJAX!") return false; } } } return xmlHttp; } function HandleResponse(response) { if(document.getElementById('ajaxResponse') == null) alert(response); else document.getElementById('ajaxResponse').innerHTML = response; }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ if (typeof(RGraph) == 'undefined') RGraph = {}; /** * The bar chart constructor * * @param object canvas The canvas object * @param array data The chart data */ RGraph.Bar = function (id, data) { // Get the canvas and context objects this.id = id; this.canvas = document.getElementById(id); this.context = this.canvas.getContext ? this.canvas.getContext("2d") : null; this.canvas.__object__ = this; this.type = 'bar'; this.max = 0; this.stackedOrGrouped = false; this.isRGraph = true; /** * Compatibility with older browsers */ RGraph.OldBrowserCompat(this.context); // Various config type stuff this.properties = { 'chart.background.barcolor1': 'rgba(0,0,0,0)', 'chart.background.barcolor2': 'rgba(0,0,0,0)', 'chart.background.grid': true, 'chart.background.grid.color': '#ddd', 'chart.background.grid.width': 1, 'chart.background.grid.hsize': 20, 'chart.background.grid.vsize': 20, 'chart.background.grid.vlines': true, 'chart.background.grid.hlines': true, 'chart.background.grid.border': true, 'chart.background.grid.autofit':false, 'chart.background.grid.autofit.numhlines': 7, 'chart.background.grid.autofit.numvlines': 20, 'chart.ytickgap': 20, 'chart.smallyticks': 3, 'chart.largeyticks': 5, 'chart.numyticks': 10, 'chart.hmargin': 5, 'chart.strokecolor': '#666', 'chart.axis.color': 'black', 'chart.gutter': 25, 'chart.labels': null, 'chart.labels.ingraph': null, 'chart.labels.above': false, 'chart.labels.above.decimals': 0, 'chart.labels.above.size': null, 'chart.ylabels': true, 'chart.ylabels.count': 5, 'chart.ylabels.inside': false, 'chart.xlabels.offset': 0, 'chart.xaxispos': 'bottom', 'chart.yaxispos': 'left', 'chart.text.color': 'black', 'chart.text.size': 10, 'chart.text.angle': 0, 'chart.text.font': 'Verdana', 'chart.ymax': null, 'chart.title': '', 'chart.title.background': null, 'chart.title.hpos': null, 'chart.title.vpos': null, 'chart.title.xaxis': '', 'chart.title.yaxis': '', 'chart.title.xaxis.pos': 0.25, 'chart.title.yaxis.pos': 0.25, 'chart.colors': ['rgb(0,0,255)', '#0f0', '#00f', '#ff0', '#0ff', '#0f0'], 'chart.grouping': 'grouped', 'chart.variant': 'bar', 'chart.shadow': false, 'chart.shadow.color': '#666', 'chart.shadow.offsetx': 3, 'chart.shadow.offsety': 3, 'chart.shadow.blur': 3, 'chart.tooltips': null, 'chart.tooltips.effect': 'fade', 'chart.tooltips.css.class': 'RGraph_tooltip', 'chart.tooltips.event': 'onclick', 'chart.tooltips.coords.adjust': [0,0], 'chart.tooltips.highlight': true, 'chart.background.hbars': null, 'chart.key': [], 'chart.key.background': 'white', 'chart.key.position': 'graph', 'chart.key.shadow': false, 'chart.key.shadow.color': '#666', 'chart.key.shadow.blur': 3, 'chart.key.shadow.offsetx': 2, 'chart.key.shadow.offsety': 2, 'chart.key.position.gutter.boxed': true, 'chart.key.position.x': null, 'chart.key.position.y': null, 'chart.key.color.shape': 'square', 'chart.key.rounded': true, 'chart.key.text.size': 10, 'chart.contextmenu': null, 'chart.line': null, 'chart.units.pre': '', 'chart.units.post': '', 'chart.scale.decimals': 0, 'chart.scale.point': '.', 'chart.scale.thousand': ',', 'chart.crosshairs': false, 'chart.crosshairs.color': '#333', 'chart.linewidth': 1, 'chart.annotatable': false, 'chart.annotate.color': 'black', 'chart.zoom.factor': 1.5, 'chart.zoom.fade.in': true, 'chart.zoom.fade.out': true, 'chart.zoom.hdir': 'right', 'chart.zoom.vdir': 'down', 'chart.zoom.frames': 10, 'chart.zoom.delay': 50, 'chart.zoom.shadow': true, 'chart.zoom.mode': 'canvas', 'chart.zoom.thumbnail.width': 75, 'chart.zoom.thumbnail.height': 75, 'chart.zoom.background': true, 'chart.resizable': false, 'chart.adjustable': false } // Check for support if (!this.canvas) { alert('[BAR] No canvas support'); return; } // Check the common library has been included if (typeof(RGraph) == 'undefined') { alert('[BAR] Fatal error: The common library does not appear to have been included'); } /** * Determine whether the chart will contain stacked or grouped bars */ for (i=0; i<data.length; ++i) { if (typeof(data[i]) == 'object') { this.stackedOrGrouped = true; } } // Store the data this.data = data; // Used to store the coords of the bars this.coords = []; } /** * A setter * * @param name string The name of the property to set * @param value mixed The value of the property */ RGraph.Bar.prototype.Set = function (name, value) { name = name.toLowerCase(); if (name == 'chart.labels.abovebar') { name = 'chart.labels.above'; } if (name == 'chart.strokestyle') { name = 'chart.strokecolor'; } this.properties[name] = value; } /** * A getter * * @param name string The name of the property to get */ RGraph.Bar.prototype.Get = function (name) { if (name == 'chart.labels.abovebar') { name = 'chart.labels.above'; } return this.properties[name]; } /** * The function you call to draw the bar chart */ RGraph.Bar.prototype.Draw = function () { /** * Fire the onbeforedraw event */ RGraph.FireCustomEvent(this, 'onbeforedraw'); /** * Clear all of this canvases event handlers (the ones installed by RGraph) */ RGraph.ClearEventListeners(this.id); /** * Convert any null values to 0. Won't make any difference to the bar (as opposed to the line chart) */ for (var i=0; i<this.data.length; ++i) { if (this.data[i] == null) { this.data[i] = 0; } } // Cache this in a class variable as it's used rather a lot this.gutter = this.Get('chart.gutter'); /** * Check for tooltips and alert the user that they're not supported with pyramid charts */ if ( (this.Get('chart.variant') == 'pyramid' || this.Get('chart.variant') == 'dot') && typeof(this.Get('chart.tooltips')) == 'object' && this.Get('chart.tooltips') && this.Get('chart.tooltips').length > 0) { alert('[BAR] (' + this.id + ') Sorry, tooltips are not supported with dot or pyramid charts'); } /** * Stop the coords array from growing uncontrollably */ this.coords = []; /** * Work out a few things. They need to be here because they depend on things you can change before you * call Draw() but after you instantiate the object */ this.max = 0; this.grapharea = this.canvas.height - ( (2 * this.gutter)); this.halfgrapharea = this.grapharea / 2; this.halfTextHeight = this.Get('chart.text.size') / 2; // Progressively Draw the chart RGraph.background.Draw(this); //If it's a sketch chart variant, draw the axes first if (this.Get('chart.variant') == 'sketch') { this.DrawAxes(); this.Drawbars(); } else { this.Drawbars(); this.DrawAxes(); } this.DrawLabels(); // Draw the key if necessary if (this.Get('chart.key').length) { RGraph.DrawKey(this, this.Get('chart.key'), this.Get('chart.colors')); } /** * Setup the context menu if required */ if (this.Get('chart.contextmenu')) { RGraph.ShowContext(this); } /** * Is a line is defined, draw it */ var line = this.Get('chart.line'); if (line) { // Check the length of the data(s) if (line.original_data[0].length != this.data.length) { alert("[BAR] You're adding a line with a differing amount of data points to the bar chart - this is not permitted"); } // Check the X axis positions if (this.Get('chart.xaxispos') != line.Get('chart.xaxispos')) { alert("[BAR] Using different X axis positions when combining the Bar and Line is not advised"); } line.Set('chart.gutter', this.Get('chart.gutter')); line.Set('chart.noaxes', true); line.Set('chart.background.barcolor1', 'rgba(0,0,0,0)'); line.Set('chart.background.barcolor2', 'rgba(0,0,0,0)'); line.Set('chart.background.grid', false); line.Set('chart.ylabels', false); line.Set('chart.hmargin', (this.canvas.width - (2 * this.gutter)) / (line.original_data[0].length * 2)); // If a custom yMax is set, use that if (this.Get('chart.ymax')) { line.Set('chart.ymax', this.Get('chart.ymax')); } line.Draw(); } /** * Draw "in graph" labels */ if (this.Get('chart.labels.ingraph')) { RGraph.DrawInGraphLabels(this); } /** * Draw crosschairs */ if (this.Get('chart.crosshairs')) { RGraph.DrawCrosshairs(this); } /** * If the canvas is annotatable, do install the event handlers */ if (this.Get('chart.annotatable')) { RGraph.Annotate(this); } /** * This bit shows the mini zoom window if requested */ if (this.Get('chart.zoom.mode') == 'thumbnail' || this.Get('chart.zoom.mode') == 'area') { RGraph.ShowZoomWindow(this); } /** * This function enables resizing */ if (this.Get('chart.resizable')) { RGraph.AllowResizing(this); } /** * This function enables adjusting */ if (this.Get('chart.adjustable')) { RGraph.AllowAdjusting(this); } /** * Fire the RGraph ondraw event */ RGraph.FireCustomEvent(this, 'ondraw'); } /** * Draws the charts axes */ RGraph.Bar.prototype.DrawAxes = function () { var gutter = this.gutter; var xaxispos = this.Get('chart.xaxispos'); var yaxispos = this.Get('chart.yaxispos'); this.context.beginPath(); this.context.strokeStyle = this.Get('chart.axis.color'); this.context.lineWidth = 1; // Draw the Y axis if (yaxispos == 'right') { this.context.moveTo(this.canvas.width - gutter, gutter); this.context.lineTo(this.canvas.width - gutter, this.canvas.height - gutter); } else { this.context.moveTo(gutter, gutter); this.context.lineTo(gutter, this.canvas.height - gutter); } // Draw the X axis this.context.moveTo(gutter, (xaxispos == 'center' ? this.canvas.height / 2 : this.canvas.height - gutter)); this.context.lineTo(this.canvas.width - gutter, xaxispos == 'center' ? this.canvas.height / 2 : this.canvas.height - gutter); var numYTicks = this.Get('chart.numyticks'); // Draw the Y tickmarks var yTickGap = (this.canvas.height - (2 * gutter)) / numYTicks; var xpos = yaxispos == 'left' ? gutter : this.canvas.width - gutter; for (y=gutter; xaxispos == 'center' ? y <= (this.canvas.height - gutter) : y < (this.canvas.height - gutter); y += yTickGap) { if (xaxispos == 'center' && y == (this.canvas.height / 2)) continue; this.context.moveTo(xpos, y); this.context.lineTo(xpos + (yaxispos == 'left' ? -3 : 3), y); } // Draw the X tickmarks xTickGap = (this.canvas.width - (2 * gutter) ) / this.data.length; yStart = this.canvas.height - gutter; yEnd = (this.canvas.height - gutter) + 3; //////////////// X TICKS //////////////// // Now move the Y start end positions down if the axis is set to center if (xaxispos == 'center') { yStart = (this.canvas.height / 2) + 3; yEnd = (this.canvas.height / 2) - 3; } for (x=gutter + (yaxispos == 'left' ? xTickGap : 0); x<this.canvas.width - gutter + (yaxispos == 'left' ? 5 : 0); x+=xTickGap) { this.context.moveTo(x, yStart); this.context.lineTo(x, yEnd); } //////////////// X TICKS //////////////// this.context.stroke(); } /** * Draws the bars */ RGraph.Bar.prototype.Drawbars = function () { this.context.lineWidth = this.Get('chart.linewidth'); this.context.strokeStyle = this.Get('chart.strokecolor'); this.context.fillStyle = this.Get('chart.colors')[0]; var prevX = 0; var prevY = 0; var gutter = this.gutter; var decimals = this.Get('chart.scale.decimals'); /** * Work out the max value */ if (this.Get('chart.ymax')) { this.max = this.Get('chart.ymax'); this.scale = [ (this.max * (1/5)).toFixed(decimals), (this.max * (2/5)).toFixed(decimals), (this.max * (3/5)).toFixed(decimals), (this.max * (4/5)).toFixed(decimals), this.max.toFixed(decimals) ]; } else { for (i=0; i<this.data.length; ++i) { if (typeof(this.data[i]) == 'object') { var value = this.Get('chart.grouping') == 'grouped' ? Number(RGraph.array_max(this.data[i], true)) : Number(RGraph.array_sum(this.data[i])) ; } else { var value = Number(this.data[i]); } this.max = Math.max(Math.abs(this.max), Math.abs(value)); } this.scale = RGraph.getScale(this.max, this); this.max = this.scale[4]; if (this.Get('chart.scale.decimals')) { var decimals = this.Get('chart.scale.decimals'); this.scale[0] = Number(this.scale[0]).toFixed(decimals); this.scale[1] = Number(this.scale[1]).toFixed(decimals); this.scale[2] = Number(this.scale[2]).toFixed(decimals); this.scale[3] = Number(this.scale[3]).toFixed(decimals); this.scale[4] = Number(this.scale[4]).toFixed(decimals); } } /** * Draw horizontal bars here */ if (this.Get('chart.background.hbars') && this.Get('chart.background.hbars').length > 0) { RGraph.DrawBars(this); } var variant = this.Get('chart.variant'); /** * Draw the 3D axes is necessary */ if (variant == '3d') { RGraph.Draw3DAxes(this); } /** * Get the variant once, and draw the bars, be they regular, stacked or grouped */ // Get these variables outside of the loop var xaxispos = this.Get('chart.xaxispos'); var width = (this.canvas.width - (2 * gutter) ) / this.data.length; var orig_height = height; var hmargin = this.Get('chart.hmargin'); var shadow = this.Get('chart.shadow'); var shadowColor = this.Get('chart.shadow.color'); var shadowBlur = this.Get('chart.shadow.blur'); var shadowOffsetX = this.Get('chart.shadow.offsetx'); var shadowOffsetY = this.Get('chart.shadow.offsety'); var strokeStyle = this.Get('chart.strokecolor'); var colors = this.Get('chart.colors'); for (i=0; i<this.data.length; ++i) { // Work out the height //The width is up outside the loop var height = (RGraph.array_sum(this.data[i]) / this.max) * (this.canvas.height - (2 * gutter) ); // Half the height if the Y axis is at the center if (xaxispos == 'center') { height /= 2; } var x = (i * width) + gutter; var y = xaxispos == 'center' ? (this.canvas.height / 2) - height : this.canvas.height - height - gutter; // Account for negative lengths - Some browsers (eg Chrome) don't like a negative value if (height < 0) { y += height; height = Math.abs(height); } /** * Turn on the shadow if need be */ if (shadow) { this.context.shadowColor = shadowColor; this.context.shadowBlur = shadowBlur; this.context.shadowOffsetX = shadowOffsetX; this.context.shadowOffsetY = shadowOffsetY; } /** * Draw the bar */ this.context.beginPath(); if (typeof(this.data[i]) == 'number') { var barWidth = width - (2 * hmargin); // Set the fill color this.context.strokeStyle = strokeStyle; this.context.fillStyle = colors[0]; if (variant == 'sketch') { this.context.lineCap = 'round'; var sketchOffset = 3; this.context.beginPath(); this.context.strokeStyle = colors[0]; // Left side this.context.moveTo(x + hmargin + 2, y + height - 2); this.context.lineTo(x + hmargin , y - 2); // The top this.context.moveTo(x + hmargin - 3, y + -2 + (this.data[i] < 0 ? height : 0)); this.context.bezierCurveTo(x + ((hmargin + width) * 0.33),y + 5 + (this.data[i] < 0 ? height - 10: 0),x + ((hmargin + width) * 0.66),y + 5 + (this.data[i] < 0 ? height - 10 : 0),x + hmargin + width + -1, y + 0 + (this.data[i] < 0 ? height : 0)); // The right side this.context.moveTo(x + hmargin + width - 2, y + -2); this.context.lineTo(x + hmargin + width - 3, y + height - 3); for (var r=0.2; r<=0.8; r+=0.2) { this.context.moveTo(x + hmargin + width + (r > 0.4 ? -1 : 3) - (r * width),y - 1); this.context.lineTo(x + hmargin + width - (r > 0.4 ? 1 : -1) - (r * width), y + height + (r == 0.2 ? 1 : -2)); } this.context.stroke(); // Regular bar } else if (variant == 'bar' || variant == '3d' || variant == 'glass') { if (document.all && shadow) { this.DrawIEShadow([x + hmargin, y, barWidth, height]); } if (variant == 'glass') { RGraph.filledCurvyRect(this.context, x + hmargin, y, barWidth, height, 3, this.data[i] > 0, this.data[i] > 0, this.data[i] < 0, this.data[i] < 0); RGraph.strokedCurvyRect(this.context, x + hmargin, y, barWidth, height, 3, this.data[i] > 0, this.data[i] > 0, this.data[i] < 0, this.data[i] < 0); } else { this.context.strokeRect(x + hmargin, y, barWidth, height); this.context.fillRect(x + hmargin, y, barWidth, height); } // This bit draws the text labels that appear above the bars if requested if (this.Get('chart.labels.above')) { // Turn off any shadow if (shadow) { RGraph.NoShadow(this); } var yPos = y - 3; // Account for negative bars if (this.data[i] < 0) { yPos += height + 6 + (this.Get('chart.text.size') - 4); } this.context.fillStyle = this.Get('chart.text.color'); RGraph.Text(this.context, this.Get('chart.text.font'), typeof(this.Get('chart.labels.above.size')) == 'number' ? this.Get('chart.labels.above.size') : this.Get('chart.text.size') - 3, x + hmargin + (barWidth / 2), yPos, RGraph.number_format(this, Number(this.data[i]).toFixed(this.Get('chart.labels.above.decimals')),this.Get('chart.units.pre'), this.Get('chart.units.post')), null, 'center'); } // 3D effect if (variant == '3d') { var prevStrokeStyle = this.context.strokeStyle; var prevFillStyle = this.context.fillStyle; // Draw the top this.context.beginPath(); this.context.moveTo(x + hmargin, y); this.context.lineTo(x + hmargin + 10, y - 5); this.context.lineTo(x + hmargin + 10 + barWidth, y - 5); this.context.lineTo(x + hmargin + barWidth, y); this.context.closePath(); this.context.stroke(); this.context.fill(); // Draw the right hand side this.context.beginPath(); this.context.moveTo(x + hmargin + barWidth, y); this.context.lineTo(x + hmargin + barWidth + 10, y - 5); this.context.lineTo(x + hmargin + barWidth + 10, y + height - 5); this.context.lineTo(x + hmargin + barWidth, y + height); this.context.closePath(); this.context.stroke(); this.context.fill(); // Draw the darker top section this.context.beginPath(); this.context.fillStyle = 'rgba(255,255,255,0.3)'; this.context.moveTo(x + hmargin, y); this.context.lineTo(x + hmargin + 10, y - 5); this.context.lineTo(x + hmargin + 10 + barWidth, y - 5); this.context.lineTo(x + hmargin + barWidth, y); this.context.lineTo(x + hmargin, y); this.context.closePath(); this.context.stroke(); this.context.fill(); // Draw the darker right side section this.context.beginPath(); this.context.fillStyle = 'rgba(0,0,0,0.4)'; this.context.moveTo(x + hmargin + barWidth, y); this.context.lineTo(x + hmargin + barWidth + 10, y - 5); this.context.lineTo(x + hmargin + barWidth + 10, y - 5 + height); this.context.lineTo(x + hmargin + barWidth, y + height); this.context.lineTo(x + hmargin + barWidth, y); this.context.closePath(); this.context.stroke(); this.context.fill(); this.context.strokeStyle = prevStrokeStyle; this.context.fillStyle = prevFillStyle; // Glass variant } else if (variant == 'glass') { var grad = this.context.createLinearGradient( x + hmargin, y, x + hmargin + (barWidth / 2), y ); grad.addColorStop(0, 'rgba(255,255,255,0.9)'); grad.addColorStop(1, 'rgba(255,255,255,0.5)'); this.context.beginPath(); this.context.fillStyle = grad; this.context.fillRect(x + hmargin + 2,y + (this.data[i] > 0 ? 2 : 0),(barWidth / 2) - 2,height - 2); this.context.fill(); } // Dot chart } else if (variant == 'dot') { this.context.beginPath(); this.context.moveTo(x + (width / 2), y); this.context.lineTo(x + (width / 2), y + height); this.context.stroke(); this.context.beginPath(); this.context.fillStyle = this.Get('chart.colors')[i]; this.context.arc(x + (width / 2), y + (this.data[i] > 0 ? 0 : height), 2, 0, 6.28, 0); // Set the colour for the dots this.context.fillStyle = this.Get('chart.colors')[0]; this.context.stroke(); this.context.fill(); // Pyramid chart } else if (variant == 'pyramid') { this.context.beginPath(); var startY = (this.Get('chart.xaxispos') == 'center' ? (this.canvas.height / 2) : (this.canvas.height - this.Get('chart.gutter'))); this.context.moveTo(x + hmargin, startY); this.context.lineTo( x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0) ); this.context.lineTo(x + hmargin + barWidth, startY); this.context.closePath(); this.context.stroke(); this.context.fill(); // Arrow chart } else if (variant == 'arrow') { var startY = (this.Get('chart.xaxispos') == 'center' ? (this.canvas.height / 2) : (this.canvas.height - this.gutter)); this.context.lineWidth = this.Get('chart.linewidth') ? this.Get('chart.linewidth') : 1; this.context.lineCap = 'round'; this.context.beginPath(); this.context.moveTo(x + hmargin + (barWidth / 2), startY); this.context.lineTo(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0)); this.context.arc(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0), 5, this.data[i] > 0 ? 0.78 : 5.6, this.data[i] > 0 ? 0.79 : 5.48, this.data[i] < 0); this.context.moveTo(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0)); this.context.arc(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0), 5, this.data[i] > 0 ? 2.355 : 4, this.data[i] > 0 ? 2.4 : 3.925, this.data[i] < 0); this.context.stroke(); this.context.lineWidth = 1; // Unknown variant type } else { alert('[BAR] Warning! Unknown chart.variant: ' + variant); } this.coords.push([x + hmargin, y, width - (2 * hmargin), height]); /** * Stacked bar */ } else if (typeof(this.data[i]) == 'object' && this.Get('chart.grouping') == 'stacked') { var barWidth = width - (2 * hmargin); var redrawCoords = [];// Necessary to draw if the shadow is enabled var startY = 0; for (j=0; j<this.data[i].length; ++j) { // Stacked bar chart and X axis pos in the middle - poitless since negative values are not permitted if (xaxispos == 'center') { alert("[BAR] It's fruitless having the X axis position at the center on a stacked bar chart."); return; } // Negative values not permitted for the stacked chart if (this.data[i][j] < 0) { alert('[BAR] Negative values are not permitted with a stacked bar chart. Try a grouped one instead.'); return; } // Set the fill and stroke colors this.context.strokeStyle = strokeStyle this.context.fillStyle = colors[j]; var height = (this.data[i][j] / this.max) * (this.canvas.height - (2 * this.gutter) ); // If the X axis pos is in the center, we need to half the height if (xaxispos == 'center') { height /= 2; } var totalHeight = (RGraph.array_sum(this.data[i]) / this.max) * (this.canvas.height - hmargin - (2 * this.gutter)); /** * Store the coords for tooltips */ this.coords.push([x + hmargin, y, width - (2 * hmargin), height]); // MSIE shadow if (document.all && shadow) { this.DrawIEShadow([x + hmargin, y, width - (2 * hmargin), height + 1]); } this.context.strokeRect(x + hmargin, y, width - (2 * hmargin), height); this.context.fillRect(x + hmargin, y, width - (2 * hmargin), height); if (j == 0) { var startY = y; var startX = x; } /** * Store the redraw coords if the shadow is enabled */ if (shadow) { redrawCoords.push([x + hmargin, y, width - (2 * hmargin), height, colors[j]]); } /** * Stacked 3D effect */ if (variant == '3d') { var prevFillStyle = this.context.fillStyle; var prevStrokeStyle = this.context.strokeStyle; // Draw the top side if (j == 0) { this.context.beginPath(); this.context.moveTo(startX + hmargin, y); this.context.lineTo(startX + 10 + hmargin, y - 5); this.context.lineTo(startX + 10 + barWidth + hmargin, y - 5); this.context.lineTo(startX + barWidth + hmargin, y); this.context.closePath(); this.context.fill(); this.context.stroke(); } // Draw the side section this.context.beginPath(); this.context.moveTo(startX + barWidth + hmargin, y); this.context.lineTo(startX + barWidth + hmargin + 10, y - 5); this.context.lineTo(startX + barWidth + + hmargin + 10, y - 5 + height); this.context.lineTo(startX + barWidth + hmargin , y + height); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the darker top side if (j == 0) { this.context.fillStyle = 'rgba(255,255,255,0.3)'; this.context.beginPath(); this.context.moveTo(startX + hmargin, y); this.context.lineTo(startX + 10 + hmargin, y - 5); this.context.lineTo(startX + 10 + barWidth + hmargin, y - 5); this.context.lineTo(startX + barWidth + hmargin, y); this.context.closePath(); this.context.fill(); this.context.stroke(); } // Draw the darker side section this.context.fillStyle = 'rgba(0,0,0,0.4)'; this.context.beginPath(); this.context.moveTo(startX + barWidth + hmargin, y); this.context.lineTo(startX + barWidth + hmargin + 10, y - 5); this.context.lineTo(startX + barWidth + + hmargin + 10, y - 5 + height); this.context.lineTo(startX + barWidth + hmargin , y + height); this.context.closePath(); this.context.fill(); this.context.stroke(); this.context.strokeStyle = prevStrokeStyle; this.context.fillStyle = prevFillStyle; } y += height; } // This bit draws the text labels that appear above the bars if requested if (this.Get('chart.labels.above')) { // Turn off any shadow RGraph.NoShadow(this); this.context.fillStyle = this.Get('chart.text.color'); RGraph.Text(this.context,this.Get('chart.text.font'),typeof(this.Get('chart.labels.above.size')) == 'number' ? this.Get('chart.labels.above.size') : this.Get('chart.text.size') - 3,startX + (barWidth / 2) + this.Get('chart.hmargin'),startY - (this.Get('chart.shadow') && this.Get('chart.shadow.offsety') < 0 ? 7 : 4),String(this.Get('chart.units.pre') + RGraph.array_sum(this.data[i]).toFixed(this.Get('chart.labels.above.decimals')) + this.Get('chart.units.post')),null,'center'); // Turn any shadow back on if (shadow) { this.context.shadowColor = shadowColor; this.context.shadowBlur = shadowBlur; this.context.shadowOffsetX = shadowOffsetX; this.context.shadowOffsetY = shadowOffsetY; } } /** * Redraw the bars if the shadow is enabled due to hem being drawn from the bottom up, and the * shadow spilling over to higher up bars */ if (shadow) { RGraph.NoShadow(this); for (k=0; k<redrawCoords.length; ++k) { this.context.strokeStyle = strokeStyle; this.context.fillStyle = redrawCoords[k][4]; this.context.strokeRect(redrawCoords[k][0], redrawCoords[k][1], redrawCoords[k][2], redrawCoords[k][3]); this.context.fillRect(redrawCoords[k][0], redrawCoords[k][1], redrawCoords[k][2], redrawCoords[k][3]); this.context.stroke(); this.context.fill(); } // Reset the redraw coords to be empty redrawCoords = []; } /** * Grouped bar */ } else if (typeof(this.data[i]) == 'object' && this.Get('chart.grouping') == 'grouped') { var redrawCoords = []; this.context.lineWidth = this.Get('chart.linewidth'); for (j=0; j<this.data[i].length; ++j) { // Set the fill and stroke colors this.context.strokeStyle = strokeStyle; this.context.fillStyle = colors[j]; var individualBarWidth = (width - (2 * hmargin)) / this.data[i].length; var height = (this.data[i][j] / this.max) * (this.canvas.height - (2 * this.gutter) ); // If the X axis pos is in the center, we need to half the height if (xaxispos == 'center') { height /= 2; } var startX = x + hmargin + (j * individualBarWidth); var startY = (xaxispos == 'bottom' ? this.canvas.height : (this.canvas.height / 2) + this.gutter) - this.gutter - height; // Account for a bug in chrome that doesn't allow negative heights if (height < 0) { startY += height; height = Math.abs(height); } /** * Draw MSIE shadow */ if (document.all && shadow) { this.DrawIEShadow([startX, startY, individualBarWidth, height]); } this.context.strokeRect(startX, startY, individualBarWidth, height); this.context.fillRect(startX, startY, individualBarWidth, height); y += height; // This bit draws the text labels that appear above the bars if requested if (this.Get('chart.labels.above')) { this.context.strokeStyle = 'rgba(0,0,0,0)'; // Turn off any shadow if (shadow) { RGraph.NoShadow(this); } var yPos = y - 3; // Account for negative bars if (this.data[i][j] < 0) { yPos += height + 6 + (this.Get('chart.text.size') - 4); } this.context.fillStyle = this.Get('chart.text.color'); RGraph.Text(this.context,this.Get('chart.text.font'),typeof(this.Get('chart.labels.above.size')) == 'number' ? this.Get('chart.labels.above.size') : this.Get('chart.text.size') - 3,startX + (individualBarWidth / 2),startY - 2,RGraph.number_format(this, this.data[i][j].toFixed(this.Get('chart.labels.above.decimals'))),null,'center'); // Turn any shadow back on if (shadow) { this.context.shadowColor = shadowColor; this.context.shadowBlur = shadowBlur; this.context.shadowOffsetX = shadowOffsetX; this.context.shadowOffsetY = shadowOffsetY; } } /** * Grouped 3D effect */ if (variant == '3d') { var prevFillStyle = this.context.fillStyle; var prevStrokeStyle = this.context.strokeStyle; // Draw the top side this.context.beginPath(); this.context.moveTo(startX, startY); this.context.lineTo(startX + 10, startY - 5); this.context.lineTo(startX + 10 + individualBarWidth, startY - 5); this.context.lineTo(startX + individualBarWidth, startY); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the side section this.context.beginPath(); this.context.moveTo(startX + individualBarWidth, startY); this.context.lineTo(startX + individualBarWidth + 10, startY - 5); this.context.lineTo(startX + individualBarWidth + 10, startY - 5 + height); this.context.lineTo(startX + individualBarWidth , startY + height); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the darker top side this.context.fillStyle = 'rgba(255,255,255,0.3)'; this.context.beginPath(); this.context.moveTo(startX, startY); this.context.lineTo(startX + 10, startY - 5); this.context.lineTo(startX + 10 + individualBarWidth, startY - 5); this.context.lineTo(startX + individualBarWidth, startY); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the darker side section this.context.fillStyle = 'rgba(0,0,0,0.4)'; this.context.beginPath(); this.context.moveTo(startX + individualBarWidth, startY); this.context.lineTo(startX + individualBarWidth + 10, startY - 5); this.context.lineTo(startX + individualBarWidth + 10, startY - 5 + height); this.context.lineTo(startX + individualBarWidth , startY + height); this.context.closePath(); this.context.fill(); this.context.stroke(); this.context.strokeStyle = prevStrokeStyle; this.context.fillStyle = prevFillStyle; } this.coords.push([startX, startY, individualBarWidth, height]); // Facilitate shadows going to the left if (this.Get('chart.shadow')) { redrawCoords.push([startX, startY, individualBarWidth, height]); } } /** * Redraw the bar if shadows are going to the left */ if (redrawCoords.length) { RGraph.NoShadow(this); this.context.lineWidth = this.Get('chart.linewidth'); this.context.beginPath(); for (var j=0; j<redrawCoords.length; ++j) { this.context.fillStyle = this.Get('chart.colors')[j]; this.context.strokeStyle = this.Get('chart.strokecolor'); this.context.fillRect(redrawCoords[j][0], redrawCoords[j][1], redrawCoords[j][2], redrawCoords[j][3]); this.context.strokeRect(redrawCoords[j][0], redrawCoords[j][1], redrawCoords[j][2], redrawCoords[j][3]); } this.context.fill(); this.context.stroke(); redrawCoords = []; } } this.context.closePath(); } /** * Turn off any shadow */ RGraph.NoShadow(this); /** * Install the onclick event handler */ if (this.Get('chart.tooltips')) { // Need to register this object for redrawing RGraph.Register(this); /** * Install the window onclick handler */ var window_onclick_func = function (){RGraph.Redraw();}; window.addEventListener('click', window_onclick_func, false); RGraph.AddEventListener('window_' + this.id, 'click', window_onclick_func); /** * If the cursor is over a hotspot, change the cursor to a hand. Bar chart tooltips can now * be based around the onmousemove event */ canvas_onmousemove = function (e) { e = RGraph.FixEventObject(e); var canvas = document.getElementById(e.target.id); var obj = canvas.__object__; var barCoords = obj.getBar(e); /** * If there are bar coords AND the bar has height */ if (barCoords && barCoords[4] > 0) { /** * Get the tooltip text */ if (typeof(obj.Get('chart.tooltips')) == 'function') { var text = String(obj.Get('chart.tooltips')(barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'function') { var text = String(obj.Get('chart.tooltips')[barCoords[5]](barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && (typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'string' || typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'number')) { var text = String(obj.Get('chart.tooltips')[barCoords[5]]); } else { var text = null; } if (text) { canvas.style.cursor = 'pointer'; } else { canvas.style.cursor = 'default'; } /** * Hide the currently displayed tooltip if the index is the same */ if ( RGraph.Registry.Get('chart.tooltip') && RGraph.Registry.Get('chart.tooltip').__canvas__.id != obj.id && obj.Get('chart.tooltips.event') == 'onmousemove') { RGraph.Redraw(); RGraph.HideTooltip(); } /** * This facilitates the tooltips using the onmousemove event */ if ( obj.Get('chart.tooltips.event') == 'onmousemove' && ( (RGraph.Registry.Get('chart.tooltip') && RGraph.Registry.Get('chart.tooltip').__index__ != barCoords[5]) || !RGraph.Registry.Get('chart.tooltip') ) && text) { /** * Show a tooltip if it's defined */ RGraph.Redraw(obj); obj.context.beginPath(); obj.context.strokeStyle = 'black'; obj.context.fillStyle = 'rgba(255,255,255,0.5)'; obj.context.strokeRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.fillRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.stroke(); obj.context.fill(); RGraph.Tooltip(canvas, text, e.pageX, e.pageY, barCoords[5]); } } else { canvas.style.cursor = 'default'; } } RGraph.AddEventListener(this.id, 'mousemove', canvas_onmousemove); this.canvas.addEventListener('mousemove', canvas_onmousemove, false); /** * Install the onclick event handler for the tooltips */ if (this.Get('chart.tooltips.event') == 'onclick') { canvas_onclick = function (e) { var e = RGraph.FixEventObject(e); // If the button pressed isn't the left, we're not interested if (e.button != 0) return; e = RGraph.FixEventObject(e); var canvas = document.getElementById(this.id); var obj = canvas.__object__; var barCoords = obj.getBar(e); /** * Redraw the graph first, in effect resetting the graph to as it was when it was first drawn * This "deselects" any already selected bar */ RGraph.Redraw(); /** * Loop through the bars determining if the mouse is over a bar */ if (barCoords) { /** * Get the tooltip text */ if (typeof(obj.Get('chart.tooltips')) == 'function') { var text = String(obj.Get('chart.tooltips')(barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'function') { var text = String(obj.Get('chart.tooltips')[barCoords[5]](barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object') { var text = String(obj.Get('chart.tooltips')[barCoords[5]]); } else { var text = null; } /** * Show a tooltip if it's defined */ if (text && text != 'undefined') { // [TODO] Allow customisation of the highlight colors obj.context.beginPath(); obj.context.strokeStyle = 'black'; obj.context.fillStyle = 'rgba(255,255,255,0.5)'; obj.context.strokeRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.fillRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.stroke(); obj.context.fill(); RGraph.Tooltip(canvas, text, e.pageX, e.pageY, barCoords[5]); } } /** * Stop the event bubbling */ e.stopPropagation(); } RGraph.AddEventListener(this.id, 'click', canvas_onclick); this.canvas.addEventListener('click', canvas_onclick, false); } // This resets the bar graph // 8th August 2010 : Is this redundant //if (typeof(obj) != 'undefined' && obj == RGraph.Registry.Get('chart.tooltip')) { // obj.style.display = 'none'; // RGraph.Registry.Set('chart.tooltip', null) //} } } /** * Draws the labels for the graph */ RGraph.Bar.prototype.DrawLabels = function () { var context = this.context; var gutter = this.gutter; var text_angle = this.Get('chart.text.angle'); var text_size = this.Get('chart.text.size'); var labels = this.Get('chart.labels'); // Draw the Y axis labels: if (this.Get('chart.ylabels')) { this.Drawlabels_center(); this.Drawlabels_bottom(); } /** * The X axis labels */ if (typeof(labels) == 'object' && labels) { var yOffset = 13 + Number(this.Get('chart.xlabels.offset')); /** * Text angle */ var angle = 0; var halign = 'center'; if (text_angle > 0) { angle = -1 * text_angle; halign = 'right'; yOffset -= 5; } // Draw the X axis labels context.fillStyle = this.Get('chart.text.color'); // How wide is each bar var barWidth = (this.canvas.width - (2 * gutter) ) / labels.length; // Reset the xTickGap xTickGap = (this.canvas.width - (2 * gutter)) / labels.length // Draw the X tickmarks var i=0; var font = this.Get('chart.text.font'); for (x=gutter + (xTickGap / 2); x<=this.canvas.width - gutter; x+=xTickGap) { RGraph.Text(context, font, text_size, x + (this.Get('chart.text.angle') == 90 ? 0: 0), (this.canvas.height - gutter) + yOffset, String(labels[i++]), (this.Get('chart.text.angle') == 90 ? 'center' : null), halign, null, angle); } } } /** * Draws the X axis in the middle */ RGraph.Bar.prototype.Drawlabels_center = function () { var font = this.Get('chart.text.font'); var numYLabels = this.Get('chart.ylabels.count'); this.context.fillStyle = this.Get('chart.text.color'); if (this.Get('chart.xaxispos') == 'center') { /** * Draw the top labels */ var interval = (this.grapharea * (1/10) ); var text_size = this.Get('chart.text.size'); var gutter = this.gutter; var units_pre = this.Get('chart.units.pre'); var units_post = this.Get('chart.units.post'); var context = this.context; var align = ''; var xpos = 0; var boxed = false; this.context.fillStyle = this.Get('chart.text.color'); this.context.strokeStyle = 'black'; if (this.Get('chart.ylabels.inside') == true) { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter + 5 : this.canvas.width - gutter - 5; var align = this.Get('chart.yaxispos') == 'left' ? 'left' : 'right'; var boxed = true; } else { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : this.canvas.width - gutter + 5; var align = this.Get('chart.yaxispos') == 'left' ? 'right' : 'left'; var boxed = false; } /** * Draw specific Y labels here so that the local variables can be reused */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); var grapharea = this.canvas.height - (2 * gutter); // Draw the top halves labels for (var i=0; i<labels.length; ++i) { var y = gutter + (grapharea * (i / (labels.length * 2) )); RGraph.Text(context, font, text_size, xpos, y, labels[i], 'center', align, boxed); } // Draw the bottom halves labels for (var i=labels.length-1; i>=0; --i) { var y = gutter + (grapharea * ( (i+1) / (labels.length * 2) )) + (grapharea / 2); RGraph.Text(context, font, text_size, xpos, y, labels[labels.length - i - 1], 'center', align, boxed); } return; } if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, boxed); if (numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (1*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (3*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, boxed); } if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (4*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (2*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, boxed); } } else if (numYLabels == 10) { // 10Y labels interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xpos,gutter + ((this.grapharea / (numYLabels * 2)) * i),RGraph.number_format(this, ((this.scale[4] / numYLabels) * (numYLabels - i)).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align, boxed); } } /////////////////////////////////////////////////////////////////////////////////// /** * Draw the bottom (X axis) labels */ var interval = (this.grapharea) / 10; if (numYLabels == 3 || numYLabels == 5) { if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - (4 * interval), '-' + RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - (2 * interval), '-' + RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, boxed); } if (numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - (3 * interval), '-' + RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - interval, '-' + RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, boxed); } RGraph.Text(context, font, text_size, xpos, this.grapharea + gutter + this.halfTextHeight, '-' + RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, boxed); } else if (numYLabels == 10) { // Arbitrary number of Y labels interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xpos,this.Get('chart.gutter') + (this.grapharea / 2) + ((this.grapharea / (numYLabels * 2)) * i) + (this.grapharea / (numYLabels * 2)),RGraph.number_format(this, ((this.scale[4] / numYLabels) * (i+1)).toFixed((this.Get('chart.scale.decimals'))), '-' + units_pre, units_post),'center', align, boxed); } } } } /** * Draws the X axdis at the bottom (the default) */ RGraph.Bar.prototype.Drawlabels_bottom = function () { this.context.beginPath(); this.context.fillStyle = this.Get('chart.text.color'); this.context.strokeStyle = 'black'; if (this.Get('chart.xaxispos') != 'center') { var interval = (this.grapharea * (1/5) ); var text_size = this.Get('chart.text.size'); var units_pre = this.Get('chart.units.pre'); var units_post = this.Get('chart.units.post'); var gutter = this.gutter; var context = this.context; var align = this.Get('chart.yaxispos') == 'left' ? 'right' : 'left'; var font = this.Get('chart.text.font'); var numYLabels = this.Get('chart.ylabels.count'); if (this.Get('chart.ylabels.inside') == true) { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter + 5 : this.canvas.width - gutter - 5; var align = this.Get('chart.yaxispos') == 'left' ? 'left' : 'right'; var boxed = true; } else { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : this.canvas.width - gutter + 5; var boxed = false; } /** * Draw specific Y labels here so that the local variables can be reused */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); var grapharea = this.canvas.height - (2 * gutter); for (var i=0; i<labels.length; ++i) { var y = gutter + (grapharea * (i / labels.length)); RGraph.Text(context, font, text_size, xpos, y, labels[i], 'center', align, boxed); } return; } // 1 label if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, boxed); // 5 labels if (numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (1*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (3*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, boxed); } // 3 labels if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (2*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (4*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, boxed); } } // 10 Y labels if (numYLabels == 10) { interval = (this.grapharea / numYLabels ); for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xpos, this.Get('chart.gutter') + ((this.grapharea / numYLabels) * i), RGraph.number_format(this,((this.scale[4] / numYLabels) * (numYLabels - i)).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align, boxed); } } } this.context.fill(); this.context.stroke(); } /** * This function is used by MSIE only to manually draw the shadow * * @param array coords The coords for the bar */ RGraph.Bar.prototype.DrawIEShadow = function (coords) { var prevFillStyle = this.context.fillStyle; var offsetx = this.Get('chart.shadow.offsetx'); var offsety = this.Get('chart.shadow.offsety'); this.context.lineWidth = this.Get('chart.linewidth'); this.context.fillStyle = this.Get('chart.shadow.color'); this.context.beginPath(); // Draw shadow here this.context.fillRect(coords[0] + offsetx, coords[1] + offsety, coords[2], coords[3]); this.context.fill(); // Change the fillstyle back to what it was this.context.fillStyle = prevFillStyle; } /** * Not used by the class during creating the graph, but is used by event handlers * to get the coordinates (if any) of the selected bar */ RGraph.Bar.prototype.getBar = function (e) { var canvas = e.target; var obj = e.target.__object__; var mouseCoords = RGraph.getMouseXY(e); /** * Loop through the bars determining if the mouse is over a bar */ for (var i=0; i<obj.coords.length; i++) { var mouseX = mouseCoords[0]; var mouseY = mouseCoords[1]; var left = obj.coords[i][0]; var top = obj.coords[i][1]; var width = obj.coords[i][2]; var height = obj.coords[i][3]; if ( mouseX >= (left + obj.Get('chart.tooltips.coords.adjust')[0]) && mouseX <= (left + width+ obj.Get('chart.tooltips.coords.adjust')[0]) && mouseY >= (top + obj.Get('chart.tooltips.coords.adjust')[1]) && mouseY <= (top + height + obj.Get('chart.tooltips.coords.adjust')[1]) ) { return [obj, left, top, width, height, i]; } } return null; }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ /** * Initialise the various objects */ if (typeof(RGraph) == 'undefined') RGraph = {isRGraph:true,type:'common'}; RGraph.Registry = {}; RGraph.Registry.store = []; RGraph.Registry.store['chart.event.handlers'] = []; RGraph.background = {}; RGraph.objects = []; RGraph.Resizing = {}; RGraph.events = []; /** * Returns five values which are used as a nice scale * * @param max int The maximum value of the graph * @param obj object The graph object * @return array An appropriate scale */ RGraph.getScale = function (max, obj) { /** * Special case for 0 */ if (max == 0) { return ['0.2', '0.4', '0.6', '0.8', '1.0']; } var original_max = max; /** * Manually do decimals */ if (max <= 1) { if (max > 0.5) { return [0.2,0.4,0.6,0.8, Number(1).toFixed(1)]; } else if (max >= 0.1) { return obj.Get('chart.scale.round') ? [0.2,0.4,0.6,0.8,1] : [0.1,0.2,0.3,0.4,0.5]; } else { var tmp = max; var exp = 0; while (tmp < 1.01) { exp += 1; tmp *= 10; } var ret = ['2e-' + exp, '4e-' + exp, '6e-' + exp, '8e-' + exp, '10e-' + exp]; if (max <= ('5e-' + exp)) { ret = ['1e-' + exp, '2e-' + exp, '3e-' + exp, '4e-' + exp, '5e-' + exp]; } return ret; } } // Take off any decimals if (String(max).indexOf('.') > 0) { max = String(max).replace(/\.\d+$/, ''); } var interval = Math.pow(10, Number(String(Number(max)).length - 1)); var topValue = interval; while (topValue < max) { topValue += (interval / 2); } // Handles cases where the max is (for example) 50.5 if (Number(original_max) > Number(topValue)) { topValue += (interval / 2); } // Custom if the max is greater than 5 and less than 10 if (max < 10) { topValue = (Number(original_max) <= 5 ? 5 : 10); } /** * Added 02/11/2010 to create "nicer" scales */ if (obj && typeof(obj.Get('chart.scale.round')) == 'boolean' && obj.Get('chart.scale.round')) { topValue = 10 * interval; } return [topValue * 0.2, topValue * 0.4, topValue * 0.6, topValue * 0.8, topValue]; } /** * Returns the maximum value which is in an array * * @param array arr The array * @param int Whether to ignore signs (ie negative/positive) * @return int The maximum value in the array */ RGraph.array_max = function (arr) { var max = null; for (var i=0; i<arr.length; ++i) { if (typeof(arr[i]) == 'number') { max = (max ? Math.max(max, arguments[1] ? Math.abs(arr[i]) : arr[i]) : arr[i]); } } return max; } /** * Returns the maximum value which is in an array * * @param array arr The array * @param int len The length to pad the array to * @param mixed The value to use to pad the array (optional) */ RGraph.array_pad = function (arr, len) { if (arr.length < len) { var val = arguments[2] ? arguments[2] : null; for (var i=arr.length; i<len; ++i) { arr[i] = val; } } return arr; } /** * An array sum function * * @param array arr The array to calculate the total of * @return int The summed total of the arrays elements */ RGraph.array_sum = function (arr) { // Allow integers if (typeof(arr) == 'number') { return arr; } var i, sum; var len = arr.length; for(i=0,sum=0;i<len;sum+=arr[i++]); return sum; } /** * A simple is_array() function * * @param mixed obj The object you want to check * @return bool Whether the object is an array or not */ RGraph.is_array = function (obj) { return obj != null && obj.constructor.toString().indexOf('Array') != -1; } /** * Converts degrees to radians * * @param int degrees The number of degrees * @return float The number of radians */ RGraph.degrees2Radians = function (degrees) { return degrees * (Math.PI / 180); } /** * This function draws an angled line. The angle is cosidered to be clockwise * * @param obj ctxt The context object * @param int x The X position * @param int y The Y position * @param int angle The angle in RADIANS * @param int length The length of the line */ RGraph.lineByAngle = function (context, x, y, angle, length) { context.arc(x, y, length, angle, angle, false); context.lineTo(x, y); context.arc(x, y, length, angle, angle, false); } /** * This is a useful function which is basically a shortcut for drawing left, right, top and bottom alligned text. * * @param object context The context * @param string font The font * @param int size The size of the text * @param int x The X coordinate * @param int y The Y coordinate * @param string text The text to draw * @parm string The vertical alignment. Can be null. "center" gives center aligned text, "top" gives top aligned text. * Anything else produces bottom aligned text. Default is bottom. * @param string The horizontal alignment. Can be null. "center" gives center aligned text, "right" gives right aligned text. * Anything else produces left aligned text. Default is left. * @param bool Whether to show a bounding box around the text. Defaults not to * @param int The angle that the text should be rotate at (IN DEGREES) * @param string Background color for the text * @param bool Whether the text is bold or not * @param bool Whether the bounding box has a placement indicator */ RGraph.Text = function (context, font, size, x, y, text) { /** * This calls the text function recursively to accommodate multi-line text */ if (typeof(text) == 'string' && text.match(/\r?\n/)) { var nextline = text.replace(/^.*\r?\n/, ''); RGraph.Text(context, font, size, arguments[9] == -90 ? (x + (size * 1.5)) : x, y + (size * 1.5), nextline, arguments[6] ? arguments[6] : null, 'center', arguments[8], arguments[9], arguments[10], arguments[11], arguments[12]); text = text.replace(/\r?\n.*$/, ''); } // Accommodate MSIE if (RGraph.isIE8()) { y += 2; } context.font = (arguments[11] ? 'Bold ': '') + size + 'pt ' + font; var i; var origX = x; var origY = y; var originalFillStyle = context.fillStyle; var originalLineWidth = context.lineWidth; // Need these now the angle can be specified, ie defaults for the former two args if (typeof(arguments[6]) == null) arguments[6] = 'bottom'; // Vertical alignment. Default to bottom/baseline if (typeof(arguments[7]) == null) arguments[7] = 'left'; // Horizontal alignment. Default to left if (typeof(arguments[8]) == null) arguments[8] = null; // Show a bounding box. Useful for positioning during development. Defaults to false if (typeof(arguments[9]) == null) arguments[9] = 0; // Angle (IN DEGREES) that the text should be drawn at. 0 is middle right, and it goes clockwise if (typeof(arguments[12]) == null) arguments[12] = true; // Whether the bounding box has the placement indicator // The alignment is recorded here for purposes of Opera compatibility if (navigator.userAgent.indexOf('Opera') != -1) { context.canvas.__rgraph_valign__ = arguments[6]; context.canvas.__rgraph_halign__ = arguments[7]; } // First, translate to x/y coords context.save(); context.canvas.__rgraph_originalx__ = x; context.canvas.__rgraph_originaly__ = y; context.translate(x, y); x = 0; y = 0; // Rotate the canvas if need be if (arguments[9]) { context.rotate(arguments[9] / 57.3); } // Vertical alignment - defaults to bottom if (arguments[6]) { var vAlign = arguments[6]; if (vAlign == 'center') { context.translate(0, size / 2); } else if (vAlign == 'top') { context.translate(0, size); } } // Hoeizontal alignment - defaults to left if (arguments[7]) { var hAlign = arguments[7]; var width = context.measureText(text).width; if (hAlign) { if (hAlign == 'center') { context.translate(-1 * (width / 2), 0) } else if (hAlign == 'right') { context.translate(-1 * width, 0) } } } context.fillStyle = originalFillStyle; /** * Draw a bounding box if requested */ context.save(); context.fillText(text,0,0); context.lineWidth = 0.5; if (arguments[8]) { var width = context.measureText(text).width; var ieOffset = RGraph.isIE8() ? 2 : 0; context.translate(x, y); context.strokeRect(0 - 3, 0 - 3 - size - ieOffset, width + 6, 0 + size + 6); /** * If requested, draw a background for the text */ if (arguments[10]) { var offset = 3; var ieOffset = RGraph.isIE8() ? 2 : 0; var width = context.measureText(text).width //context.strokeStyle = 'gray'; context.fillStyle = arguments[10]; context.fillRect(x - offset, y - size - offset - ieOffset, width + (2 * offset), size + (2 * offset)); //context.strokeRect(x - offset, y - size - offset - ieOffset, width + (2 * offset), size + (2 * offset)); } /** * Do the actual drawing of the text */ context.fillStyle = originalFillStyle; context.fillText(text,0,0); if (arguments[12]) { context.fillRect( arguments[7] == 'left' ? 0 : (arguments[7] == 'center' ? width / 2 : width ) - 2, arguments[6] == 'bottom' ? 0 : (arguments[6] == 'center' ? (0 - size) / 2 : 0 - size) - 2, 4, 4 ); } } context.restore(); // Reset the lineWidth context.lineWidth = originalLineWidth; context.restore(); } /** * Clears the canvas by setting the width. You can specify a colour if you wish. * * @param object canvas The canvas to clear */ RGraph.Clear = function (canvas) { var context = canvas.getContext('2d'); context.fillStyle = arguments[1] ? String(arguments[1]) : 'white'; context = canvas.getContext('2d'); context.beginPath(); context.fillRect(-5,-5,canvas.width + 5,canvas.height + 5); context.fill(); if (RGraph.ClearAnnotations) { RGraph.ClearAnnotations(canvas.id); } } /** * Draws the title of the graph * * @param object canvas The canvas object * @param string text The title to write * @param integer gutter The size of the gutter * @param integer The center X point (optional - if not given it will be generated from the canvas width) * @param integer Size of the text. If not given it will be 14 */ RGraph.DrawTitle = function (canvas, text, gutter) { var obj = canvas.__object__; var context = canvas.getContext('2d'); var size = arguments[4] ? arguments[4] : 12; var centerx = (arguments[3] ? arguments[3] : canvas.width / 2); var keypos = obj.Get('chart.key.position'); var vpos = gutter / 2; var hpos = obj.Get('chart.title.hpos'); var bgcolor = obj.Get('chart.title.background'); // Account for 3D effect by faking the key position if (obj.type == 'bar' && obj.Get('chart.variant') == '3d') { keypos = 'gutter'; } context.beginPath(); context.fillStyle = obj.Get('chart.text.color') ? obj.Get('chart.text.color') : 'black'; /** * Vertically center the text if the key is not present */ if (keypos && keypos != 'gutter') { var vCenter = 'center'; } else if (!keypos) { var vCenter = 'center'; } else { var vCenter = 'bottom'; } // if chart.title.vpos does not equal 0.5, use that if (typeof(obj.Get('chart.title.vpos')) == 'number') { vpos = obj.Get('chart.title.vpos') * gutter; } // if chart.title.hpos is a number, use that. It's multiplied with the (entire) canvas width if (typeof(hpos) == 'number') { centerx = hpos * canvas.width; } // Set the colour if (typeof(obj.Get('chart.title.color') != null)) { var oldColor = context.fillStyle var newColor = obj.Get('chart.title.color') context.fillStyle = newColor ? newColor : 'black'; } /** * Default font is Verdana */ var font = obj.Get('chart.text.font'); /** * Draw the title itself */ RGraph.Text(context, font, size, centerx, vpos, text, vCenter, 'center', bgcolor != null, null, bgcolor, true); // Reset the fill colour context.fillStyle = oldColor; } /** * This function returns the mouse position in relation to the canvas * * @param object e The event object. */ RGraph.getMouseXY = function (e) { var obj = (RGraph.isIE8() ? event.srcElement : e.target); var x; var y; if (RGraph.isIE8()) e = event; // Browser with offsetX and offsetY if (typeof(e.offsetX) == 'number' && typeof(e.offsetY) == 'number') { x = e.offsetX; y = e.offsetY; // FF and other } else { x = 0; y = 0; while (obj != document.body && obj) { x += obj.offsetLeft; y += obj.offsetTop; obj = obj.offsetParent; } x = e.pageX - x; y = e.pageY - y; } return [x, y]; } /** * This function returns a two element array of the canvas x/y position in * relation to the page * * @param object canvas */ RGraph.getCanvasXY = function (canvas) { var x = 0; var y = 0; var obj = canvas; do { x += obj.offsetLeft; y += obj.offsetTop; obj = obj.offsetParent; } while (obj && obj.tagName.toLowerCase() != 'body'); return [x, y]; } /** * Registers a graph object (used when the canvas is redrawn) * * @param object obj The object to be registered */ RGraph.Register = function (obj) { var key = obj.id + '_' + obj.type; RGraph.objects[key] = obj; } /** * Causes all registered objects to be redrawn * * @param string An optional string indicating which canvas is not to be redrawn * @param string An optional color to use to clear the canvas */ RGraph.Redraw = function () { for (i in RGraph.objects) { // TODO FIXME Maybe include more intense checking for whether the object is an RGraph object, eg obj.isRGraph == true ...? if ( typeof(i) == 'string' && typeof(RGraph.objects[i]) == 'object' && typeof(RGraph.objects[i].type) == 'string' && RGraph.objects[i].isRGraph) { if (!arguments[0] || arguments[0] != RGraph.objects[i].id) { RGraph.Clear(RGraph.objects[i].canvas, arguments[1] ? arguments[1] : null); RGraph.objects[i].Draw(); } } } } /** * Loosly mimicks the PHP function print_r(); */ RGraph.pr = function (obj) { var str = ''; var indent = (arguments[2] ? arguments[2] : ''); switch (typeof(obj)) { case 'number': if (indent == '') { str+= 'Number: ' } str += String(obj); break; case 'string': if (indent == '') { str+= 'String (' + obj.length + '):' } str += '"' + String(obj) + '"'; break; case 'object': // In case of null if (obj == null) { str += 'null'; break; } str += 'Object\n' + indent + '(\n'; for (var i=0; i<obj.length; ++i) { str += indent + ' ' + i + ' => ' + RGraph.pr(obj[i], true, indent + ' ') + '\n'; } var str = str + indent + ')'; break; case 'function': str += obj; break; case 'boolean': str += 'Boolean: ' + (obj ? 'true' : 'false'); break; } /** * Finished, now either return if we're in a recursed call, or alert() * if we're not. */ if (arguments[1]) { return str; } else { alert(str); } } /** * The RGraph registry Set() function * * @param string name The name of the key * @param mixed value The value to set * @return mixed Returns the same value as you pass it */ RGraph.Registry.Set = function (name, value) { // Store the setting RGraph.Registry.store[name] = value; // Don't really need to do this, but ho-hum return value; } /** * The RGraph registry Get() function * * @param string name The name of the particular setting to fetch * @return mixed The value if exists, null otherwise */ RGraph.Registry.Get = function (name) { //return RGraph.Registry.store[name] == null ? null : RGraph.Registry.store[name]; return RGraph.Registry.store[name]; } /** * This function draws the background for the bar chart, line chart and scatter chart. * * @param object obj The graph object */ RGraph.background.Draw = function (obj) { var canvas = obj.canvas; var context = obj.context; var height = 0; var gutter = obj.Get('chart.gutter'); var variant = obj.Get('chart.variant'); context.fillStyle = obj.Get('chart.text.color'); // If it's a bar and 3D variant, translate if (variant == '3d') { context.save(); context.translate(10, -5); } // X axis title if (typeof(obj.Get('chart.title.xaxis')) == 'string' && obj.Get('chart.title.xaxis').length) { var size = obj.Get('chart.text.size'); var font = obj.Get('chart.text.font'); context.beginPath(); RGraph.Text(context, font, size + 2, obj.canvas.width / 2, canvas.height - (gutter * obj.Get('chart.title.xaxis.pos')), obj.Get('chart.title.xaxis'), 'center', 'center', false, false, false, true); context.fill(); } // Y axis title if (typeof(obj.Get('chart.title.yaxis')) == 'string' && obj.Get('chart.title.yaxis').length) { var size = obj.Get('chart.text.size'); var font = obj.Get('chart.text.font'); context.beginPath(); RGraph.Text(context, font, size + 2, gutter * obj.Get('chart.title.yaxis.pos'), canvas.height / 2, obj.Get('chart.title.yaxis'), 'center', 'center', false, 270, false, true); context.fill(); } obj.context.beginPath(); // Draw the horizontal bars context.fillStyle = obj.Get('chart.background.barcolor1'); height = (obj.canvas.height - obj.Get('chart.gutter')); for (var i=gutter; i < height ; i+=80) { obj.context.fillRect(gutter, i, obj.canvas.width - (gutter * 2), Math.min(40, obj.canvas.height - gutter - i) ); } context.fillStyle = obj.Get('chart.background.barcolor2'); height = (obj.canvas.height - gutter); for (var i= (40 + gutter); i < height; i+=80) { obj.context.fillRect(gutter, i, obj.canvas.width - (gutter * 2), i + 40 > (obj.canvas.height - gutter) ? obj.canvas.height - (gutter + i) : 40); } context.stroke(); // Draw the background grid if (obj.Get('chart.background.grid')) { // If autofit is specified, use the .numhlines and .numvlines along with the width to work // out the hsize and vsize if (obj.Get('chart.background.grid.autofit')) { var vsize = (canvas.width - (2 * obj.Get('chart.gutter')) - (obj.type == 'gantt' ? 2 * obj.Get('chart.gutter') : 0)) / obj.Get('chart.background.grid.autofit.numvlines'); var hsize = (canvas.height - (2 * obj.Get('chart.gutter'))) / obj.Get('chart.background.grid.autofit.numhlines'); obj.Set('chart.background.grid.vsize', vsize); obj.Set('chart.background.grid.hsize', hsize); } context.beginPath(); context.lineWidth = obj.Get('chart.background.grid.width') ? obj.Get('chart.background.grid.width') : 1; context.strokeStyle = obj.Get('chart.background.grid.color'); // Draw the horizontal lines if (obj.Get('chart.background.grid.hlines')) { height = (canvas.height - gutter) for (y=gutter; y < height; y+=obj.Get('chart.background.grid.hsize')) { context.moveTo(gutter, y); context.lineTo(canvas.width - gutter, y); } } if (obj.Get('chart.background.grid.vlines')) { // Draw the vertical lines var width = (canvas.width - gutter) for (x=gutter + (obj.type == 'gantt' ? (2 * gutter) : 0); x<=width; x+=obj.Get('chart.background.grid.vsize')) { context.moveTo(x, gutter); context.lineTo(x, obj.canvas.height - gutter); } } if (obj.Get('chart.background.grid.border')) { // Make sure a rectangle, the same colour as the grid goes around the graph context.strokeStyle = obj.Get('chart.background.grid.color'); context.strokeRect(gutter, gutter, canvas.width - (2 * gutter), canvas.height - (2 * gutter)); } } context.stroke(); // If it's a bar and 3D variant, translate if (variant == '3d') { context.restore(); } // Draw the title if one is set if ( typeof(obj.Get('chart.title')) == 'string') { if (obj.type == 'gantt') { gutter /= 2; } RGraph.DrawTitle(canvas, obj.Get('chart.title'), gutter, null, obj.Get('chart.text.size') + 2); } context.stroke(); } /** * Returns the day number for a particular date. Eg 1st February would be 32 * * @param object obj A date object * @return int The day number of the given date */ RGraph.GetDays = function (obj) { var year = obj.getFullYear(); var days = obj.getDate(); var month = obj.getMonth(); if (month == 0) return days; if (month >= 1) days += 31; if (month >= 2) days += 28; // Leap years. Crude, but if this code is still being used // when it stops working, then you have my permission to shoot // me. Oh, you won't be able to - I'll be dead... if (year >= 2008 && year % 4 == 0) days += 1; if (month >= 3) days += 31; if (month >= 4) days += 30; if (month >= 5) days += 31; if (month >= 6) days += 30; if (month >= 7) days += 31; if (month >= 8) days += 31; if (month >= 9) days += 30; if (month >= 10) days += 31; if (month >= 11) days += 30; return days; } /** * Draws the graph key (used by various graphs) * * @param object obj The graph object * @param array key An array of the texts to be listed in the key * @param colors An array of the colors to be used */ RGraph.DrawKey = function (obj, key, colors) { var canvas = obj.canvas; var context = obj.context; context.lineWidth = 1; context.beginPath(); /** * Key positioned in the gutter */ var keypos = obj.Get('chart.key.position'); var textsize = obj.Get('chart.text.size'); var gutter = obj.Get('chart.gutter'); /** * Change the older chart.key.vpos to chart.key.position.y */ if (typeof(obj.Get('chart.key.vpos')) == 'number') { obj.Set('chart.key.position.y', obj.Get('chart.key.vpos') * gutter); } if (keypos && keypos == 'gutter') { RGraph.DrawKey_gutter(obj, key, colors); /** * In-graph style key */ } else if (keypos && keypos == 'graph') { RGraph.DrawKey_graph(obj, key, colors); } else { alert('[COMMON] (' + obj.id + ') Unknown key position: ' + keypos); } } /** * This does the actual drawing of the key when it's in the graph * * @param object obj The graph object * @param array key The key items to draw * @param array colors An aray of colors that the key will use */ RGraph.DrawKey_graph = function (obj, key, colors) { var canvas = obj.canvas; var context = obj.context; var text_size = typeof(obj.Get('chart.key.text.size')) == 'number' ? obj.Get('chart.key.text.size') : obj.Get('chart.text.size'); var text_font = obj.Get('chart.text.font'); var gutter = obj.Get('chart.gutter'); var hpos = obj.Get('chart.yaxispos') == 'right' ? gutter + 10 : canvas.width - gutter - 10; var vpos = gutter + 10; var title = obj.Get('chart.title'); var blob_size = text_size; // The blob of color var hmargin = 8; // This is the size of the gaps between the blob of color and the text var vmargin = 4; // This is the vertical margin of the key var fillstyle = obj.Get('chart.key.background'); var strokestyle = 'black'; var height = 0; var width = 0; // Need to set this so that measuring the text works out OK context.font = text_size + 'pt ' + obj.Get('chart.text.font'); // Work out the longest bit of text for (i=0; i<key.length; ++i) { width = Math.max(width, context.measureText(key[i]).width); } width += 5; width += blob_size; width += 5; width += 5; width += 5; /** * Now we know the width, we can move the key left more accurately */ if ( obj.Get('chart.yaxispos') == 'left' || (obj.type == 'pie' && !obj.Get('chart.yaxispos')) || (obj.type == 'hbar' && !obj.Get('chart.yaxispos')) || (obj.type == 'rscatter' && !obj.Get('chart.yaxispos')) || (obj.type == 'tradar' && !obj.Get('chart.yaxispos')) || (obj.type == 'rose' && !obj.Get('chart.yaxispos')) || (obj.type == 'funnel' && !obj.Get('chart.yaxispos')) ) { hpos -= width; } /** * Specific location coordinates */ if (typeof(obj.Get('chart.key.position.x')) == 'number') { hpos = obj.Get('chart.key.position.x'); } if (typeof(obj.Get('chart.key.position.y')) == 'number') { vpos = obj.Get('chart.key.position.y'); } // Stipulate the shadow for the key box if (obj.Get('chart.key.shadow')) { context.shadowColor = obj.Get('chart.key.shadow.color'); context.shadowBlur = obj.Get('chart.key.shadow.blur'); context.shadowOffsetX = obj.Get('chart.key.shadow.offsetx'); context.shadowOffsetY = obj.Get('chart.key.shadow.offsety'); } // Draw the box that the key resides in context.beginPath(); context.fillStyle = obj.Get('chart.key.background'); context.strokeStyle = 'black'; if (arguments[3] != false) { /* // Manually draw the MSIE shadow if (RGraph.isIE8() && obj.Get('chart.key.shadow')) { context.beginPath(); context.fillStyle = '#666'; if (obj.Get('chart.key.rounded')) { RGraph.NoShadow(obj); context.beginPath(); RGraph.filledCurvyRect(context, xpos + obj.Get('chart.key.shadow.offsetx'), gutter + 5 + obj.Get('chart.key.shadow.offsety'), width - 5, 5 + ( (textsize + 5) * key.length), 5); context.closePath(); context.fill(); } else { context.fillRect(xpos + 2, gutter + 5 + 2, width - 5, 5 + ( (textsize + 5) * key.length)); } context.fill(); context.fillStyle = obj.Get('chart.key.background'); } */ // The older square rectangled key if (obj.Get('chart.key.rounded') == true) { context.beginPath(); context.strokeStyle = strokestyle; RGraph.strokedCurvyRect(context, hpos, vpos, width - 5, 5 + ( (text_size + 5) * key.length),4); context.stroke(); context.fill(); RGraph.NoShadow(obj); } else { context.strokeRect(hpos, vpos, width - 5, 5 + ( (text_size + 5) * key.length)); context.fillRect(hpos, vpos, width - 5, 5 + ( (text_size + 5) * key.length)); } } RGraph.NoShadow(obj); context.beginPath(); // Draw the labels given for (var i=key.length - 1; i>=0; i--) { var j = Number(i) + 1; // Draw the blob of color if (obj.Get('chart.key.color.shape') == 'circle') { context.beginPath(); context.strokeStyle = 'rgba(0,0,0,0)'; context.fillStyle = colors[i]; context.arc(hpos + 5 + (blob_size / 2), vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2), blob_size / 2, 0, 6.26, 0); context.fill(); } else if (obj.Get('chart.key.color.shape') == 'line') { context.beginPath(); context.strokeStyle = colors[i]; context.moveTo(hpos + 5, vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2)); context.lineTo(hpos + blob_size + 5, vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2)); context.stroke(); } else { context.fillStyle = colors[i]; context.fillRect(hpos + 5, vpos + (5 * j) + (text_size * j) - text_size, text_size, text_size + 1); } context.beginPath(); context.fillStyle = 'black'; RGraph.Text(context, text_font, text_size, hpos + blob_size + 5 + 5, vpos + (5 * j) + (text_size * j), key[i]); } context.fill(); } /** * This does the actual drawing of the key when it's in the gutter * * @param object obj The graph object * @param array key The key items to draw * @param array colors An aray of colors that the key will use */ RGraph.DrawKey_gutter = function (obj, key, colors) { var canvas = obj.canvas; var context = obj.context; var text_size = typeof(obj.Get('chart.key.text.size')) == 'number' ? obj.Get('chart.key.text.size') : obj.Get('chart.text.size'); var text_font = obj.Get('chart.text.font'); var gutter = obj.Get('chart.gutter'); var hpos = canvas.width / 2; var vpos = (gutter / 2) - 5; var title = obj.Get('chart.title'); var blob_size = text_size; // The blob of color var hmargin = 8; // This is the size of the gaps between the blob of color and the text var vmargin = 4; // This is the vertical margin of the key var fillstyle = obj.Get('chart.key.background'); var strokestyle = 'black'; var length = 0; // Need to work out the length of the key first context.font = text_size + 'pt ' + text_font; for (i=0; i<key.length; ++i) { length += hmargin; length += blob_size; length += hmargin; length += context.measureText(key[i]).width; } length += hmargin; /** * Work out hpos since in the Pie it isn't necessarily dead center */ if (obj.type == 'pie') { if (obj.Get('chart.align') == 'left') { var hpos = obj.radius + obj.Get('chart.gutter'); } else if (obj.Get('chart.align') == 'right') { var hpos = obj.canvas.width - obj.radius - obj.Get('chart.gutter'); } else { hpos = canvas.width / 2; } } /** * This makes the key centered */ hpos -= (length / 2); /** * Override the horizontal/vertical positioning */ if (typeof(obj.Get('chart.key.position.x')) == 'number') { hpos = obj.Get('chart.key.position.x'); } if (typeof(obj.Get('chart.key.position.y')) == 'number') { vpos = obj.Get('chart.key.position.y'); } /** * Draw the box that the key sits in */ if (obj.Get('chart.key.position.gutter.boxed')) { if (obj.Get('chart.key.shadow')) { context.shadowColor = obj.Get('chart.key.shadow.color'); context.shadowBlur = obj.Get('chart.key.shadow.blur'); context.shadowOffsetX = obj.Get('chart.key.shadow.offsetx'); context.shadowOffsetY = obj.Get('chart.key.shadow.offsety'); } context.beginPath(); context.fillStyle = fillstyle; context.strokeStyle = strokestyle; if (obj.Get('chart.key.rounded')) { RGraph.strokedCurvyRect(context, hpos, vpos - vmargin, length, text_size + vmargin + vmargin) // Odd... RGraph.filledCurvyRect(context, hpos, vpos - vmargin, length, text_size + vmargin + vmargin); } else { context.strokeRect(hpos, vpos - vmargin, length, text_size + vmargin + vmargin); context.fillRect(hpos, vpos - vmargin, length, text_size + vmargin + vmargin); } context.stroke(); context.fill(); RGraph.NoShadow(obj); } /** * Draw the blobs of color and the text */ for (var i=0, pos=hpos; i<key.length; ++i) { pos += hmargin; // Draw the blob of color - line if (obj.Get('chart.key.color.shape') =='line') { context.beginPath(); context.strokeStyle = colors[i]; context.moveTo(pos, vpos + (blob_size / 2)); context.lineTo(pos + blob_size, vpos + (blob_size / 2)); context.stroke(); // Circle } else if (obj.Get('chart.key.color.shape') == 'circle') { context.beginPath(); context.fillStyle = colors[i]; context.moveTo(pos, vpos + (blob_size / 2)); context.arc(pos + (blob_size / 2), vpos + (blob_size / 2), (blob_size / 2), 0, 6.28, 0); context.fill(); } else { context.beginPath(); context.fillStyle = colors[i]; context.fillRect(pos, vpos, blob_size, blob_size); context.fill(); } pos += blob_size; pos += hmargin; context.beginPath(); context.fillStyle = 'black'; RGraph.Text(context, text_font, text_size, pos, vpos + text_size - 1, key[i]); context.fill(); pos += context.measureText(key[i]).width; } } /** * A shortcut for RGraph.pr() */ function pd(variable) { RGraph.pr(variable); } function p(variable) { RGraph.pr(variable); } /** * A shortcut for console.log - as used by Firebug and Chromes console */ function cl (variable) { return console.log(variable); } /** * Makes a clone of an object * * @param obj val The object to clone */ RGraph.array_clone = function (obj) { if(obj == null || typeof(obj) != 'object') { return obj; } var temp = []; //var temp = new obj.constructor(); for(var i=0;i<obj.length; ++i) { temp[i] = RGraph.array_clone(obj[i]); } return temp; } /** * This function reverses an array */ RGraph.array_reverse = function (arr) { var newarr = []; for (var i=arr.length - 1; i>=0; i--) { newarr.push(arr[i]); } return newarr; } /** * Formats a number with thousand seperators so it's easier to read * * @param integer num The number to format * @param string The (optional) string to prepend to the string * @param string The (optional) string to ap * pend to the string * @return string The formatted number */ RGraph.number_format = function (obj, num) { var i; var prepend = arguments[2] ? String(arguments[2]) : ''; var append = arguments[3] ? String(arguments[3]) : ''; var output = ''; var decimal = ''; var decimal_seperator = obj.Get('chart.scale.point') ? obj.Get('chart.scale.point') : '.'; var thousand_seperator = obj.Get('chart.scale.thousand') ? obj.Get('chart.scale.thousand') : ','; RegExp.$1 = ''; var i,j; // Ignore the preformatted version of "1e-2" if (String(num).indexOf('e') > 0) { return String(prepend + String(num) + append); } // We need then number as a string num = String(num); // Take off the decimal part - we re-append it later if (num.indexOf('.') > 0) { num = num.replace(/\.(.*)/, ''); decimal = RegExp.$1; } // Thousand seperator //var seperator = arguments[1] ? String(arguments[1]) : ','; var seperator = thousand_seperator; /** * Work backwards adding the thousand seperators */ var foundPoint; for (i=(num.length - 1),j=0; i>=0; j++,i--) { var character = num.charAt(i); if ( j % 3 == 0 && j != 0) { output += seperator; } /** * Build the output */ output += character; } /** * Now need to reverse the string */ var rev = output; output = ''; for (i=(rev.length - 1); i>=0; i--) { output += rev.charAt(i); } // Tidy up output = output.replace(/^-,/, '-'); // Reappend the decimal if (decimal.length) { output = output + decimal_seperator + decimal; decimal = ''; RegExp.$1 = ''; } // Minor bugette if (output.charAt(0) == '-') { output *= -1; prepend = '-' + prepend; } return prepend + output + append; } /** * Draws horizontal coloured bars on something like the bar, line or scatter */ RGraph.DrawBars = function (obj) { var hbars = obj.Get('chart.background.hbars'); /** * Draws a horizontal bar */ obj.context.beginPath(); for (i=0; i<hbars.length; ++i) { // If null is specified as the "height", set it to the upper max value if (hbars[i][1] == null) { hbars[i][1] = obj.max; // If the first index plus the second index is greater than the max value, adjust accordingly } else if (hbars[i][0] + hbars[i][1] > obj.max) { hbars[i][1] = obj.max - hbars[i][0]; } // If height is negative, and the abs() value is greater than .max, use a negative max instead if (Math.abs(hbars[i][1]) > obj.max) { hbars[i][1] = -1 * obj.max; } // If start point is greater than max, change it to max if (Math.abs(hbars[i][0]) > obj.max) { hbars[i][0] = obj.max; } // If start point plus height is less than negative max, use the negative max plus the start point if (hbars[i][0] + hbars[i][1] < (-1 * obj.max) ) { hbars[i][1] = -1 * (obj.max + hbars[i][0]); } // If the X axis is at the bottom, and a negative max is given, warn the user if (obj.Get('chart.xaxispos') == 'bottom' && (hbars[i][0] < 0 || (hbars[i][1] + hbars[i][1] < 0)) ) { alert('[' + obj.type.toUpperCase() + ' (ID: ' + obj.id + ') BACKGROUND HBARS] You have a negative value in one of your background hbars values, whilst the X axis is in the center'); } var ystart = (obj.grapharea - ((hbars[i][0] / obj.max) * obj.grapharea)); var height = (Math.min(hbars[i][1], obj.max - hbars[i][0]) / obj.max) * obj.grapharea; // Account for the X axis being in the center if (obj.Get('chart.xaxispos') == 'center') { ystart /= 2; height /= 2; } ystart += obj.Get('chart.gutter') var x = obj.Get('chart.gutter'); var y = ystart - height; var w = obj.canvas.width - (2 * obj.Get('chart.gutter')); var h = height; // Accommodate Opera :-/ if (navigator.userAgent.indexOf('Opera') != -1 && obj.Get('chart.xaxispos') == 'center' && h < 0) { h *= -1; y = y - h; } obj.context.fillStyle = hbars[i][2]; obj.context.fillRect(x, y, w, h); } obj.context.fill(); } /** * Draws in-graph labels. * * @param object obj The graph object */ RGraph.DrawInGraphLabels = function (obj) { var canvas = obj.canvas; var context = obj.context; var labels = obj.Get('chart.labels.ingraph'); var labels_processed = []; // Defaults var fgcolor = 'black'; var bgcolor = 'white'; var direction = 1; if (!labels) { return; } /** * Preprocess the labels array. Numbers are expanded */ for (var i=0; i<labels.length; ++i) { if (typeof(labels[i]) == 'number') { for (var j=0; j<labels[i]; ++j) { labels_processed.push(null); } } else if (typeof(labels[i]) == 'string' || typeof(labels[i]) == 'object') { labels_processed.push(labels[i]); } else { labels_processed.push(''); } } /** * Turn off any shadow */ RGraph.NoShadow(obj); if (labels_processed && labels_processed.length > 0) { for (var i=0; i<labels_processed.length; ++i) { if (labels_processed[i]) { var coords = obj.coords[i]; if (coords && coords.length > 0) { var x = (obj.type == 'bar' ? coords[0] + (coords[2] / 2) : coords[0]); var y = (obj.type == 'bar' ? coords[1] + (coords[3] / 2) : coords[1]); var length = typeof(labels_processed[i][4]) == 'number' ? labels_processed[i][4] : 25; context.beginPath(); context.fillStyle = 'black'; context.strokeStyle = 'black'; if (obj.type == 'bar') { if (obj.Get('chart.variant') == 'dot') { context.moveTo(x, obj.coords[i][1] - 5); context.lineTo(x, obj.coords[i][1] - 5 - length); var text_x = x; var text_y = obj.coords[i][1] - 5 - length; } else if (obj.Get('chart.variant') == 'arrow') { context.moveTo(x, obj.coords[i][1] - 5); context.lineTo(x, obj.coords[i][1] - 5 - length); var text_x = x; var text_y = obj.coords[i][1] - 5 - length; } else { context.arc(x, y, 2.5, 0, 6.28, 0); context.moveTo(x, y); context.lineTo(x, y - length); var text_x = x; var text_y = y - length; } context.stroke(); context.fill(); } else if (obj.type == 'line') { if ( typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][3]) == 'number' && labels_processed[i][3] == -1 ) { context.moveTo(x, y + 5); context.lineTo(x, y + 5 + length); context.stroke(); context.beginPath(); // This draws the arrow context.moveTo(x, y + 5); context.lineTo(x - 3, y + 10); context.lineTo(x + 3, y + 10); context.closePath(); var text_x = x; var text_y = y + 5 + length; } else { var text_x = x; var text_y = y - 5 - length; context.moveTo(x, y - 5); context.lineTo(x, y - 5 - length); context.stroke(); context.beginPath(); // This draws the arrow context.moveTo(x, y - 5); context.lineTo(x - 3, y - 10); context.lineTo(x + 3, y - 10); context.closePath(); } context.fill(); } // Taken out on the 10th Nov 2010 - unnecessary //var width = context.measureText(labels[i]).width; context.beginPath(); // Fore ground color context.fillStyle = (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][1]) == 'string') ? labels_processed[i][1] : 'black'; RGraph.Text(context, obj.Get('chart.text.font'), obj.Get('chart.text.size'), text_x, text_y, (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][0]) == 'string') ? labels_processed[i][0] : labels_processed[i], 'bottom', 'center', true, null, (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][2]) == 'string') ? labels_processed[i][2] : 'white'); context.fill(); } } } } } /** * This function "fills in" key missing properties that various implementations lack * * @param object e The event object */ RGraph.FixEventObject = function (e) { if (RGraph.isIE8()) { var e = event; e.pageX = (event.clientX + document.body.scrollLeft); e.pageY = (event.clientY + document.body.scrollTop); e.target = event.srcElement; if (!document.body.scrollTop && document.documentElement.scrollTop) { e.pageX += parseInt(document.documentElement.scrollLeft); e.pageY += parseInt(document.documentElement.scrollTop); } } // This is mainly for FF which doesn't provide offsetX if (typeof(e.offsetX) == 'undefined' && typeof(e.offsetY) == 'undefined') { var coords = RGraph.getMouseXY(e); e.offsetX = coords[0]; e.offsetY = coords[1]; } // Any browser that doesn't implement stopPropagation() (MSIE) if (!e.stopPropagation) { e.stopPropagation = function () {window.event.cancelBubble = true;} } return e; } /** * Draw crosshairs if enabled * * @param object obj The graph object (from which we can get the context and canvas as required) */ RGraph.DrawCrosshairs = function (obj) { if (obj.Get('chart.crosshairs')) { var canvas = obj.canvas; var context = obj.context; // 5th November 2010 - removed now that tooltips are DOM2 based. //if (obj.Get('chart.tooltips') && obj.Get('chart.tooltips').length > 0) { //alert('[' + obj.type.toUpperCase() + '] Sorry - you cannot have crosshairs enabled with tooltips! Turning off crosshairs...'); //obj.Set('chart.crosshairs', false); //return; //} canvas.onmousemove = function (e) { var e = RGraph.FixEventObject(e); var canvas = obj.canvas; var context = obj.context; var gutter = obj.Get('chart.gutter'); var width = canvas.width; var height = canvas.height; var adjustments = obj.Get('chart.tooltips.coords.adjust'); var mouseCoords = RGraph.getMouseXY(e); var x = mouseCoords[0]; var y = mouseCoords[1]; if (typeof(adjustments) == 'object' && adjustments[0] && adjustments[1]) { x = x - adjustments[0]; y = y - adjustments[1]; } RGraph.Clear(canvas); obj.Draw(); if ( x >= gutter && y >= gutter && x <= (width - gutter) && y <= (height - gutter) ) { var linewidth = obj.Get('chart.crosshairs.linewidth'); context.lineWidth = linewidth ? linewidth : 1; context.beginPath(); context.strokeStyle = obj.Get('chart.crosshairs.color'); // Draw a top vertical line context.moveTo(x, gutter); context.lineTo(x, height - gutter); // Draw a horizontal line context.moveTo(gutter, y); context.lineTo(width - gutter, y); context.stroke(); /** * Need to show the coords? */ if (obj.Get('chart.crosshairs.coords')) { if (obj.type == 'scatter') { var xCoord = (((x - obj.Get('chart.gutter')) / (obj.canvas.width - (2 * obj.Get('chart.gutter')))) * (obj.Get('chart.xmax') - obj.Get('chart.xmin'))) + obj.Get('chart.xmin'); xCoord = xCoord.toFixed(obj.Get('chart.scale.decimals')); var yCoord = obj.max - (((y - obj.Get('chart.gutter')) / (obj.canvas.height - (2 * obj.Get('chart.gutter')))) * obj.max); if (obj.type == 'scatter' && obj.Get('chart.xaxispos') == 'center') { yCoord = (yCoord - (obj.max / 2)) * 2; } yCoord = yCoord.toFixed(obj.Get('chart.scale.decimals')); var div = RGraph.Registry.Get('chart.coordinates.coords.div'); var mouseCoords = RGraph.getMouseXY(e); var canvasXY = RGraph.getCanvasXY(canvas); if (!div) { div = document.createElement('DIV'); div.__object__ = obj; div.style.position = 'absolute'; div.style.backgroundColor = 'white'; div.style.border = '1px solid black'; div.style.fontFamily = 'Arial, Verdana, sans-serif'; div.style.fontSize = '10pt' div.style.padding = '2px'; div.style.opacity = 1; div.style.WebkitBorderRadius = '3px'; div.style.borderRadius = '3px'; div.style.MozBorderRadius = '3px'; document.body.appendChild(div); RGraph.Registry.Set('chart.coordinates.coords.div', div); } // Convert the X/Y pixel coords to correspond to the scale div.style.opacity = 1; div.style.display = 'inline'; if (!obj.Get('chart.crosshairs.coords.fixed')) { div.style.left = Math.max(2, (e.pageX - div.offsetWidth - 3)) + 'px'; div.style.top = Math.max(2, (e.pageY - div.offsetHeight - 3)) + 'px'; } else { div.style.left = canvasXY[0] + obj.Get('chart.gutter') + 3 + 'px'; div.style.top = canvasXY[1] + obj.Get('chart.gutter') + 3 + 'px'; } div.innerHTML = '<span style="color: #666">' + obj.Get('chart.crosshairs.coords.labels.x') + ':</span> ' + xCoord + '<br><span style="color: #666">' + obj.Get('chart.crosshairs.coords.labels.y') + ':</span> ' + yCoord; canvas.addEventListener('mouseout', RGraph.HideCrosshairCoords, false); } else { alert('[RGRAPH] Showing crosshair coordinates is only supported on the Scatter chart'); } } } else { RGraph.HideCrosshairCoords(); } } } } /** * Thisz function hides the crosshairs coordinates */ RGraph.HideCrosshairCoords = function () { var div = RGraph.Registry.Get('chart.coordinates.coords.div'); if ( div && div.style.opacity == 1 && div.__object__.Get('chart.crosshairs.coords.fadeout') ) { setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.9;}, 50); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.8;}, 100); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.7;}, 150); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.6;}, 200); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.5;}, 250); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.4;}, 300); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.3;}, 350); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.2;}, 400); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.1;}, 450); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0;}, 500); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.display = 'none';}, 550); } } /** * Trims the right hand side of a string. Removes SPACE, TAB * CR and LF. * * @param string str The string to trim */ RGraph.rtrim = function (str) { return str.replace(/( |\n|\r|\t)+$/, ''); } /** * Draws the3D axes/background */ RGraph.Draw3DAxes = function (obj) { var gutter = obj.Get('chart.gutter'); var context = obj.context; var canvas = obj.canvas; context.strokeStyle = '#aaa'; context.fillStyle = '#ddd'; // Draw the vertical left side context.beginPath(); context.moveTo(gutter, gutter); context.lineTo(gutter + 10, gutter - 5); context.lineTo(gutter + 10, canvas.height - gutter - 5); context.lineTo(gutter, canvas.height - gutter); context.closePath(); context.stroke(); context.fill(); // Draw the bottom floor context.beginPath(); context.moveTo(gutter, canvas.height - gutter); context.lineTo(gutter + 10, canvas.height - gutter - 5); context.lineTo(canvas.width - gutter + 10, canvas.height - gutter - 5); context.lineTo(canvas.width - gutter, canvas.height - gutter); context.closePath(); context.stroke(); context.fill(); } /** * Turns off any shadow * * @param object obj The graph object */ RGraph.NoShadow = function (obj) { obj.context.shadowColor = 'rgba(0,0,0,0)'; obj.context.shadowBlur = 0; obj.context.shadowOffsetX = 0; obj.context.shadowOffsetY = 0; } /** * Sets the four shadow properties - a shortcut function * * @param object obj Your graph object * @param string color The shadow color * @param number offsetx The shadows X offset * @param number offsety The shadows Y offset * @param number blur The blurring effect applied to the shadow */ RGraph.SetShadow = function (obj, color, offsetx, offsety, blur) { obj.context.shadowColor = color; obj.context.shadowOffsetX = offsetx; obj.context.shadowOffsetY = offsety; obj.context.shadowBlur = blur; } /** * This function attempts to "fill in" missing functions from the canvas * context object. Only two at the moment - measureText() nd fillText(). * * @param object context The canvas 2D context */ RGraph.OldBrowserCompat = function (context) { if (!context.measureText) { // This emulates the measureText() function context.measureText = function (text) { var textObj = document.createElement('DIV'); textObj.innerHTML = text; textObj.style.backgroundColor = 'white'; textObj.style.position = 'absolute'; textObj.style.top = -100 textObj.style.left = 0; document.body.appendChild(textObj); var width = {width: textObj.offsetWidth}; textObj.style.display = 'none'; return width; } } if (!context.fillText) { // This emulates the fillText() method context.fillText = function (text, targetX, targetY) { return false; } } // If IE8, add addEventListener() if (!context.canvas.addEventListener) { window.addEventListener = function (ev, func, bubble) { return this.attachEvent('on' + ev, func); } context.canvas.addEventListener = function (ev, func, bubble) { return this.attachEvent('on' + ev, func); } } } /** * This function is for use with circular graph types, eg the Pie or Radar. Pass it your event object * and it will pass you back the corresponding segment details as an array: * * [x, y, r, startAngle, endAngle] * * Angles are measured in degrees, and are measured from the "east" axis (just like the canvas). * * @param object e Your event object */ RGraph.getSegment = function (e) { RGraph.FixEventObject(e); // The optional arg provides a way of allowing some accuracy (pixels) var accuracy = arguments[1] ? arguments[1] : 0; var obj = e.target.__object__; var canvas = obj.canvas; var context = obj.context; var mouseCoords = RGraph.getMouseXY(e); var x = mouseCoords[0] - obj.centerx; var y = mouseCoords[1] - obj.centery; var r = obj.radius; var theta = Math.atan(y / x); // RADIANS var hyp = y / Math.sin(theta); var angles = obj.angles; var ret = []; var hyp = (hyp < 0) ? hyp + accuracy : hyp - accuracy; // Put theta in DEGREES theta *= 57.3 // hyp should not be greater than radius if it's a Rose chart if (obj.type == 'rose') { if ( (isNaN(hyp) && Math.abs(mouseCoords[0]) < (obj.centerx - r) ) || (isNaN(hyp) && Math.abs(mouseCoords[0]) > (obj.centerx + r)) || (!isNaN(hyp) && Math.abs(hyp) > r)) { return; } } /** * Account for the correct quadrant */ if (x < 0 && y >= 0) { theta += 180; } else if (x < 0 && y < 0) { theta += 180; } else if (x > 0 && y < 0) { theta += 360; } /** * Account for the rose chart */ if (obj.type == 'rose') { theta += 90; } if (theta > 360) { theta -= 360; } for (var i=0; i<angles.length; ++i) { if (theta >= angles[i][0] && theta < angles[i][1]) { hyp = Math.abs(hyp); if (obj.type == 'rose' && hyp > angles[i][2]) { return null; } if (!hyp || (obj.type == 'pie' && obj.radius && hyp > obj.radius) ) { return null; } if (obj.type == 'pie' && obj.Get('chart.variant') == 'donut' && (hyp > obj.radius || hyp < (obj.radius / 2) ) ) { return null; } ret[0] = obj.centerx; ret[1] = obj.centery; ret[2] = (obj.type == 'rose') ? angles[i][2] : obj.radius; ret[3] = angles[i][0]; ret[4] = angles[i][1]; ret[5] = i; if (obj.type == 'rose') { ret[3] -= 90; ret[4] -= 90; if (x > 0 && y < 0) { ret[3] += 360; ret[4] += 360; } } if (ret[3] < 0) ret[3] += 360; if (ret[4] > 360) ret[4] -= 360; return ret; } } return null; } /** * This is a function that can be used to run code asynchronously, which can * be used to speed up the loading of you pages. * * @param string func This is the code to run. It can also be a function pointer. * The front page graphs show this function in action. Basically * each graphs code is made in a function, and that function is * passed to this function to run asychronously. */ RGraph.Async = function (func) { return setTimeout(func, arguments[1] ? arguments[1] : 1); } /** * A custom random number function * * @param number min The minimum that the number should be * @param number max The maximum that the number should be * @param number How many decimal places there should be. Default for this is 0 */ RGraph.random = function (min, max) { var dp = arguments[2] ? arguments[2] : 0; var r = Math.random(); return Number((((max - min) * r) + min).toFixed(dp)); } /** * Draws a rectangle with curvy corners * * @param context object The context * @param x number The X coordinate (top left of the square) * @param y number The Y coordinate (top left of the square) * @param w number The width of the rectangle * @param h number The height of the rectangle * @param number The radius of the curved corners * @param boolean Whether the top left corner is curvy * @param boolean Whether the top right corner is curvy * @param boolean Whether the bottom right corner is curvy * @param boolean Whether the bottom left corner is curvy */ RGraph.strokedCurvyRect = function (context, x, y, w, h) { // The corner radius var r = arguments[5] ? arguments[5] : 3; // The corners var corner_tl = (arguments[6] || arguments[6] == null) ? true : false; var corner_tr = (arguments[7] || arguments[7] == null) ? true : false; var corner_br = (arguments[8] || arguments[8] == null) ? true : false; var corner_bl = (arguments[9] || arguments[9] == null) ? true : false; context.beginPath(); // Top left side context.moveTo(x + (corner_tl ? r : 0), y); context.lineTo(x + w - (corner_tr ? r : 0), y); // Top right corner if (corner_tr) { context.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2, false); } // Top right side context.lineTo(x + w, y + h - (corner_br ? r : 0) ); // Bottom right corner if (corner_br) { context.arc(x + w - r, y - r + h, r, Math.PI * 2, Math.PI * 0.5, false); } // Bottom right side context.lineTo(x + (corner_bl ? r : 0), y + h); // Bottom left corner if (corner_bl) { context.arc(x + r, y - r + h, r, Math.PI * 0.5, Math.PI, false); } // Bottom left side context.lineTo(x, y + (corner_tl ? r : 0) ); // Top left corner if (corner_tl) { context.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5, false); } context.stroke(); } /** * Draws a filled rectangle with curvy corners * * @param context object The context * @param x number The X coordinate (top left of the square) * @param y number The Y coordinate (top left of the square) * @param w number The width of the rectangle * @param h number The height of the rectangle * @param number The radius of the curved corners * @param boolean Whether the top left corner is curvy * @param boolean Whether the top right corner is curvy * @param boolean Whether the bottom right corner is curvy * @param boolean Whether the bottom left corner is curvy */ RGraph.filledCurvyRect = function (context, x, y, w, h) { // The corner radius var r = arguments[5] ? arguments[5] : 3; // The corners var corner_tl = (arguments[6] || arguments[6] == null) ? true : false; var corner_tr = (arguments[7] || arguments[7] == null) ? true : false; var corner_br = (arguments[8] || arguments[8] == null) ? true : false; var corner_bl = (arguments[9] || arguments[9] == null) ? true : false; context.beginPath(); // First draw the corners // Top left corner if (corner_tl) { context.moveTo(x + r, y + r); context.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI, false); } else { context.fillRect(x, y, r, r); } // Top right corner if (corner_tr) { context.moveTo(x + w - r, y + r); context.arc(x + w - r, y + r, r, 1.5 * Math.PI, 0, false); } else { context.moveTo(x + w - r, y); context.fillRect(x + w - r, y, r, r); } // Bottom right corner if (corner_br) { context.moveTo(x + w - r, y + h - r); context.arc(x + w - r, y - r + h, r, 0, Math.PI / 2, false); } else { context.moveTo(x + w - r, y + h - r); context.fillRect(x + w - r, y + h - r, r, r); } // Bottom left corner if (corner_bl) { context.moveTo(x + r, y + h - r); context.arc(x + r, y - r + h, r, Math.PI / 2, Math.PI, false); } else { context.moveTo(x, y + h - r); context.fillRect(x, y + h - r, r, r); } // Now fill it in context.fillRect(x + r, y, w - r - r, h); context.fillRect(x, y + r, r + 1, h - r - r); context.fillRect(x + w - r - 1, y + r, r + 1, h - r - r); context.fill(); } /** * A crude timing function * * @param string label The label to use for the time */ RGraph.Timer = function (label) { var d = new Date(); // This uses the Firebug console console.log(label + ': ' + d.getSeconds() + '.' + d.getMilliseconds()); } /** * Hides the palette if it's visible */ RGraph.HidePalette = function () { var div = RGraph.Registry.Get('palette'); if (typeof(div) == 'object' && div) { div.style.visibility = 'hidden'; div.style.display = 'none'; RGraph.Registry.Set('palette', null); } } /** * Hides the zoomed canvas */ RGraph.HideZoomedCanvas = function () { if (typeof(__zoomedimage__) == 'object') { obj = __zoomedimage__.obj; } else { return; } if (obj.Get('chart.zoom.fade.out')) { for (var i=10,j=1; i>=0; --i, ++j) { if (typeof(__zoomedimage__) == 'object') { setTimeout("__zoomedimage__.style.opacity = " + String(i / 10), j * 30); } } if (typeof(__zoomedbackground__) == 'object') { setTimeout("__zoomedbackground__.style.opacity = " + String(i / 10), j * 30); } } if (typeof(__zoomedimage__) == 'object') { setTimeout("__zoomedimage__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? 310 : 0); } if (typeof(__zoomedbackground__) == 'object') { setTimeout("__zoomedbackground__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? 310 : 0); } } /** * Adds an event handler * * @param object obj The graph object * @param string event The name of the event, eg ontooltip * @param object func The callback function */ RGraph.AddCustomEventListener = function (obj, name, func) { if (typeof(RGraph.events[obj.id]) == 'undefined') { RGraph.events[obj.id] = []; } RGraph.events[obj.id].push([obj, name, func]); } /** * Used to fire one of the RGraph custom events * * @param object obj The graph object that fires the event * @param string event The name of the event to fire */ RGraph.FireCustomEvent = function (obj, name) { for (i in RGraph.events) { if (typeof(i) == 'string' && i == obj.id && RGraph.events[i].length > 0) { for(var j=0; j<RGraph.events[i].length; ++j) { if (RGraph.events[i][j][1] == name) { RGraph.events[i][j][2](obj); } } } } } /** * Checks the browser for traces of MSIE8 */ RGraph.isIE8 = function () { return navigator.userAgent.indexOf('MSIE 8') > 0; } /** * Checks the browser for traces of MSIE9 */ RGraph.isIE9 = function () { return navigator.userAgent.indexOf('MSIE 9') > 0; } /** * Checks the browser for traces of MSIE9 */ RGraph.isIE9up = function () { navigator.userAgent.match(/MSIE (\d+)/); return Number(RegExp.$1) >= 9; } /** * This clears a canvases event handlers. * * @param string id The ID of the canvas whose event handlers will be cleared */ RGraph.ClearEventListeners = function (id) { for (var i=0; i<RGraph.Registry.Get('chart.event.handlers').length; ++i) { var el = RGraph.Registry.Get('chart.event.handlers')[i]; if (el && (el[0] == id || el[0] == ('window_' + id)) ) { if (el[0].substring(0, 7) == 'window_') { window.removeEventListener(el[1], el[2], false); } else { document.getElementById(id).removeEventListener(el[1], el[2], false); } RGraph.Registry.Get('chart.event.handlers')[i] = null; } } } /** * */ RGraph.AddEventListener = function (id, e, func) { RGraph.Registry.Get('chart.event.handlers').push([id, e, func]); } /** * This function suggests a gutter size based on the widest left label. Given that the bottom * labels may be longer, this may be a little out. * * @param object obj The graph object * @param array data An array of graph data * @return int A suggested gutter setting */ RGraph.getGutterSuggest = function (obj, data) { var str = RGraph.number_format(obj, RGraph.array_max(RGraph.getScale(RGraph.array_max(data), obj)), obj.Get('chart.units.pre'), obj.Get('chart.units.post')); // Take into account the HBar if (obj.type == 'hbar') { var str = ''; var len = 0; for (var i=0; i<obj.Get('chart.labels').length; ++i) { str = (obj.Get('chart.labels').length > str.length ? obj.Get('chart.labels')[i] : str); } } obj.context.font = obj.Get('chart.text.size') + 'pt ' + obj.Get('chart.text.font'); len = obj.context.measureText(str).width + 5; return (obj.type == 'hbar' ? len / 3 : len); } /** * A basic Array shift gunction * * @param object The numerical array to work on * @return The new array */ RGraph.array_shift = function (arr) { var ret = []; for (var i=1; i<arr.length; ++i) ret.push(arr[i]); return ret; } /** * If you prefer, you can use the SetConfig() method to set the configuration information * for your chart. You may find that setting the configuration this way eases reuse. * * @param object obj The graph object * @param object config The graph configuration information */ RGraph.SetConfig = function (obj, config) { for (i in config) { if (typeof(i) == 'string') { obj.Set(i, config[i]); } } return obj; } /** * This function gets the canvas height. Defaults to the actual * height but this can be changed by setting chart.height. * * @param object obj The graph object */ RGraph.GetHeight = function (obj) { var height = obj.Get('chart.height'); return height ? height : obj.canvas.height; } /** * This function gets the canvas width. Defaults to the actual * width but this can be changed by setting chart.width. * * @param object obj The graph object */ RGraph.GetWidth = function (obj) { var width = obj.Get('chart.width'); return width ? width : obj.canvas.width; }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ if (typeof(RGraph) == 'undefined') RGraph = {}; /** * The scatter graph constructor * * @param object canvas The cxanvas object * @param array data The chart data */ RGraph.Scatter = function (id, data) { // Get the canvas and context objects this.id = id; this.canvas = document.getElementById(id); this.canvas.__object__ = this; this.context = this.canvas.getContext ? this.canvas.getContext("2d") : null; this.max = 0; this.coords = []; this.data = []; this.type = 'scatter'; this.isRGraph = true; /** * Compatibility with older browsers */ RGraph.OldBrowserCompat(this.context); // Various config properties this.properties = { 'chart.background.barcolor1': 'white', 'chart.background.barcolor2': 'white', 'chart.background.grid': true, 'chart.background.grid.width': 1, 'chart.background.grid.color': '#ddd', 'chart.background.grid.hsize': 20, 'chart.background.grid.vsize': 20, 'chart.background.hbars': null, 'chart.background.vbars': null, 'chart.background.grid.vlines': true, 'chart.background.grid.hlines': true, 'chart.background.grid.border': true, 'chart.background.grid.autofit':false, 'chart.background.grid.autofit.numhlines': 7, 'chart.background.grid.autofit.numvlines': 20, 'chart.text.size': 10, 'chart.text.angle': 0, 'chart.text.color': 'black', 'chart.text.font': 'Verdana', 'chart.tooltips.effect': 'fade', 'chart.tooltips.hotspot': 3, 'chart.tooltips.css.class': 'RGraph_tooltip', 'chart.tooltips.highlight': true, 'chart.tooltips.coords.adjust': [0,0], 'chart.units.pre': '', 'chart.units.post': '', 'chart.tickmarks': 'cross', 'chart.ticksize': 5, 'chart.xticks': true, 'chart.xaxis': true, 'chart.gutter': 25, 'chart.xmax': 0, 'chart.ymax': null, 'chart.ymin': null, 'chart.scale.decimals': null, 'chart.scale.point': '.', 'chart.scale.thousand': ',', 'chart.title': '', 'chart.title.background': null, 'chart.title.hpos': null, 'chart.title.vpos': null, 'chart.title.xaxis': '', 'chart.title.yaxis': '', 'chart.title.xaxis.pos': 0.25, 'chart.title.yaxis.pos': 0.25, 'chart.labels': [], 'chart.ylabels': true, 'chart.ylabels.count': 5, 'chart.contextmenu': null, 'chart.defaultcolor': 'black', 'chart.xaxispos': 'bottom', 'chart.yaxispos': 'left', 'chart.noendxtick': false, 'chart.crosshairs': false, 'chart.crosshairs.color': '#333', 'chart.crosshairs.linewidth': 1, 'chart.crosshairs.coords': false, 'chart.crosshairs.coords.fixed':true, 'chart.crosshairs.coords.fadeout':false, 'chart.crosshairs.coords.labels.x': 'X', 'chart.crosshairs.coords.labels.y': 'Y', 'chart.annotatable': false, 'chart.annotate.color': 'black', 'chart.line': false, 'chart.line.linewidth': 1, 'chart.line.colors': ['green', 'red'], 'chart.line.shadow.color': 'rgba(0,0,0,0)', 'chart.line.shadow.blur': 2, 'chart.line.shadow.offsetx': 3, 'chart.line.shadow.offsety': 3, 'chart.line.stepped': false, 'chart.noaxes': false, 'chart.key': [], 'chart.key.background': 'white', 'chart.key.position': 'graph', 'chart.key.shadow': false, 'chart.key.shadow.color': '#666', 'chart.key.shadow.blur': 3, 'chart.key.shadow.offsetx': 2, 'chart.key.shadow.offsety': 2, 'chart.key.position.gutter.boxed': true, 'chart.key.position.x': null, 'chart.key.position.y': null, 'chart.key.color.shape': 'square', 'chart.key.rounded': true, 'chart.axis.color': 'black', 'chart.zoom.factor': 1.5, 'chart.zoom.fade.in': true, 'chart.zoom.fade.out': true, 'chart.zoom.hdir': 'right', 'chart.zoom.vdir': 'down', 'chart.zoom.frames': 10, 'chart.zoom.delay': 50, 'chart.zoom.shadow': true, 'chart.zoom.mode': 'canvas', 'chart.zoom.thumbnail.width': 75, 'chart.zoom.thumbnail.height': 75, 'chart.zoom.background': true, 'chart.zoom.action': 'zoom', 'chart.boxplot.width': 8, 'chart.resizable': false, 'chart.xmin': 0 } // Handle multiple datasets being given as one argument if (arguments[1][0] && arguments[1][0][0] && typeof(arguments[1][0][0][0]) == 'number') { // Store the data set(s) for (var i=0; i<arguments[1].length; ++i) { this.data[i] = arguments[1][i]; } // Handle multiple data sets being supplied as seperate arguments } else { // Store the data set(s) for (var i=1; i<arguments.length; ++i) { this.data[i - 1] = arguments[i]; } } // Check for support if (!this.canvas) { alert('[SCATTER] No canvas support'); return; } // Check the common library has been included if (typeof(RGraph) == 'undefined') { alert('[SCATTER] Fatal error: The common library does not appear to have been included'); } } /** * A simple setter * * @param string name The name of the property to set * @param string value The value of the property */ RGraph.Scatter.prototype.Set = function (name, value) { /** * This is here because the key expects a name of "chart.colors" */ if (name == 'chart.line.colors') { this.properties['chart.colors'] = value; } /** * Allow compatibility with older property names */ if (name == 'chart.tooltip.hotspot') { name = 'chart.tooltips.hotspot'; } /** * chart.yaxispos should be left or right */ if (name == 'chart.yaxispos' && value != 'left' && value != 'right') { alert("[SCATTER] chart.yaxispos should be left or right. You've set it to: '" + value + "' Changing it to left"); value = 'left'; } this.properties[name.toLowerCase()] = value; } /** * A simple getter * * @param string name The name of the property to set */ RGraph.Scatter.prototype.Get = function (name) { return this.properties[name]; } /** * The function you call to draw the line chart */ RGraph.Scatter.prototype.Draw = function () { /** * Fire the onbeforedraw event */ RGraph.FireCustomEvent(this, 'onbeforedraw'); /** * Clear all of this canvases event handlers (the ones installed by RGraph) */ RGraph.ClearEventListeners(this.id); // Go through all the data points and see if a tooltip has been given this.Set('chart.tooltips', false); this.hasTooltips = false; var overHotspot = false; // Reset the coords array this.coords = []; if (!RGraph.isIE8()) { for (var i=0; i<this.data.length; ++i) { for (var j =0;j<this.data[i].length; ++j) { if (this.data[i][j] && this.data[i][j][3] && typeof(this.data[i][j][3]) == 'string' && this.data[i][j][3].length) { this.Set('chart.tooltips', [1]); // An array this.hasTooltips = true; } } } } // Reset the maximum value this.max = 0; // Work out the maximum Y value if (this.Get('chart.ymax') && this.Get('chart.ymax') > 0) { this.scale = []; this.max = this.Get('chart.ymax'); this.min = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; this.scale[0] = ((this.max - this.min) * (1/5)) + this.min; this.scale[1] = ((this.max - this.min) * (2/5)) + this.min; this.scale[2] = ((this.max - this.min) * (3/5)) + this.min; this.scale[3] = ((this.max - this.min) * (4/5)) + this.min; this.scale[4] = ((this.max - this.min) * (5/5)) + this.min; var decimals = this.Get('chart.scale.decimals'); this.scale = [ Number(this.scale[0]).toFixed(decimals), Number(this.scale[1]).toFixed(decimals), Number(this.scale[2]).toFixed(decimals), Number(this.scale[3]).toFixed(decimals), Number(this.scale[4]).toFixed(decimals) ]; } else { var i = 0; var j = 0; for (i=0; i<this.data.length; ++i) { for (j=0; j<this.data[i].length; ++j) { this.max = Math.max(this.max, typeof(this.data[i][j][1]) == 'object' ? RGraph.array_max(this.data[i][j][1]) : Math.abs(this.data[i][j][1])); } } this.scale = RGraph.getScale(this.max, this); this.max = this.scale[4]; this.min = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; if (this.min) { this.scale[0] = ((this.max - this.min) * (1/5)) + this.min; this.scale[1] = ((this.max - this.min) * (2/5)) + this.min; this.scale[2] = ((this.max - this.min) * (3/5)) + this.min; this.scale[3] = ((this.max - this.min) * (4/5)) + this.min; this.scale[4] = ((this.max - this.min) * (5/5)) + this.min; } if (typeof(this.Get('chart.scale.decimals')) == 'number') { var decimals = this.Get('chart.scale.decimals'); this.scale = [ Number(this.scale[0]).toFixed(decimals), Number(this.scale[1]).toFixed(decimals), Number(this.scale[2]).toFixed(decimals), Number(this.scale[3]).toFixed(decimals), Number(this.scale[4]).toFixed(decimals) ]; } } this.grapharea = this.canvas.height - (2 * this.Get('chart.gutter')); // Progressively Draw the chart RGraph.background.Draw(this); /** * Draw any horizontal bars that have been specified */ if (this.Get('chart.background.hbars') && this.Get('chart.background.hbars').length) { RGraph.DrawBars(this); } /** * Draw any vertical bars that have been specified */ if (this.Get('chart.background.vbars') && this.Get('chart.background.vbars').length) { this.DrawVBars(); } if (!this.Get('chart.noaxes')) { this.DrawAxes(); } this.DrawLabels(); i = 0; for(i=0; i<this.data.length; ++i) { this.DrawMarks(i); // Set the shadow this.context.shadowColor = this.Get('chart.line.shadow.color'); this.context.shadowOffsetX = this.Get('chart.line.shadow.offsetx'); this.context.shadowOffsetY = this.Get('chart.line.shadow.offsety'); this.context.shadowBlur = this.Get('chart.line.shadow.blur'); this.DrawLine(i); // Turn the shadow off RGraph.NoShadow(this); } if (this.Get('chart.line')) { for (var i=0;i<this.data.length; ++i) { this.DrawMarks(i); // Call this again so the tickmarks appear over the line } } /** * Setup the context menu if required */ if (this.Get('chart.contextmenu')) { RGraph.ShowContext(this); } /** * Install the event handler for tooltips */ if (this.hasTooltips) { /** * Register all charts */ RGraph.Register(this); var overHotspot = false; var canvas_onmousemove_func = function (e) { e = RGraph.FixEventObject(e); var canvas = e.target; var obj = canvas.__object__; var context = canvas.getContext('2d'); var mouseCoords = RGraph.getMouseXY(e); var overHotspot = false; /** * Now loop through each point comparing the coords */ var offset = obj.Get('chart.tooltips.hotspot'); // This is how far the hotspot extends for (var set=0; set<obj.coords.length; ++set) { for (var i=0; i<obj.coords[set].length; ++i) { var adjust = obj.Get('chart.tooltips.coords.adjust'); var xCoord = obj.coords[set][i][0] + adjust[0]; var yCoord = obj.coords[set][i][1] + adjust[1]; var tooltip = obj.coords[set][i][2]; if (mouseCoords[0] <= (xCoord + offset) && mouseCoords[0] >= (xCoord - offset) && mouseCoords[1] <= (yCoord + offset) && mouseCoords[1] >= (yCoord - offset) && tooltip && tooltip.length > 0) { overHotspot = true; canvas.style.cursor = 'pointer'; if ( !RGraph.Registry.Get('chart.tooltip') || RGraph.Registry.Get('chart.tooltip').__text__ != tooltip || RGraph.Registry.Get('chart.tooltip').__index__ != i || RGraph.Registry.Get('chart.tooltip').__dataset__ != set ) { if (obj.Get('chart.tooltips.highlight')) { RGraph.Redraw(); } /** * Get the tooltip text */ if (typeof(tooltip) == 'function') { var text = String(tooltip(i)); } else { var text = String(tooltip); } RGraph.Tooltip(canvas, text, e.pageX, e.pageY, i); RGraph.Registry.Get('chart.tooltip').__dataset__ = set; /** * Draw a circle around the mark */ if (obj.Get('chart.tooltips.highlight')) { context.beginPath(); context.fillStyle = 'rgba(255,255,255,0.5)'; context.arc(xCoord, yCoord, 3, 0, 6.28, 0); context.fill(); } } } } } /** * Reset the pointer */ if (!overHotspot) { canvas.style.cursor = 'default'; } } this.canvas.addEventListener('mousemove', canvas_onmousemove_func, false); RGraph.AddEventListener(this.id, 'mousemove', canvas_onmousemove_func); } /** * Draw the key if necessary */ if (this.Get('chart.key') && this.Get('chart.key').length) { RGraph.DrawKey(this, this.Get('chart.key'), this.Get('chart.line.colors')); } /** * Draw crosschairs */ RGraph.DrawCrosshairs(this); /** * If the canvas is annotatable, do install the event handlers */ if (this.Get('chart.annotatable')) { RGraph.Annotate(this); } /** * This bit shows the mini zoom window if requested */ if (this.Get('chart.zoom.mode') == 'thumbnail' || this.Get('chart.zoom.mode') == 'area') { RGraph.ShowZoomWindow(this); } /** * This function enables resizing */ if (this.Get('chart.resizable')) { RGraph.AllowResizing(this); } /** * Fire the RGraph ondraw event */ RGraph.FireCustomEvent(this, 'ondraw'); } /** * Draws the axes of the scatter graph */ RGraph.Scatter.prototype.DrawAxes = function () { var canvas = this.canvas; var context = this.context; var graphHeight = this.canvas.height - (this.Get('chart.gutter') * 2); var gutter = this.Get('chart.gutter'); context.beginPath(); context.strokeStyle = this.Get('chart.axis.color'); context.lineWidth = 1; // Draw the Y axis if (this.Get('chart.yaxispos') == 'left') { context.moveTo(gutter, gutter); context.lineTo(gutter, this.canvas.height - gutter); } else { context.moveTo(canvas.width - gutter, gutter); context.lineTo(canvas.width - gutter, canvas.height - gutter); } // Draw the X axis if (this.Get('chart.xaxis')) { if (this.Get('chart.xaxispos') == 'center') { context.moveTo(gutter, canvas.height / 2); context.lineTo(canvas.width - gutter, canvas.height / 2); } else { context.moveTo(gutter, canvas.height - gutter); context.lineTo(canvas.width - gutter, canvas.height - gutter); } } /** * Draw the Y tickmarks */ for (y=gutter; y < canvas.height - gutter + (this.Get('chart.xaxispos') == 'center' ? 1 : 0) ; y+=(graphHeight / 5) / 2) { // This is here to accomodate the X axis being at the center if (y == (canvas.height / 2) ) continue; if (this.Get('chart.yaxispos') == 'left') { context.moveTo(gutter, y); context.lineTo(gutter - 3, y); } else { context.moveTo(canvas.width - gutter +3, y); context.lineTo(canvas.width - gutter, y); } } /** * Draw the X tickmarks */ if (this.Get('chart.xticks') && this.Get('chart.xaxis')) { var x = 0; var y = (this.Get('chart.xaxispos') == 'center') ? (this.canvas.height / 2) : (this.canvas.height - gutter); this.xTickGap = (this.canvas.width - (2 * gutter) ) / this.Get('chart.labels').length; for (x = (gutter + (this.Get('chart.yaxispos') == 'left' ? this.xTickGap / 2 : 0) ); x<=(canvas.width - gutter - (this.Get('chart.yaxispos') == 'left' ? 0 : 1)); x += this.xTickGap / 2) { if (this.Get('chart.yaxispos') == 'left' && this.Get('chart.noendxtick') == true && x == (canvas.width - gutter) ) { continue; } else if (this.Get('chart.yaxispos') == 'right' && this.Get('chart.noendxtick') == true && x == gutter) { continue; } context.moveTo(x, y - (this.Get('chart.xaxispos') == 'center' ? 3 : 0)); context.lineTo(x, y + 3); } } context.stroke(); } /** * Draws the labels on the scatter graph */ RGraph.Scatter.prototype.DrawLabels = function () { this.context.fillStyle = this.Get('chart.text.color'); var font = this.Get('chart.text.font'); var xMin = this.Get('chart.xmin'); var xMax = this.Get('chart.xmax'); var yMax = this.scale[4]; var gutter = this.Get('chart.gutter'); var text_size = this.Get('chart.text.size'); var units_pre = this.Get('chart.units.pre'); var units_post = this.Get('chart.units.post'); var numYLabels = this.Get('chart.ylabels.count'); var context = this.context; var canvas = this.canvas; this.halfTextHeight = text_size / 2; this.halfGraphHeight = (this.canvas.height - (2 * this.Get('chart.gutter'))) / 2; /** * Draw the Y yaxis labels, be it at the top or center */ if (this.Get('chart.ylabels')) { var xPos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : canvas.width - gutter + 5; var align = this.Get('chart.yaxispos') == 'right' ? 'left' : 'right'; if (this.Get('chart.xaxispos') == 'center') { /** * Specific Y labels */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); for (var i=0; i<this.Get('chart.ylabels.specific').length; ++i) { var y = gutter + (i * (this.grapharea / (labels.length * 2) ) ); RGraph.Text(context, font, text_size, xPos, y, labels[i], 'center', align); } var reversed_labels = RGraph.array_reverse(labels); for (var i=0; i<reversed_labels.length; ++i) { var y = gutter + (this.grapharea / 2) + ((i+1) * (this.grapharea / (labels.length * 2) ) ); RGraph.Text(context, font, text_size, xPos, y, reversed_labels[i], 'center', align); } return; } if (numYLabels == 1 || numYLabels == 3 || numYLabels == 5) { // Draw the top halves labels RGraph.Text(context, font, text_size, xPos, gutter, RGraph.number_format(this, this.scale[4], units_pre, units_post), 'center', align); if (numYLabels >= 5) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (1/10) ), RGraph.number_format(this, this.scale[3], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (3/10) ), RGraph.number_format(this, this.scale[1], units_pre, units_post), 'center', align); } if (numYLabels >= 3) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (2/10) ), RGraph.number_format(this, this.scale[2], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (4/10) ), RGraph.number_format(this, this.scale[0], units_pre, units_post), 'center', align); } // Draw the bottom halves labels if (numYLabels >= 3) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (1/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[0], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (3/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[2], units_pre, units_post), 'center', align); } if (numYLabels == 5) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (2/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[1], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (4/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[3], units_pre, units_post), 'center', align); } RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (5/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[4], units_pre, units_post), 'center', align); } else if (numYLabels == 10) { // 10 Y labels var interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xPos,gutter + ((canvas.height - (2 * gutter)) * (i/20) ),RGraph.number_format(this, (this.max - (this.max * (i/10))).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post),'center', align); RGraph.Text(context, font, text_size, xPos,gutter + ((canvas.height - (2 * gutter)) * (i/20) ) + (this.grapharea / 2) + (this.grapharea / 20),'-' + RGraph.number_format(this, ((this.max * (i/10)) + (this.max * (1/10))).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align); } } else { alert('[SCATTER SCALE] Number of Y labels can be 1/3/5/10 only'); } } else { var xPos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : canvas.width - gutter + 5; var align = this.Get('chart.yaxispos') == 'right' ? 'left' : 'right'; /** * Specific Y labels */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); for (var i=0; i<this.Get('chart.ylabels.specific').length; ++i) { var y = gutter + (i * (this.grapharea / labels.length) ); RGraph.Text(context, font, text_size, xPos, y, labels[i], 'center', align); } return; } if (numYLabels == 1 || numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xPos, gutter, RGraph.number_format(this, this.scale[4], units_pre, units_post), 'center', align); if (numYLabels >= 5) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (1/5) ), RGraph.number_format(this, this.scale[3], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (3/5) ), RGraph.number_format(this, this.scale[1], units_pre, units_post), 'center', align); } if (numYLabels >= 3) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (2/5) ), RGraph.number_format(this, this.scale[2], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (4/5) ), RGraph.number_format(this, this.scale[0], units_pre, units_post), 'center', align); } } else if (numYLabels == 10) { // 10 Y labels var interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xPos,gutter + ((canvas.height - (2 * gutter)) * (i/10) ),RGraph.number_format(this,(this.max - (this.max * (i/10))).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align); } } else { alert('[SCATTER SCALE] Number of Y labels can be 1/3/5/10 only'); } if (this.Get('chart.ymin')) { RGraph.Text(context, font, text_size, xPos, canvas.height - gutter,RGraph.number_format(this, this.Get('chart.ymin').toFixed(this.Get('chart.scale.decimals')), units_pre, units_post),'center', align); } } } // Put the text on the X axis var graphArea = this.canvas.width - (2 * gutter); var xInterval = graphArea / this.Get('chart.labels').length; var xPos = gutter; var yPos = (this.canvas.height - gutter) + 15; var labels = this.Get('chart.labels'); /** * Text angle */ var angle = 0; var valign = null; var halign = 'center'; if (this.Get('chart.text.angle') > 0) { angle = -1 * this.Get('chart.text.angle'); valign = 'center'; halign = 'right'; yPos -= 10; } for (i=0; i<labels.length; ++i) { if (typeof(labels[i]) == 'object') { RGraph.Text(context, font, this.Get('chart.text.size'), gutter + (graphArea * ((labels[i][1] - xMin) / (this.Get('chart.xmax') - xMin))) + 5, yPos, String(labels[i][0]), valign, angle != 0 ? 'right' : 'left', null, angle); /** * Draw the gray indicator line */ this.context.beginPath(); this.context.strokeStyle = '#bbb'; this.context.moveTo(gutter + (graphArea * ((labels[i][1] - xMin)/ (this.Get('chart.xmax') - xMin))), this.canvas.height - gutter); this.context.lineTo(gutter + (graphArea * ((labels[i][1] - xMin)/ (this.Get('chart.xmax') - xMin))), this.canvas.height - gutter + 20); this.context.stroke(); } else { RGraph.Text(context, font, this.Get('chart.text.size'), xPos + (this.xTickGap / 2), yPos, String(labels[i]), valign, halign, null, angle); } // Do this for the next time around xPos += xInterval; } } /** * Draws the actual scatter graph marks * * @param i integer The dataset index */ RGraph.Scatter.prototype.DrawMarks = function (i) { /** * Reset the coords array */ this.coords[i] = []; /** * Plot the values */ var xmax = this.Get('chart.xmax'); var default_color = this.Get('chart.defaultcolor'); for (var j=0; j<this.data[i].length; ++j) { /** * This is here because tooltips are optional */ var data_point = this.data[i]; var xCoord = data_point[j][0]; var yCoord = data_point[j][1]; var color = data_point[j][2] ? data_point[j][2] : default_color; var tooltip = (data_point[j] && data_point[j][3]) ? data_point[j][3] : null; this.DrawMark( i, xCoord, yCoord, xmax, this.scale[4], color, tooltip, this.coords[i], data_point ); } } /** * Draws a single scatter mark */ RGraph.Scatter.prototype.DrawMark = function (index, x, y, xMax, yMax, color, tooltip, coords, data) { var tickmarks = this.Get('chart.tickmarks'); var tickSize = this.Get('chart.ticksize'); var gutter = this.Get('chart.gutter'); var xMin = this.Get('chart.xmin'); var x = ((x - xMin) / (xMax - xMin)) * (this.canvas.width - (2 * gutter)); var originalX = x; var originalY = y; /** * This allows chart.tickmarks to be an array */ if (tickmarks && typeof(tickmarks) == 'object') { tickmarks = tickmarks[index]; } /** * This allows chart.ticksize to be an array */ if (typeof(tickSize) == 'object') { var tickSize = tickSize[index]; var halfTickSize = tickSize / 2; } else { var halfTickSize = tickSize / 2; } /** * This bit is for boxplots only */ if ( typeof(y) == 'object' && typeof(y[0]) == 'number' && typeof(y[1]) == 'number' && typeof(y[2]) == 'number' && typeof(y[3]) == 'number' && typeof(y[4]) == 'number' ) { var yMin = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; this.Set('chart.boxplot', true); this.graphheight = this.canvas.height - (2 * gutter); if (this.Get('chart.xaxispos') == 'center') { this.graphheight /= 2; } var y0 = (this.graphheight) - ((y[4] - yMin) / (yMax - yMin)) * (this.graphheight); var y1 = (this.graphheight) - ((y[3] - yMin) / (yMax - yMin)) * (this.graphheight); var y2 = (this.graphheight) - ((y[2] - yMin) / (yMax - yMin)) * (this.graphheight); var y3 = (this.graphheight) - ((y[1] - yMin) / (yMax - yMin)) * (this.graphheight); var y4 = (this.graphheight) - ((y[0] - yMin) / (yMax - yMin)) * (this.graphheight); var col1 = y[5]; var col2 = y[6]; // Override the boxWidth if (typeof(y[7]) == 'number') { var boxWidth = y[7]; } var y = this.graphheight - y2; } else { var yMin = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; var y = (( (y - yMin) / (yMax - yMin)) * (this.canvas.height - (2 * gutter))); } /** * Account for the X axis being at the centre */ if (this.Get('chart.xaxispos') == 'center') { y /= 2; y += this.halfGraphHeight; } // This is so that points are on the graph, and not the gutter x += gutter; y = this.canvas.height - gutter - y; this.context.beginPath(); // Color this.context.strokeStyle = color; /** * Boxplots */ if ( this.Get('chart.boxplot') && typeof(y0) == 'number' && typeof(y1) == 'number' && typeof(y2) == 'number' && typeof(y3) == 'number' && typeof(y4) == 'number' ) { var boxWidth = boxWidth ? boxWidth : this.Get('chart.boxplot.width'); var halfBoxWidth = boxWidth / 2; this.context.beginPath(); // Draw the upper coloured box if a value is specified if (col1) { this.context.fillStyle = col1; this.context.fillRect(x - halfBoxWidth, y1 + gutter, boxWidth, y2 - y1); } // Draw the lower coloured box if a value is specified if (col2) { this.context.fillStyle = col2; this.context.fillRect(x - halfBoxWidth, y2 + gutter, boxWidth, y3 - y2); } this.context.strokeRect(x - halfBoxWidth, y1 + gutter, boxWidth, y3 - y1); this.context.stroke(); // Now draw the whiskers this.context.beginPath(); this.context.moveTo(x - halfBoxWidth, y0 + gutter); this.context.lineTo(x + halfBoxWidth, y0 + gutter); this.context.moveTo(x, y0 + gutter); this.context.lineTo(x, y1 + gutter); this.context.moveTo(x - halfBoxWidth, y4 + gutter); this.context.lineTo(x + halfBoxWidth, y4 + gutter); this.context.moveTo(x, y4 + gutter); this.context.lineTo(x, y3 + gutter); this.context.stroke(); } /** * Draw the tickmark, but not for boxplots */ if (!y0 && !y1 && !y2 && !y3 && !y4) { this.graphheight = this.canvas.height - (2 * gutter); if (tickmarks == 'circle') { this.context.arc(x, y, halfTickSize, 0, 6.28, 0); this.context.fillStyle = color; this.context.fill(); } else if (tickmarks == 'plus') { this.context.moveTo(x, y - halfTickSize); this.context.lineTo(x, y + halfTickSize); this.context.moveTo(x - halfTickSize, y); this.context.lineTo(x + halfTickSize, y); this.context.stroke(); } else if (tickmarks == 'square') { this.context.strokeStyle = color; this.context.fillStyle = color; this.context.fillRect( x - halfTickSize, y - halfTickSize, tickSize, tickSize ); //this.context.fill(); } else if (tickmarks == 'cross') { this.context.moveTo(x - halfTickSize, y - halfTickSize); this.context.lineTo(x + halfTickSize, y + halfTickSize); this.context.moveTo(x + halfTickSize, y - halfTickSize); this.context.lineTo(x - halfTickSize, y + halfTickSize); this.context.stroke(); /** * Diamond shape tickmarks */ } else if (tickmarks == 'diamond') { this.context.fillStyle = this.context.strokeStyle; this.context.moveTo(x, y - halfTickSize); this.context.lineTo(x + halfTickSize, y); this.context.lineTo(x, y + halfTickSize); this.context.lineTo(x - halfTickSize, y); this.context.lineTo(x, y - halfTickSize); this.context.fill(); this.context.stroke(); /** * Custom tickmark style */ } else if (typeof(tickmarks) == 'function') { var graphWidth = this.canvas.width - (2 * this.Get('chart.gutter')) var xVal = ((x - this.Get('chart.gutter')) / graphWidth) * xMax; var yVal = ((this.graphheight - (y - this.Get('chart.gutter'))) / this.graphheight) * yMax; tickmarks(this, data, x, y, xVal, yVal, xMax, yMax, color) /** * No tickmarks */ } else if (tickmarks == null) { /** * Unknown tickmark type */ } else { alert('[SCATTER] (' + this.id + ') Unknown tickmark style: ' + tickmarks ); } } /** * Add the tickmark to the coords array */ coords.push([x, y, tooltip]); } /** * Draws an optional line connecting the tick marks. * * @param i The index of the dataset to use */ RGraph.Scatter.prototype.DrawLine = function (i) { if (this.Get('chart.line') && this.coords[i].length >= 2) { this.context.lineCap = 'round'; this.context.lineJoin = 'round'; this.context.lineWidth = this.GetLineWidth(i);// i is the index of the set of coordinates this.context.strokeStyle = this.Get('chart.line.colors')[i]; this.context.beginPath(); var len = this.coords[i].length; for (var j=0; j<this.coords[i].length; ++j) { var xPos = this.coords[i][j][0]; var yPos = this.coords[i][j][1]; if (j == 0) { this.context.moveTo(xPos, yPos); } else { // Stepped? var stepped = this.Get('chart.line.stepped'); if ( (typeof(stepped) == 'boolean' && stepped) || (typeof(stepped) == 'object' && stepped[i]) ) { this.context.lineTo(this.coords[i][j][0], this.coords[i][j - 1][1]); } this.context.lineTo(xPos, yPos); } } this.context.stroke(); } /** * Set the linewidth back to 1 */ this.context.lineWidth = 1; } /** * Returns the linewidth * * @param number i The index of the "line" (/set of coordinates) */ RGraph.Scatter.prototype.GetLineWidth = function (i) { var linewidth = this.Get('chart.line.linewidth'); if (typeof(linewidth) == 'number') { return linewidth; } else if (typeof(linewidth) == 'object') { if (linewidth[i]) { return linewidth[i]; } else { return linewidth[0]; } alert('[SCATTER] Error! chart.linewidth should be a single number or an array of one or more numbers'); } } /** * Draws vertical bars. Line chart doesn't use a horizontal scale, hence this function * is not common */ RGraph.Scatter.prototype.DrawVBars = function () { var canvas = this.canvas; var context = this.context; var vbars = this.Get('chart.background.vbars'); var gutter = this.Get('chart.gutter'); var graphWidth = canvas.width - gutter - gutter; if (vbars) { var xmax = this.Get('chart.xmax'); for (var i=0; i<vbars.length; ++i) { var startX = ((vbars[i][0] / xmax) * graphWidth) + gutter; var width = (vbars[i][1] / xmax) * graphWidth; context.beginPath(); context.fillStyle = vbars[i][2]; context.fillRect(startX, gutter, width, (canvas.height - gutter - gutter)); context.fill(); } } }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ if (typeof(RGraph) == 'undefined') RGraph = {isRGraph:true,type:'common'}; /** * This is used in two functions, hence it's here */ RGraph.tooltips = {}; RGraph.tooltips.padding = '3px'; RGraph.tooltips.font_face = 'Tahoma'; RGraph.tooltips.font_size = '10pt'; /** * Shows a tooltip next to the mouse pointer * * @param canvas object The canvas element object * @param text string The tooltip text * @param int x The X position that the tooltip should appear at. Combined with the canvases offsetLeft * gives the absolute X position * @param int y The Y position the tooltip should appear at. Combined with the canvases offsetTop * gives the absolute Y position * @param int idx The index of the tooltip in the graph objects tooltip array */ RGraph.Tooltip = function (canvas, text, x, y, idx) { /** * chart.tooltip.override allows you to totally take control of rendering the tooltip yourself */ if (typeof(canvas.__object__.Get('chart.tooltips.override')) == 'function') { return canvas.__object__.Get('chart.tooltips.override')(canvas, text, x, y, idx); } /** * This facilitates the "id:xxx" format */ text = RGraph.getTooltipText(text); /** * First clear any exising timers */ var timers = RGraph.Registry.Get('chart.tooltip.timers'); if (timers && timers.length) { for (i=0; i<timers.length; ++i) { clearTimeout(timers[i]); } } RGraph.Registry.Set('chart.tooltip.timers', []); /** * Hide the context menu if it's currently shown */ if (canvas.__object__.Get('chart.contextmenu')) { RGraph.HideContext(); } // Redraw the canvas? if (canvas.__object__.Get('chart.tooltips.highlight')) { RGraph.Redraw(canvas.id); } var effect = canvas.__object__.Get('chart.tooltips.effect').toLowerCase(); if (effect == 'snap' && RGraph.Registry.Get('chart.tooltip')) { if ( canvas.__object__.type == 'line' || canvas.__object__.type == 'tradar' || canvas.__object__.type == 'scatter' || canvas.__object__.type == 'rscatter' ) { var tooltipObj = RGraph.Registry.Get('chart.tooltip'); tooltipObj.style.width = null; tooltipObj.style.height = null; tooltipObj.innerHTML = text; tooltipObj.__text__ = text; /** * Now that the new content has been set, re-set the width & height */ RGraph.Registry.Get('chart.tooltip').style.width = RGraph.getTooltipWidth(text, canvas.__object__) + 'px'; RGraph.Registry.Get('chart.tooltip').style.height = RGraph.Registry.Get('chart.tooltip').offsetHeight - (RGraph.isIE9up() ? 7 : 0) + 'px'; var currentx = parseInt(RGraph.Registry.Get('chart.tooltip').style.left); var currenty = parseInt(RGraph.Registry.Get('chart.tooltip').style.top); var diffx = x - currentx - ((x + RGraph.Registry.Get('chart.tooltip').offsetWidth) > document.body.offsetWidth ? RGraph.Registry.Get('chart.tooltip').offsetWidth : 0); var diffy = y - currenty - RGraph.Registry.Get('chart.tooltip').offsetHeight; // Position the tooltip setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.2)) + 'px"', 25); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.4)) + 'px"', 50); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.6)) + 'px"', 75); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.8)) + 'px"', 100); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 1.0)) + 'px"', 125); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.2)) + 'px"', 25); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.4)) + 'px"', 50); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.6)) + 'px"', 75); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.8)) + 'px"', 100); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 1.0)) + 'px"', 125); } else { alert('[TOOLTIPS] The "snap" effect is only supported on the Line, Rscatter, Scatter and Tradar charts'); } /** * Fire the tooltip event */ RGraph.FireCustomEvent(canvas.__object__, 'ontooltip'); return; } /** * Hide any currently shown tooltip */ RGraph.HideTooltip(); /** * Show a tool tip */ var tooltipObj = document.createElement('DIV'); tooltipObj.className = canvas.__object__.Get('chart.tooltips.css.class'); tooltipObj.style.display = 'none'; tooltipObj.style.position = 'absolute'; tooltipObj.style.left = 0; tooltipObj.style.top = 0; tooltipObj.style.backgroundColor = '#ffe'; tooltipObj.style.color = 'black'; if (!document.all) tooltipObj.style.border = '1px solid rgba(0,0,0,0)'; tooltipObj.style.visibility = 'visible'; tooltipObj.style.paddingLeft = RGraph.tooltips.padding; tooltipObj.style.paddingRight = RGraph.tooltips.padding; tooltipObj.style.fontFamily = RGraph.tooltips.font_face; tooltipObj.style.fontSize = RGraph.tooltips.font_size; tooltipObj.style.zIndex = 3; tooltipObj.style.borderRadius = '5px'; tooltipObj.style.MozBorderRadius = '5px'; tooltipObj.style.WebkitBorderRadius = '5px'; tooltipObj.style.WebkitBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; tooltipObj.style.MozBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; tooltipObj.style.boxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; tooltipObj.style.filter = 'progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=135)'; tooltipObj.style.opacity = 0; tooltipObj.style.overflow = 'hidden'; tooltipObj.innerHTML = text; tooltipObj.__text__ = text; // This is set because the innerHTML can change when it's set tooltipObj.__canvas__ = canvas; tooltipObj.style.display = 'inline'; if (typeof(idx) == 'number') { tooltipObj.__index__ = idx; } document.body.appendChild(tooltipObj); var width = tooltipObj.offsetWidth; var height = tooltipObj.offsetHeight - (RGraph.isIE9up() ? 7 : 0); if ((y - height - 2) > 0) { y = y - height - 2; } else { y = y + 2; } /** * Set the width on the tooltip so it doesn't resize if the window is resized */ tooltipObj.style.width = width + 'px'; //tooltipObj.style.height = 0; // Initially set the tooltip height to nothing /** * If the mouse is towards the right of the browser window and the tooltip would go outside of the window, * move it left */ if ( (x + width) > document.body.offsetWidth ) { x = x - width - 7; var placementLeft = true; if (canvas.__object__.Get('chart.tooltips.effect') == 'none') { x = x - 3; } tooltipObj.style.left = x + 'px'; tooltipObj.style.top = y + 'px'; } else { x += 5; tooltipObj.style.left = x + 'px'; tooltipObj.style.top = y + 'px'; } if (effect == 'expand') { tooltipObj.style.left = (x + (width / 2)) + 'px'; tooltipObj.style.top = (y + (height / 2)) + 'px'; leftDelta = (width / 2) / 10; topDelta = (height / 2) / 10; tooltipObj.style.width = 0; tooltipObj.style.height = 0; tooltipObj.style.boxShadow = ''; tooltipObj.style.MozBoxShadow = ''; tooltipObj.style.WebkitBoxShadow = ''; tooltipObj.style.borderRadius = 0; tooltipObj.style.MozBorderRadius = 0; tooltipObj.style.WebkitBorderRadius = 0; tooltipObj.style.opacity = 1; // Progressively move the tooltip to where it should be (the x position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 250)); // Progressively move the tooltip to where it should be (the Y position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 250)); // Progressively grow the tooltip width RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.1) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.2) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.3) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.4) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.6) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.7) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.8) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.9) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + width + "px'; }", 250)); // Progressively grow the tooltip height RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.1) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.2) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.3) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.4) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.6) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.7) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.8) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.9) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + height + "px'; }", 250)); // When the animation is finished, set the tooltip HTML RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').innerHTML = RGraph.Registry.Get('chart.tooltip').__text__; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.boxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.borderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBorderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBorderRadius = '5px'; }", 250)); } else if (effect == 'contract') { tooltipObj.style.left = (x - width) + 'px'; tooltipObj.style.top = (y - (height * 2)) + 'px'; tooltipObj.style.cursor = 'pointer'; leftDelta = width / 10; topDelta = height / 10; tooltipObj.style.width = (width * 5) + 'px'; tooltipObj.style.height = (height * 5) + 'px'; tooltipObj.style.opacity = 0.2; // Progressively move the tooltip to where it should be (the x position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 250)); // Progressively move the tooltip to where it should be (the Y position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 250)); // Progressively shrink the tooltip width RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 5.5) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 5.0) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 4.5) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 4.0) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 3.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 3.0) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 2.5) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 2.0) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 1.5) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + width + "px'; }", 250)); // Progressively shrink the tooltip height RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 5.5) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 5.0) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 4.5) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 4.0) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 3.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 3.0) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 2.5) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 2.0) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 1.5) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + height + "px'; }", 250)); // When the animation is finished, set the tooltip HTML RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').innerHTML = RGraph.Registry.Get('chart.tooltip').__text__; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.boxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.borderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBorderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBorderRadius = '5px'; }", 250)); /** * This resets the pointer */ RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.cursor = 'default'; }", 275)); } else if (effect != 'fade' && effect != 'expand' && effect != 'none' && effect != 'snap' && effect != 'contract') { alert('[COMMON] Unknown tooltip effect: ' + effect); } if (effect != 'none') { setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.1; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 25); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.2; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 50); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.3; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 75); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.4; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 100); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.5; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 125); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.6; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 150); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.7; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.4)'; }", 175); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.8; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.6)'; }", 200); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.9; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.8)'; }", 225); } setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 1;RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgb(96,96,96)';}", effect == 'none' ? 50 : 250); /** * If the tooltip it self is clicked, cancel it */ tooltipObj.onmousedown = function (e) { e = RGraph.FixEventObject(e) e.stopPropagation(); } tooltipObj.onclick = function (e) { if (e.button == 0) { e = RGraph.FixEventObject(e); e.stopPropagation(); } } /** * Install the function for hiding the tooltip. */ document.body.onmousedown = function (event) { var tooltip = RGraph.Registry.Get('chart.tooltip'); if (tooltip) { RGraph.HideTooltip(); // Redraw if highlighting is enabled if (tooltip.__canvas__.__object__.Get('chart.tooltips.highlight')) { RGraph.Redraw(); } } } /** * If the window is resized, hide the tooltip */ window.onresize = function () { var tooltip = RGraph.Registry.Get('chart.tooltip'); if (tooltip) { tooltip.parentNode.removeChild(tooltip); tooltip.style.display = 'none'; tooltip.style.visibility = 'hidden'; RGraph.Registry.Set('chart.tooltip', null); // Redraw the graph if necessary if (canvas.__object__.Get('chart.tooltips.highlight')) { RGraph.Clear(canvas); canvas.__object__.Draw(); } } } /** * Keep a reference to the tooltip */ RGraph.Registry.Set('chart.tooltip', tooltipObj); /** * Fire the tooltip event */ RGraph.FireCustomEvent(canvas.__object__, 'ontooltip'); } /** * */ RGraph.getTooltipText = function (text) { var result = /^id:(.*)/.exec(text); if (result) { text = document.getElementById(result[1]).innerHTML; } return text; } /** * */ RGraph.getTooltipWidth = function (text, obj) { var div = document.createElement('DIV'); div.className = obj.Get('chart.tooltips.css.class'); div.style.paddingLeft = RGraph.tooltips.padding; div.style.paddingRight = RGraph.tooltips.padding; div.style.fontFamily = RGraph.tooltips.font_face; div.style.fontSize = RGraph.tooltips.font_size; div.style.visibility = 'hidden'; div.style.position = 'absolute'; div.style.top = '300px'; div.style.left = 0; div.style.display = 'inline'; div.innerHTML = RGraph.getTooltipText(text); document.body.appendChild(div); return div.offsetWidth; } /** * Hides the currently shown tooltip */ RGraph.HideTooltip = function () { var tooltip = RGraph.Registry.Get('chart.tooltip'); if (tooltip) { tooltip.parentNode.removeChild(tooltip); tooltip.style.display = 'none'; tooltip.style.visibility = 'hidden'; RGraph.Registry.Set('chart.tooltip', null); } }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ if (typeof(RGraph) == 'undefined') RGraph = {}; /** * The bar chart constructor * * @param object canvas The canvas object * @param array data The chart data */ RGraph.Bar = function (id, data) { // Get the canvas and context objects this.id = id; this.canvas = document.getElementById(id); this.context = this.canvas.getContext ? this.canvas.getContext("2d") : null; this.canvas.__object__ = this; this.type = 'bar'; this.max = 0; this.stackedOrGrouped = false; this.isRGraph = true; /** * Compatibility with older browsers */ RGraph.OldBrowserCompat(this.context); // Various config type stuff this.properties = { 'chart.background.barcolor1': 'rgba(0,0,0,0)', 'chart.background.barcolor2': 'rgba(0,0,0,0)', 'chart.background.grid': true, 'chart.background.grid.color': '#ddd', 'chart.background.grid.width': 1, 'chart.background.grid.hsize': 20, 'chart.background.grid.vsize': 20, 'chart.background.grid.vlines': true, 'chart.background.grid.hlines': true, 'chart.background.grid.border': true, 'chart.background.grid.autofit':false, 'chart.background.grid.autofit.numhlines': 7, 'chart.background.grid.autofit.numvlines': 20, 'chart.ytickgap': 20, 'chart.smallyticks': 3, 'chart.largeyticks': 5, 'chart.numyticks': 10, 'chart.hmargin': 5, 'chart.strokecolor': '#666', 'chart.axis.color': 'black', 'chart.gutter': 25, 'chart.labels': null, 'chart.labels.ingraph': null, 'chart.labels.above': false, 'chart.labels.above.decimals': 0, 'chart.labels.above.size': null, 'chart.ylabels': true, 'chart.ylabels.count': 5, 'chart.ylabels.inside': false, 'chart.xlabels.offset': 0, 'chart.xaxispos': 'bottom', 'chart.yaxispos': 'left', 'chart.text.color': 'black', 'chart.text.size': 10, 'chart.text.angle': 0, 'chart.text.font': 'Verdana', 'chart.ymax': null, 'chart.title': '', 'chart.title.background': null, 'chart.title.hpos': null, 'chart.title.vpos': null, 'chart.title.xaxis': '', 'chart.title.yaxis': '', 'chart.title.xaxis.pos': 0.25, 'chart.title.yaxis.pos': 0.25, 'chart.colors': ['rgb(0,0,255)', '#0f0', '#00f', '#ff0', '#0ff', '#0f0'], 'chart.grouping': 'grouped', 'chart.variant': 'bar', 'chart.shadow': false, 'chart.shadow.color': '#666', 'chart.shadow.offsetx': 3, 'chart.shadow.offsety': 3, 'chart.shadow.blur': 3, 'chart.tooltips': null, 'chart.tooltips.effect': 'fade', 'chart.tooltips.css.class': 'RGraph_tooltip', 'chart.tooltips.event': 'onclick', 'chart.tooltips.coords.adjust': [0,0], 'chart.tooltips.highlight': true, 'chart.background.hbars': null, 'chart.key': [], 'chart.key.background': 'white', 'chart.key.position': 'graph', 'chart.key.shadow': false, 'chart.key.shadow.color': '#666', 'chart.key.shadow.blur': 3, 'chart.key.shadow.offsetx': 2, 'chart.key.shadow.offsety': 2, 'chart.key.position.gutter.boxed': true, 'chart.key.position.x': null, 'chart.key.position.y': null, 'chart.key.color.shape': 'square', 'chart.key.rounded': true, 'chart.key.text.size': 10, 'chart.contextmenu': null, 'chart.line': null, 'chart.units.pre': '', 'chart.units.post': '', 'chart.scale.decimals': 0, 'chart.scale.point': '.', 'chart.scale.thousand': ',', 'chart.crosshairs': false, 'chart.crosshairs.color': '#333', 'chart.linewidth': 1, 'chart.annotatable': false, 'chart.annotate.color': 'black', 'chart.zoom.factor': 1.5, 'chart.zoom.fade.in': true, 'chart.zoom.fade.out': true, 'chart.zoom.hdir': 'right', 'chart.zoom.vdir': 'down', 'chart.zoom.frames': 10, 'chart.zoom.delay': 50, 'chart.zoom.shadow': true, 'chart.zoom.mode': 'canvas', 'chart.zoom.thumbnail.width': 75, 'chart.zoom.thumbnail.height': 75, 'chart.zoom.background': true, 'chart.resizable': false, 'chart.adjustable': false } // Check for support if (!this.canvas) { alert('[BAR] No canvas support'); return; } // Check the common library has been included if (typeof(RGraph) == 'undefined') { alert('[BAR] Fatal error: The common library does not appear to have been included'); } /** * Determine whether the chart will contain stacked or grouped bars */ for (i=0; i<data.length; ++i) { if (typeof(data[i]) == 'object') { this.stackedOrGrouped = true; } } // Store the data this.data = data; // Used to store the coords of the bars this.coords = []; } /** * A setter * * @param name string The name of the property to set * @param value mixed The value of the property */ RGraph.Bar.prototype.Set = function (name, value) { name = name.toLowerCase(); if (name == 'chart.labels.abovebar') { name = 'chart.labels.above'; } if (name == 'chart.strokestyle') { name = 'chart.strokecolor'; } this.properties[name] = value; } /** * A getter * * @param name string The name of the property to get */ RGraph.Bar.prototype.Get = function (name) { if (name == 'chart.labels.abovebar') { name = 'chart.labels.above'; } return this.properties[name]; } /** * The function you call to draw the bar chart */ RGraph.Bar.prototype.Draw = function () { /** * Fire the onbeforedraw event */ RGraph.FireCustomEvent(this, 'onbeforedraw'); /** * Clear all of this canvases event handlers (the ones installed by RGraph) */ RGraph.ClearEventListeners(this.id); /** * Convert any null values to 0. Won't make any difference to the bar (as opposed to the line chart) */ for (var i=0; i<this.data.length; ++i) { if (this.data[i] == null) { this.data[i] = 0; } } // Cache this in a class variable as it's used rather a lot this.gutter = this.Get('chart.gutter'); /** * Check for tooltips and alert the user that they're not supported with pyramid charts */ if ( (this.Get('chart.variant') == 'pyramid' || this.Get('chart.variant') == 'dot') && typeof(this.Get('chart.tooltips')) == 'object' && this.Get('chart.tooltips') && this.Get('chart.tooltips').length > 0) { alert('[BAR] (' + this.id + ') Sorry, tooltips are not supported with dot or pyramid charts'); } /** * Stop the coords array from growing uncontrollably */ this.coords = []; /** * Work out a few things. They need to be here because they depend on things you can change before you * call Draw() but after you instantiate the object */ this.max = 0; this.grapharea = this.canvas.height - ( (2 * this.gutter)); this.halfgrapharea = this.grapharea / 2; this.halfTextHeight = this.Get('chart.text.size') / 2; // Progressively Draw the chart RGraph.background.Draw(this); //If it's a sketch chart variant, draw the axes first if (this.Get('chart.variant') == 'sketch') { this.DrawAxes(); this.Drawbars(); } else { this.Drawbars(); this.DrawAxes(); } this.DrawLabels(); // Draw the key if necessary if (this.Get('chart.key').length) { RGraph.DrawKey(this, this.Get('chart.key'), this.Get('chart.colors')); } /** * Setup the context menu if required */ if (this.Get('chart.contextmenu')) { RGraph.ShowContext(this); } /** * Is a line is defined, draw it */ var line = this.Get('chart.line'); if (line) { // Check the length of the data(s) if (line.original_data[0].length != this.data.length) { alert("[BAR] You're adding a line with a differing amount of data points to the bar chart - this is not permitted"); } // Check the X axis positions if (this.Get('chart.xaxispos') != line.Get('chart.xaxispos')) { alert("[BAR] Using different X axis positions when combining the Bar and Line is not advised"); } line.Set('chart.gutter', this.Get('chart.gutter')); line.Set('chart.noaxes', true); line.Set('chart.background.barcolor1', 'rgba(0,0,0,0)'); line.Set('chart.background.barcolor2', 'rgba(0,0,0,0)'); line.Set('chart.background.grid', false); line.Set('chart.ylabels', false); line.Set('chart.hmargin', (this.canvas.width - (2 * this.gutter)) / (line.original_data[0].length * 2)); // If a custom yMax is set, use that if (this.Get('chart.ymax')) { line.Set('chart.ymax', this.Get('chart.ymax')); } line.Draw(); } /** * Draw "in graph" labels */ if (this.Get('chart.labels.ingraph')) { RGraph.DrawInGraphLabels(this); } /** * Draw crosschairs */ if (this.Get('chart.crosshairs')) { RGraph.DrawCrosshairs(this); } /** * If the canvas is annotatable, do install the event handlers */ if (this.Get('chart.annotatable')) { RGraph.Annotate(this); } /** * This bit shows the mini zoom window if requested */ if (this.Get('chart.zoom.mode') == 'thumbnail' || this.Get('chart.zoom.mode') == 'area') { RGraph.ShowZoomWindow(this); } /** * This function enables resizing */ if (this.Get('chart.resizable')) { RGraph.AllowResizing(this); } /** * This function enables adjusting */ if (this.Get('chart.adjustable')) { RGraph.AllowAdjusting(this); } /** * Fire the RGraph ondraw event */ RGraph.FireCustomEvent(this, 'ondraw'); } /** * Draws the charts axes */ RGraph.Bar.prototype.DrawAxes = function () { var gutter = this.gutter; var xaxispos = this.Get('chart.xaxispos'); var yaxispos = this.Get('chart.yaxispos'); this.context.beginPath(); this.context.strokeStyle = this.Get('chart.axis.color'); this.context.lineWidth = 1; // Draw the Y axis if (yaxispos == 'right') { this.context.moveTo(this.canvas.width - gutter, gutter); this.context.lineTo(this.canvas.width - gutter, this.canvas.height - gutter); } else { this.context.moveTo(gutter, gutter); this.context.lineTo(gutter, this.canvas.height - gutter); } // Draw the X axis this.context.moveTo(gutter, (xaxispos == 'center' ? this.canvas.height / 2 : this.canvas.height - gutter)); this.context.lineTo(this.canvas.width - gutter, xaxispos == 'center' ? this.canvas.height / 2 : this.canvas.height - gutter); var numYTicks = this.Get('chart.numyticks'); // Draw the Y tickmarks var yTickGap = (this.canvas.height - (2 * gutter)) / numYTicks; var xpos = yaxispos == 'left' ? gutter : this.canvas.width - gutter; for (y=gutter; xaxispos == 'center' ? y <= (this.canvas.height - gutter) : y < (this.canvas.height - gutter); y += yTickGap) { if (xaxispos == 'center' && y == (this.canvas.height / 2)) continue; this.context.moveTo(xpos, y); this.context.lineTo(xpos + (yaxispos == 'left' ? -3 : 3), y); } // Draw the X tickmarks xTickGap = (this.canvas.width - (2 * gutter) ) / this.data.length; yStart = this.canvas.height - gutter; yEnd = (this.canvas.height - gutter) + 3; //////////////// X TICKS //////////////// // Now move the Y start end positions down if the axis is set to center if (xaxispos == 'center') { yStart = (this.canvas.height / 2) + 3; yEnd = (this.canvas.height / 2) - 3; } for (x=gutter + (yaxispos == 'left' ? xTickGap : 0); x<this.canvas.width - gutter + (yaxispos == 'left' ? 5 : 0); x+=xTickGap) { this.context.moveTo(x, yStart); this.context.lineTo(x, yEnd); } //////////////// X TICKS //////////////// this.context.stroke(); } /** * Draws the bars */ RGraph.Bar.prototype.Drawbars = function () { this.context.lineWidth = this.Get('chart.linewidth'); this.context.strokeStyle = this.Get('chart.strokecolor'); this.context.fillStyle = this.Get('chart.colors')[0]; var prevX = 0; var prevY = 0; var gutter = this.gutter; var decimals = this.Get('chart.scale.decimals'); /** * Work out the max value */ if (this.Get('chart.ymax')) { this.max = this.Get('chart.ymax'); this.scale = [ (this.max * (1/5)).toFixed(decimals), (this.max * (2/5)).toFixed(decimals), (this.max * (3/5)).toFixed(decimals), (this.max * (4/5)).toFixed(decimals), this.max.toFixed(decimals) ]; } else { for (i=0; i<this.data.length; ++i) { if (typeof(this.data[i]) == 'object') { var value = this.Get('chart.grouping') == 'grouped' ? Number(RGraph.array_max(this.data[i], true)) : Number(RGraph.array_sum(this.data[i])) ; } else { var value = Number(this.data[i]); } this.max = Math.max(Math.abs(this.max), Math.abs(value)); } this.scale = RGraph.getScale(this.max, this); this.max = this.scale[4]; if (this.Get('chart.scale.decimals')) { var decimals = this.Get('chart.scale.decimals'); this.scale[0] = Number(this.scale[0]).toFixed(decimals); this.scale[1] = Number(this.scale[1]).toFixed(decimals); this.scale[2] = Number(this.scale[2]).toFixed(decimals); this.scale[3] = Number(this.scale[3]).toFixed(decimals); this.scale[4] = Number(this.scale[4]).toFixed(decimals); } } /** * Draw horizontal bars here */ if (this.Get('chart.background.hbars') && this.Get('chart.background.hbars').length > 0) { RGraph.DrawBars(this); } var variant = this.Get('chart.variant'); /** * Draw the 3D axes is necessary */ if (variant == '3d') { RGraph.Draw3DAxes(this); } /** * Get the variant once, and draw the bars, be they regular, stacked or grouped */ // Get these variables outside of the loop var xaxispos = this.Get('chart.xaxispos'); var width = (this.canvas.width - (2 * gutter) ) / this.data.length; var orig_height = height; var hmargin = this.Get('chart.hmargin'); var shadow = this.Get('chart.shadow'); var shadowColor = this.Get('chart.shadow.color'); var shadowBlur = this.Get('chart.shadow.blur'); var shadowOffsetX = this.Get('chart.shadow.offsetx'); var shadowOffsetY = this.Get('chart.shadow.offsety'); var strokeStyle = this.Get('chart.strokecolor'); var colors = this.Get('chart.colors'); for (i=0; i<this.data.length; ++i) { // Work out the height //The width is up outside the loop var height = (RGraph.array_sum(this.data[i]) / this.max) * (this.canvas.height - (2 * gutter) ); // Half the height if the Y axis is at the center if (xaxispos == 'center') { height /= 2; } var x = (i * width) + gutter; var y = xaxispos == 'center' ? (this.canvas.height / 2) - height : this.canvas.height - height - gutter; // Account for negative lengths - Some browsers (eg Chrome) don't like a negative value if (height < 0) { y += height; height = Math.abs(height); } /** * Turn on the shadow if need be */ if (shadow) { this.context.shadowColor = shadowColor; this.context.shadowBlur = shadowBlur; this.context.shadowOffsetX = shadowOffsetX; this.context.shadowOffsetY = shadowOffsetY; } /** * Draw the bar */ this.context.beginPath(); if (typeof(this.data[i]) == 'number') { var barWidth = width - (2 * hmargin); // Set the fill color this.context.strokeStyle = strokeStyle; this.context.fillStyle = colors[0]; if (variant == 'sketch') { this.context.lineCap = 'round'; var sketchOffset = 3; this.context.beginPath(); this.context.strokeStyle = colors[0]; // Left side this.context.moveTo(x + hmargin + 2, y + height - 2); this.context.lineTo(x + hmargin , y - 2); // The top this.context.moveTo(x + hmargin - 3, y + -2 + (this.data[i] < 0 ? height : 0)); this.context.bezierCurveTo(x + ((hmargin + width) * 0.33),y + 5 + (this.data[i] < 0 ? height - 10: 0),x + ((hmargin + width) * 0.66),y + 5 + (this.data[i] < 0 ? height - 10 : 0),x + hmargin + width + -1, y + 0 + (this.data[i] < 0 ? height : 0)); // The right side this.context.moveTo(x + hmargin + width - 2, y + -2); this.context.lineTo(x + hmargin + width - 3, y + height - 3); for (var r=0.2; r<=0.8; r+=0.2) { this.context.moveTo(x + hmargin + width + (r > 0.4 ? -1 : 3) - (r * width),y - 1); this.context.lineTo(x + hmargin + width - (r > 0.4 ? 1 : -1) - (r * width), y + height + (r == 0.2 ? 1 : -2)); } this.context.stroke(); // Regular bar } else if (variant == 'bar' || variant == '3d' || variant == 'glass') { if (document.all && shadow) { this.DrawIEShadow([x + hmargin, y, barWidth, height]); } if (variant == 'glass') { RGraph.filledCurvyRect(this.context, x + hmargin, y, barWidth, height, 3, this.data[i] > 0, this.data[i] > 0, this.data[i] < 0, this.data[i] < 0); RGraph.strokedCurvyRect(this.context, x + hmargin, y, barWidth, height, 3, this.data[i] > 0, this.data[i] > 0, this.data[i] < 0, this.data[i] < 0); } else { this.context.strokeRect(x + hmargin, y, barWidth, height); this.context.fillRect(x + hmargin, y, barWidth, height); } // This bit draws the text labels that appear above the bars if requested if (this.Get('chart.labels.above')) { // Turn off any shadow if (shadow) { RGraph.NoShadow(this); } var yPos = y - 3; // Account for negative bars if (this.data[i] < 0) { yPos += height + 6 + (this.Get('chart.text.size') - 4); } this.context.fillStyle = this.Get('chart.text.color'); RGraph.Text(this.context, this.Get('chart.text.font'), typeof(this.Get('chart.labels.above.size')) == 'number' ? this.Get('chart.labels.above.size') : this.Get('chart.text.size') - 3, x + hmargin + (barWidth / 2), yPos, RGraph.number_format(this, Number(this.data[i]).toFixed(this.Get('chart.labels.above.decimals')),this.Get('chart.units.pre'), this.Get('chart.units.post')), null, 'center'); } // 3D effect if (variant == '3d') { var prevStrokeStyle = this.context.strokeStyle; var prevFillStyle = this.context.fillStyle; // Draw the top this.context.beginPath(); this.context.moveTo(x + hmargin, y); this.context.lineTo(x + hmargin + 10, y - 5); this.context.lineTo(x + hmargin + 10 + barWidth, y - 5); this.context.lineTo(x + hmargin + barWidth, y); this.context.closePath(); this.context.stroke(); this.context.fill(); // Draw the right hand side this.context.beginPath(); this.context.moveTo(x + hmargin + barWidth, y); this.context.lineTo(x + hmargin + barWidth + 10, y - 5); this.context.lineTo(x + hmargin + barWidth + 10, y + height - 5); this.context.lineTo(x + hmargin + barWidth, y + height); this.context.closePath(); this.context.stroke(); this.context.fill(); // Draw the darker top section this.context.beginPath(); this.context.fillStyle = 'rgba(255,255,255,0.3)'; this.context.moveTo(x + hmargin, y); this.context.lineTo(x + hmargin + 10, y - 5); this.context.lineTo(x + hmargin + 10 + barWidth, y - 5); this.context.lineTo(x + hmargin + barWidth, y); this.context.lineTo(x + hmargin, y); this.context.closePath(); this.context.stroke(); this.context.fill(); // Draw the darker right side section this.context.beginPath(); this.context.fillStyle = 'rgba(0,0,0,0.4)'; this.context.moveTo(x + hmargin + barWidth, y); this.context.lineTo(x + hmargin + barWidth + 10, y - 5); this.context.lineTo(x + hmargin + barWidth + 10, y - 5 + height); this.context.lineTo(x + hmargin + barWidth, y + height); this.context.lineTo(x + hmargin + barWidth, y); this.context.closePath(); this.context.stroke(); this.context.fill(); this.context.strokeStyle = prevStrokeStyle; this.context.fillStyle = prevFillStyle; // Glass variant } else if (variant == 'glass') { var grad = this.context.createLinearGradient( x + hmargin, y, x + hmargin + (barWidth / 2), y ); grad.addColorStop(0, 'rgba(255,255,255,0.9)'); grad.addColorStop(1, 'rgba(255,255,255,0.5)'); this.context.beginPath(); this.context.fillStyle = grad; this.context.fillRect(x + hmargin + 2,y + (this.data[i] > 0 ? 2 : 0),(barWidth / 2) - 2,height - 2); this.context.fill(); } // Dot chart } else if (variant == 'dot') { this.context.beginPath(); this.context.moveTo(x + (width / 2), y); this.context.lineTo(x + (width / 2), y + height); this.context.stroke(); this.context.beginPath(); this.context.fillStyle = this.Get('chart.colors')[i]; this.context.arc(x + (width / 2), y + (this.data[i] > 0 ? 0 : height), 2, 0, 6.28, 0); // Set the colour for the dots this.context.fillStyle = this.Get('chart.colors')[0]; this.context.stroke(); this.context.fill(); // Pyramid chart } else if (variant == 'pyramid') { this.context.beginPath(); var startY = (this.Get('chart.xaxispos') == 'center' ? (this.canvas.height / 2) : (this.canvas.height - this.Get('chart.gutter'))); this.context.moveTo(x + hmargin, startY); this.context.lineTo( x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0) ); this.context.lineTo(x + hmargin + barWidth, startY); this.context.closePath(); this.context.stroke(); this.context.fill(); // Arrow chart } else if (variant == 'arrow') { var startY = (this.Get('chart.xaxispos') == 'center' ? (this.canvas.height / 2) : (this.canvas.height - this.gutter)); this.context.lineWidth = this.Get('chart.linewidth') ? this.Get('chart.linewidth') : 1; this.context.lineCap = 'round'; this.context.beginPath(); this.context.moveTo(x + hmargin + (barWidth / 2), startY); this.context.lineTo(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0)); this.context.arc(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0), 5, this.data[i] > 0 ? 0.78 : 5.6, this.data[i] > 0 ? 0.79 : 5.48, this.data[i] < 0); this.context.moveTo(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0)); this.context.arc(x + hmargin + (barWidth / 2), y + (this.Get('chart.xaxispos') == 'center' && (this.data[i] < 0) ? height : 0), 5, this.data[i] > 0 ? 2.355 : 4, this.data[i] > 0 ? 2.4 : 3.925, this.data[i] < 0); this.context.stroke(); this.context.lineWidth = 1; // Unknown variant type } else { alert('[BAR] Warning! Unknown chart.variant: ' + variant); } this.coords.push([x + hmargin, y, width - (2 * hmargin), height]); /** * Stacked bar */ } else if (typeof(this.data[i]) == 'object' && this.Get('chart.grouping') == 'stacked') { var barWidth = width - (2 * hmargin); var redrawCoords = [];// Necessary to draw if the shadow is enabled var startY = 0; for (j=0; j<this.data[i].length; ++j) { // Stacked bar chart and X axis pos in the middle - poitless since negative values are not permitted if (xaxispos == 'center') { alert("[BAR] It's fruitless having the X axis position at the center on a stacked bar chart."); return; } // Negative values not permitted for the stacked chart if (this.data[i][j] < 0) { alert('[BAR] Negative values are not permitted with a stacked bar chart. Try a grouped one instead.'); return; } // Set the fill and stroke colors this.context.strokeStyle = strokeStyle this.context.fillStyle = colors[j]; var height = (this.data[i][j] / this.max) * (this.canvas.height - (2 * this.gutter) ); // If the X axis pos is in the center, we need to half the height if (xaxispos == 'center') { height /= 2; } var totalHeight = (RGraph.array_sum(this.data[i]) / this.max) * (this.canvas.height - hmargin - (2 * this.gutter)); /** * Store the coords for tooltips */ this.coords.push([x + hmargin, y, width - (2 * hmargin), height]); // MSIE shadow if (document.all && shadow) { this.DrawIEShadow([x + hmargin, y, width - (2 * hmargin), height + 1]); } this.context.strokeRect(x + hmargin, y, width - (2 * hmargin), height); this.context.fillRect(x + hmargin, y, width - (2 * hmargin), height); if (j == 0) { var startY = y; var startX = x; } /** * Store the redraw coords if the shadow is enabled */ if (shadow) { redrawCoords.push([x + hmargin, y, width - (2 * hmargin), height, colors[j]]); } /** * Stacked 3D effect */ if (variant == '3d') { var prevFillStyle = this.context.fillStyle; var prevStrokeStyle = this.context.strokeStyle; // Draw the top side if (j == 0) { this.context.beginPath(); this.context.moveTo(startX + hmargin, y); this.context.lineTo(startX + 10 + hmargin, y - 5); this.context.lineTo(startX + 10 + barWidth + hmargin, y - 5); this.context.lineTo(startX + barWidth + hmargin, y); this.context.closePath(); this.context.fill(); this.context.stroke(); } // Draw the side section this.context.beginPath(); this.context.moveTo(startX + barWidth + hmargin, y); this.context.lineTo(startX + barWidth + hmargin + 10, y - 5); this.context.lineTo(startX + barWidth + + hmargin + 10, y - 5 + height); this.context.lineTo(startX + barWidth + hmargin , y + height); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the darker top side if (j == 0) { this.context.fillStyle = 'rgba(255,255,255,0.3)'; this.context.beginPath(); this.context.moveTo(startX + hmargin, y); this.context.lineTo(startX + 10 + hmargin, y - 5); this.context.lineTo(startX + 10 + barWidth + hmargin, y - 5); this.context.lineTo(startX + barWidth + hmargin, y); this.context.closePath(); this.context.fill(); this.context.stroke(); } // Draw the darker side section this.context.fillStyle = 'rgba(0,0,0,0.4)'; this.context.beginPath(); this.context.moveTo(startX + barWidth + hmargin, y); this.context.lineTo(startX + barWidth + hmargin + 10, y - 5); this.context.lineTo(startX + barWidth + + hmargin + 10, y - 5 + height); this.context.lineTo(startX + barWidth + hmargin , y + height); this.context.closePath(); this.context.fill(); this.context.stroke(); this.context.strokeStyle = prevStrokeStyle; this.context.fillStyle = prevFillStyle; } y += height; } // This bit draws the text labels that appear above the bars if requested if (this.Get('chart.labels.above')) { // Turn off any shadow RGraph.NoShadow(this); this.context.fillStyle = this.Get('chart.text.color'); RGraph.Text(this.context,this.Get('chart.text.font'),typeof(this.Get('chart.labels.above.size')) == 'number' ? this.Get('chart.labels.above.size') : this.Get('chart.text.size') - 3,startX + (barWidth / 2) + this.Get('chart.hmargin'),startY - (this.Get('chart.shadow') && this.Get('chart.shadow.offsety') < 0 ? 7 : 4),String(this.Get('chart.units.pre') + RGraph.array_sum(this.data[i]).toFixed(this.Get('chart.labels.above.decimals')) + this.Get('chart.units.post')),null,'center'); // Turn any shadow back on if (shadow) { this.context.shadowColor = shadowColor; this.context.shadowBlur = shadowBlur; this.context.shadowOffsetX = shadowOffsetX; this.context.shadowOffsetY = shadowOffsetY; } } /** * Redraw the bars if the shadow is enabled due to hem being drawn from the bottom up, and the * shadow spilling over to higher up bars */ if (shadow) { RGraph.NoShadow(this); for (k=0; k<redrawCoords.length; ++k) { this.context.strokeStyle = strokeStyle; this.context.fillStyle = redrawCoords[k][4]; this.context.strokeRect(redrawCoords[k][0], redrawCoords[k][1], redrawCoords[k][2], redrawCoords[k][3]); this.context.fillRect(redrawCoords[k][0], redrawCoords[k][1], redrawCoords[k][2], redrawCoords[k][3]); this.context.stroke(); this.context.fill(); } // Reset the redraw coords to be empty redrawCoords = []; } /** * Grouped bar */ } else if (typeof(this.data[i]) == 'object' && this.Get('chart.grouping') == 'grouped') { var redrawCoords = []; this.context.lineWidth = this.Get('chart.linewidth'); for (j=0; j<this.data[i].length; ++j) { // Set the fill and stroke colors this.context.strokeStyle = strokeStyle; this.context.fillStyle = colors[j]; var individualBarWidth = (width - (2 * hmargin)) / this.data[i].length; var height = (this.data[i][j] / this.max) * (this.canvas.height - (2 * this.gutter) ); // If the X axis pos is in the center, we need to half the height if (xaxispos == 'center') { height /= 2; } var startX = x + hmargin + (j * individualBarWidth); var startY = (xaxispos == 'bottom' ? this.canvas.height : (this.canvas.height / 2) + this.gutter) - this.gutter - height; // Account for a bug in chrome that doesn't allow negative heights if (height < 0) { startY += height; height = Math.abs(height); } /** * Draw MSIE shadow */ if (document.all && shadow) { this.DrawIEShadow([startX, startY, individualBarWidth, height]); } this.context.strokeRect(startX, startY, individualBarWidth, height); this.context.fillRect(startX, startY, individualBarWidth, height); y += height; // This bit draws the text labels that appear above the bars if requested if (this.Get('chart.labels.above')) { this.context.strokeStyle = 'rgba(0,0,0,0)'; // Turn off any shadow if (shadow) { RGraph.NoShadow(this); } var yPos = y - 3; // Account for negative bars if (this.data[i][j] < 0) { yPos += height + 6 + (this.Get('chart.text.size') - 4); } this.context.fillStyle = this.Get('chart.text.color'); RGraph.Text(this.context,this.Get('chart.text.font'),typeof(this.Get('chart.labels.above.size')) == 'number' ? this.Get('chart.labels.above.size') : this.Get('chart.text.size') - 3,startX + (individualBarWidth / 2),startY - 2,RGraph.number_format(this, this.data[i][j].toFixed(this.Get('chart.labels.above.decimals'))),null,'center'); // Turn any shadow back on if (shadow) { this.context.shadowColor = shadowColor; this.context.shadowBlur = shadowBlur; this.context.shadowOffsetX = shadowOffsetX; this.context.shadowOffsetY = shadowOffsetY; } } /** * Grouped 3D effect */ if (variant == '3d') { var prevFillStyle = this.context.fillStyle; var prevStrokeStyle = this.context.strokeStyle; // Draw the top side this.context.beginPath(); this.context.moveTo(startX, startY); this.context.lineTo(startX + 10, startY - 5); this.context.lineTo(startX + 10 + individualBarWidth, startY - 5); this.context.lineTo(startX + individualBarWidth, startY); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the side section this.context.beginPath(); this.context.moveTo(startX + individualBarWidth, startY); this.context.lineTo(startX + individualBarWidth + 10, startY - 5); this.context.lineTo(startX + individualBarWidth + 10, startY - 5 + height); this.context.lineTo(startX + individualBarWidth , startY + height); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the darker top side this.context.fillStyle = 'rgba(255,255,255,0.3)'; this.context.beginPath(); this.context.moveTo(startX, startY); this.context.lineTo(startX + 10, startY - 5); this.context.lineTo(startX + 10 + individualBarWidth, startY - 5); this.context.lineTo(startX + individualBarWidth, startY); this.context.closePath(); this.context.fill(); this.context.stroke(); // Draw the darker side section this.context.fillStyle = 'rgba(0,0,0,0.4)'; this.context.beginPath(); this.context.moveTo(startX + individualBarWidth, startY); this.context.lineTo(startX + individualBarWidth + 10, startY - 5); this.context.lineTo(startX + individualBarWidth + 10, startY - 5 + height); this.context.lineTo(startX + individualBarWidth , startY + height); this.context.closePath(); this.context.fill(); this.context.stroke(); this.context.strokeStyle = prevStrokeStyle; this.context.fillStyle = prevFillStyle; } this.coords.push([startX, startY, individualBarWidth, height]); // Facilitate shadows going to the left if (this.Get('chart.shadow')) { redrawCoords.push([startX, startY, individualBarWidth, height]); } } /** * Redraw the bar if shadows are going to the left */ if (redrawCoords.length) { RGraph.NoShadow(this); this.context.lineWidth = this.Get('chart.linewidth'); this.context.beginPath(); for (var j=0; j<redrawCoords.length; ++j) { this.context.fillStyle = this.Get('chart.colors')[j]; this.context.strokeStyle = this.Get('chart.strokecolor'); this.context.fillRect(redrawCoords[j][0], redrawCoords[j][1], redrawCoords[j][2], redrawCoords[j][3]); this.context.strokeRect(redrawCoords[j][0], redrawCoords[j][1], redrawCoords[j][2], redrawCoords[j][3]); } this.context.fill(); this.context.stroke(); redrawCoords = []; } } this.context.closePath(); } /** * Turn off any shadow */ RGraph.NoShadow(this); /** * Install the onclick event handler */ if (this.Get('chart.tooltips')) { // Need to register this object for redrawing RGraph.Register(this); /** * Install the window onclick handler */ var window_onclick_func = function (){RGraph.Redraw();}; window.addEventListener('click', window_onclick_func, false); RGraph.AddEventListener('window_' + this.id, 'click', window_onclick_func); /** * If the cursor is over a hotspot, change the cursor to a hand. Bar chart tooltips can now * be based around the onmousemove event */ canvas_onmousemove = function (e) { e = RGraph.FixEventObject(e); var canvas = document.getElementById(e.target.id); var obj = canvas.__object__; var barCoords = obj.getBar(e); /** * If there are bar coords AND the bar has height */ if (barCoords && barCoords[4] > 0) { /** * Get the tooltip text */ if (typeof(obj.Get('chart.tooltips')) == 'function') { var text = String(obj.Get('chart.tooltips')(barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'function') { var text = String(obj.Get('chart.tooltips')[barCoords[5]](barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && (typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'string' || typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'number')) { var text = String(obj.Get('chart.tooltips')[barCoords[5]]); } else { var text = null; } if (text) { canvas.style.cursor = 'pointer'; } else { canvas.style.cursor = 'default'; } /** * Hide the currently displayed tooltip if the index is the same */ if ( RGraph.Registry.Get('chart.tooltip') && RGraph.Registry.Get('chart.tooltip').__canvas__.id != obj.id && obj.Get('chart.tooltips.event') == 'onmousemove') { RGraph.Redraw(); RGraph.HideTooltip(); } /** * This facilitates the tooltips using the onmousemove event */ if ( obj.Get('chart.tooltips.event') == 'onmousemove' && ( (RGraph.Registry.Get('chart.tooltip') && RGraph.Registry.Get('chart.tooltip').__index__ != barCoords[5]) || !RGraph.Registry.Get('chart.tooltip') ) && text) { /** * Show a tooltip if it's defined */ RGraph.Redraw(obj); obj.context.beginPath(); obj.context.strokeStyle = 'black'; obj.context.fillStyle = 'rgba(255,255,255,0.5)'; obj.context.strokeRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.fillRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.stroke(); obj.context.fill(); RGraph.Tooltip(canvas, text, e.pageX, e.pageY, barCoords[5]); } } else { canvas.style.cursor = 'default'; } } RGraph.AddEventListener(this.id, 'mousemove', canvas_onmousemove); this.canvas.addEventListener('mousemove', canvas_onmousemove, false); /** * Install the onclick event handler for the tooltips */ if (this.Get('chart.tooltips.event') == 'onclick') { canvas_onclick = function (e) { var e = RGraph.FixEventObject(e); // If the button pressed isn't the left, we're not interested if (e.button != 0) return; e = RGraph.FixEventObject(e); var canvas = document.getElementById(this.id); var obj = canvas.__object__; var barCoords = obj.getBar(e); /** * Redraw the graph first, in effect resetting the graph to as it was when it was first drawn * This "deselects" any already selected bar */ RGraph.Redraw(); /** * Loop through the bars determining if the mouse is over a bar */ if (barCoords) { /** * Get the tooltip text */ if (typeof(obj.Get('chart.tooltips')) == 'function') { var text = String(obj.Get('chart.tooltips')(barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[barCoords[5]]) == 'function') { var text = String(obj.Get('chart.tooltips')[barCoords[5]](barCoords[5])); } else if (typeof(obj.Get('chart.tooltips')) == 'object') { var text = String(obj.Get('chart.tooltips')[barCoords[5]]); } else { var text = null; } /** * Show a tooltip if it's defined */ if (text && text != 'undefined') { // [TODO] Allow customisation of the highlight colors obj.context.beginPath(); obj.context.strokeStyle = 'black'; obj.context.fillStyle = 'rgba(255,255,255,0.5)'; obj.context.strokeRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.fillRect(barCoords[1], barCoords[2], barCoords[3], barCoords[4]); obj.context.stroke(); obj.context.fill(); RGraph.Tooltip(canvas, text, e.pageX, e.pageY, barCoords[5]); } } /** * Stop the event bubbling */ e.stopPropagation(); } RGraph.AddEventListener(this.id, 'click', canvas_onclick); this.canvas.addEventListener('click', canvas_onclick, false); } // This resets the bar graph // 8th August 2010 : Is this redundant //if (typeof(obj) != 'undefined' && obj == RGraph.Registry.Get('chart.tooltip')) { // obj.style.display = 'none'; // RGraph.Registry.Set('chart.tooltip', null) //} } } /** * Draws the labels for the graph */ RGraph.Bar.prototype.DrawLabels = function () { var context = this.context; var gutter = this.gutter; var text_angle = this.Get('chart.text.angle'); var text_size = this.Get('chart.text.size'); var labels = this.Get('chart.labels'); // Draw the Y axis labels: if (this.Get('chart.ylabels')) { this.Drawlabels_center(); this.Drawlabels_bottom(); } /** * The X axis labels */ if (typeof(labels) == 'object' && labels) { var yOffset = 13 + Number(this.Get('chart.xlabels.offset')); /** * Text angle */ var angle = 0; var halign = 'center'; if (text_angle > 0) { angle = -1 * text_angle; halign = 'right'; yOffset -= 5; } // Draw the X axis labels context.fillStyle = this.Get('chart.text.color'); // How wide is each bar var barWidth = (this.canvas.width - (2 * gutter) ) / labels.length; // Reset the xTickGap xTickGap = (this.canvas.width - (2 * gutter)) / labels.length // Draw the X tickmarks var i=0; var font = this.Get('chart.text.font'); for (x=gutter + (xTickGap / 2); x<=this.canvas.width - gutter; x+=xTickGap) { RGraph.Text(context, font, text_size, x + (this.Get('chart.text.angle') == 90 ? 0: 0), (this.canvas.height - gutter) + yOffset, String(labels[i++]), (this.Get('chart.text.angle') == 90 ? 'center' : null), halign, null, angle); } } } /** * Draws the X axis in the middle */ RGraph.Bar.prototype.Drawlabels_center = function () { var font = this.Get('chart.text.font'); var numYLabels = this.Get('chart.ylabels.count'); this.context.fillStyle = this.Get('chart.text.color'); if (this.Get('chart.xaxispos') == 'center') { /** * Draw the top labels */ var interval = (this.grapharea * (1/10) ); var text_size = this.Get('chart.text.size'); var gutter = this.gutter; var units_pre = this.Get('chart.units.pre'); var units_post = this.Get('chart.units.post'); var context = this.context; var align = ''; var xpos = 0; var boxed = false; this.context.fillStyle = this.Get('chart.text.color'); this.context.strokeStyle = 'black'; if (this.Get('chart.ylabels.inside') == true) { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter + 5 : this.canvas.width - gutter - 5; var align = this.Get('chart.yaxispos') == 'left' ? 'left' : 'right'; var boxed = true; } else { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : this.canvas.width - gutter + 5; var align = this.Get('chart.yaxispos') == 'left' ? 'right' : 'left'; var boxed = false; } /** * Draw specific Y labels here so that the local variables can be reused */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); var grapharea = this.canvas.height - (2 * gutter); // Draw the top halves labels for (var i=0; i<labels.length; ++i) { var y = gutter + (grapharea * (i / (labels.length * 2) )); RGraph.Text(context, font, text_size, xpos, y, labels[i], 'center', align, boxed); } // Draw the bottom halves labels for (var i=labels.length-1; i>=0; --i) { var y = gutter + (grapharea * ( (i+1) / (labels.length * 2) )) + (grapharea / 2); RGraph.Text(context, font, text_size, xpos, y, labels[labels.length - i - 1], 'center', align, boxed); } return; } if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, boxed); if (numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (1*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (3*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, boxed); } if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (4*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (2*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, boxed); } } else if (numYLabels == 10) { // 10Y labels interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xpos,gutter + ((this.grapharea / (numYLabels * 2)) * i),RGraph.number_format(this, ((this.scale[4] / numYLabels) * (numYLabels - i)).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align, boxed); } } /////////////////////////////////////////////////////////////////////////////////// /** * Draw the bottom (X axis) labels */ var interval = (this.grapharea) / 10; if (numYLabels == 3 || numYLabels == 5) { if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - (4 * interval), '-' + RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - (2 * interval), '-' + RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, boxed); } if (numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - (3 * interval), '-' + RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (this.grapharea + gutter + this.halfTextHeight) - interval, '-' + RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, boxed); } RGraph.Text(context, font, text_size, xpos, this.grapharea + gutter + this.halfTextHeight, '-' + RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, boxed); } else if (numYLabels == 10) { // Arbitrary number of Y labels interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xpos,this.Get('chart.gutter') + (this.grapharea / 2) + ((this.grapharea / (numYLabels * 2)) * i) + (this.grapharea / (numYLabels * 2)),RGraph.number_format(this, ((this.scale[4] / numYLabels) * (i+1)).toFixed((this.Get('chart.scale.decimals'))), '-' + units_pre, units_post),'center', align, boxed); } } } } /** * Draws the X axdis at the bottom (the default) */ RGraph.Bar.prototype.Drawlabels_bottom = function () { this.context.beginPath(); this.context.fillStyle = this.Get('chart.text.color'); this.context.strokeStyle = 'black'; if (this.Get('chart.xaxispos') != 'center') { var interval = (this.grapharea * (1/5) ); var text_size = this.Get('chart.text.size'); var units_pre = this.Get('chart.units.pre'); var units_post = this.Get('chart.units.post'); var gutter = this.gutter; var context = this.context; var align = this.Get('chart.yaxispos') == 'left' ? 'right' : 'left'; var font = this.Get('chart.text.font'); var numYLabels = this.Get('chart.ylabels.count'); if (this.Get('chart.ylabels.inside') == true) { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter + 5 : this.canvas.width - gutter - 5; var align = this.Get('chart.yaxispos') == 'left' ? 'left' : 'right'; var boxed = true; } else { var xpos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : this.canvas.width - gutter + 5; var boxed = false; } /** * Draw specific Y labels here so that the local variables can be reused */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); var grapharea = this.canvas.height - (2 * gutter); for (var i=0; i<labels.length; ++i) { var y = gutter + (grapharea * (i / labels.length)); RGraph.Text(context, font, text_size, xpos, y, labels[i], 'center', align, boxed); } return; } // 1 label if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[4], units_pre, units_post), null, align, boxed); // 5 labels if (numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (1*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[3], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (3*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[1], units_pre, units_post), null, align, boxed); } // 3 labels if (numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xpos, (2*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[2], units_pre, units_post), null, align, boxed); RGraph.Text(context, font, text_size, xpos, (4*interval) + gutter + this.halfTextHeight, RGraph.number_format(this, this.scale[0], units_pre, units_post), null, align, boxed); } } // 10 Y labels if (numYLabels == 10) { interval = (this.grapharea / numYLabels ); for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xpos, this.Get('chart.gutter') + ((this.grapharea / numYLabels) * i), RGraph.number_format(this,((this.scale[4] / numYLabels) * (numYLabels - i)).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align, boxed); } } } this.context.fill(); this.context.stroke(); } /** * This function is used by MSIE only to manually draw the shadow * * @param array coords The coords for the bar */ RGraph.Bar.prototype.DrawIEShadow = function (coords) { var prevFillStyle = this.context.fillStyle; var offsetx = this.Get('chart.shadow.offsetx'); var offsety = this.Get('chart.shadow.offsety'); this.context.lineWidth = this.Get('chart.linewidth'); this.context.fillStyle = this.Get('chart.shadow.color'); this.context.beginPath(); // Draw shadow here this.context.fillRect(coords[0] + offsetx, coords[1] + offsety, coords[2], coords[3]); this.context.fill(); // Change the fillstyle back to what it was this.context.fillStyle = prevFillStyle; } /** * Not used by the class during creating the graph, but is used by event handlers * to get the coordinates (if any) of the selected bar */ RGraph.Bar.prototype.getBar = function (e) { var canvas = e.target; var obj = e.target.__object__; var mouseCoords = RGraph.getMouseXY(e); /** * Loop through the bars determining if the mouse is over a bar */ for (var i=0; i<obj.coords.length; i++) { var mouseX = mouseCoords[0]; var mouseY = mouseCoords[1]; var left = obj.coords[i][0]; var top = obj.coords[i][1]; var width = obj.coords[i][2]; var height = obj.coords[i][3]; if ( mouseX >= (left + obj.Get('chart.tooltips.coords.adjust')[0]) && mouseX <= (left + width+ obj.Get('chart.tooltips.coords.adjust')[0]) && mouseY >= (top + obj.Get('chart.tooltips.coords.adjust')[1]) && mouseY <= (top + height + obj.Get('chart.tooltips.coords.adjust')[1]) ) { return [obj, left, top, width, height, i]; } } return null; }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ /** * Initialise the various objects */ if (typeof(RGraph) == 'undefined') RGraph = {isRGraph:true,type:'common'}; RGraph.Registry = {}; RGraph.Registry.store = []; RGraph.Registry.store['chart.event.handlers'] = []; RGraph.background = {}; RGraph.objects = []; RGraph.Resizing = {}; RGraph.events = []; /** * Returns five values which are used as a nice scale * * @param max int The maximum value of the graph * @param obj object The graph object * @return array An appropriate scale */ RGraph.getScale = function (max, obj) { /** * Special case for 0 */ if (max == 0) { return ['0.2', '0.4', '0.6', '0.8', '1.0']; } var original_max = max; /** * Manually do decimals */ if (max <= 1) { if (max > 0.5) { return [0.2,0.4,0.6,0.8, Number(1).toFixed(1)]; } else if (max >= 0.1) { return obj.Get('chart.scale.round') ? [0.2,0.4,0.6,0.8,1] : [0.1,0.2,0.3,0.4,0.5]; } else { var tmp = max; var exp = 0; while (tmp < 1.01) { exp += 1; tmp *= 10; } var ret = ['2e-' + exp, '4e-' + exp, '6e-' + exp, '8e-' + exp, '10e-' + exp]; if (max <= ('5e-' + exp)) { ret = ['1e-' + exp, '2e-' + exp, '3e-' + exp, '4e-' + exp, '5e-' + exp]; } return ret; } } // Take off any decimals if (String(max).indexOf('.') > 0) { max = String(max).replace(/\.\d+$/, ''); } var interval = Math.pow(10, Number(String(Number(max)).length - 1)); var topValue = interval; while (topValue < max) { topValue += (interval / 2); } // Handles cases where the max is (for example) 50.5 if (Number(original_max) > Number(topValue)) { topValue += (interval / 2); } // Custom if the max is greater than 5 and less than 10 if (max < 10) { topValue = (Number(original_max) <= 5 ? 5 : 10); } /** * Added 02/11/2010 to create "nicer" scales */ if (obj && typeof(obj.Get('chart.scale.round')) == 'boolean' && obj.Get('chart.scale.round')) { topValue = 10 * interval; } return [topValue * 0.2, topValue * 0.4, topValue * 0.6, topValue * 0.8, topValue]; } /** * Returns the maximum value which is in an array * * @param array arr The array * @param int Whether to ignore signs (ie negative/positive) * @return int The maximum value in the array */ RGraph.array_max = function (arr) { var max = null; for (var i=0; i<arr.length; ++i) { if (typeof(arr[i]) == 'number') { max = (max ? Math.max(max, arguments[1] ? Math.abs(arr[i]) : arr[i]) : arr[i]); } } return max; } /** * Returns the maximum value which is in an array * * @param array arr The array * @param int len The length to pad the array to * @param mixed The value to use to pad the array (optional) */ RGraph.array_pad = function (arr, len) { if (arr.length < len) { var val = arguments[2] ? arguments[2] : null; for (var i=arr.length; i<len; ++i) { arr[i] = val; } } return arr; } /** * An array sum function * * @param array arr The array to calculate the total of * @return int The summed total of the arrays elements */ RGraph.array_sum = function (arr) { // Allow integers if (typeof(arr) == 'number') { return arr; } var i, sum; var len = arr.length; for(i=0,sum=0;i<len;sum+=arr[i++]); return sum; } /** * A simple is_array() function * * @param mixed obj The object you want to check * @return bool Whether the object is an array or not */ RGraph.is_array = function (obj) { return obj != null && obj.constructor.toString().indexOf('Array') != -1; } /** * Converts degrees to radians * * @param int degrees The number of degrees * @return float The number of radians */ RGraph.degrees2Radians = function (degrees) { return degrees * (Math.PI / 180); } /** * This function draws an angled line. The angle is cosidered to be clockwise * * @param obj ctxt The context object * @param int x The X position * @param int y The Y position * @param int angle The angle in RADIANS * @param int length The length of the line */ RGraph.lineByAngle = function (context, x, y, angle, length) { context.arc(x, y, length, angle, angle, false); context.lineTo(x, y); context.arc(x, y, length, angle, angle, false); } /** * This is a useful function which is basically a shortcut for drawing left, right, top and bottom alligned text. * * @param object context The context * @param string font The font * @param int size The size of the text * @param int x The X coordinate * @param int y The Y coordinate * @param string text The text to draw * @parm string The vertical alignment. Can be null. "center" gives center aligned text, "top" gives top aligned text. * Anything else produces bottom aligned text. Default is bottom. * @param string The horizontal alignment. Can be null. "center" gives center aligned text, "right" gives right aligned text. * Anything else produces left aligned text. Default is left. * @param bool Whether to show a bounding box around the text. Defaults not to * @param int The angle that the text should be rotate at (IN DEGREES) * @param string Background color for the text * @param bool Whether the text is bold or not * @param bool Whether the bounding box has a placement indicator */ RGraph.Text = function (context, font, size, x, y, text) { /** * This calls the text function recursively to accommodate multi-line text */ if (typeof(text) == 'string' && text.match(/\r?\n/)) { var nextline = text.replace(/^.*\r?\n/, ''); RGraph.Text(context, font, size, arguments[9] == -90 ? (x + (size * 1.5)) : x, y + (size * 1.5), nextline, arguments[6] ? arguments[6] : null, 'center', arguments[8], arguments[9], arguments[10], arguments[11], arguments[12]); text = text.replace(/\r?\n.*$/, ''); } // Accommodate MSIE if (RGraph.isIE8()) { y += 2; } context.font = (arguments[11] ? 'Bold ': '') + size + 'pt ' + font; var i; var origX = x; var origY = y; var originalFillStyle = context.fillStyle; var originalLineWidth = context.lineWidth; // Need these now the angle can be specified, ie defaults for the former two args if (typeof(arguments[6]) == null) arguments[6] = 'bottom'; // Vertical alignment. Default to bottom/baseline if (typeof(arguments[7]) == null) arguments[7] = 'left'; // Horizontal alignment. Default to left if (typeof(arguments[8]) == null) arguments[8] = null; // Show a bounding box. Useful for positioning during development. Defaults to false if (typeof(arguments[9]) == null) arguments[9] = 0; // Angle (IN DEGREES) that the text should be drawn at. 0 is middle right, and it goes clockwise if (typeof(arguments[12]) == null) arguments[12] = true; // Whether the bounding box has the placement indicator // The alignment is recorded here for purposes of Opera compatibility if (navigator.userAgent.indexOf('Opera') != -1) { context.canvas.__rgraph_valign__ = arguments[6]; context.canvas.__rgraph_halign__ = arguments[7]; } // First, translate to x/y coords context.save(); context.canvas.__rgraph_originalx__ = x; context.canvas.__rgraph_originaly__ = y; context.translate(x, y); x = 0; y = 0; // Rotate the canvas if need be if (arguments[9]) { context.rotate(arguments[9] / 57.3); } // Vertical alignment - defaults to bottom if (arguments[6]) { var vAlign = arguments[6]; if (vAlign == 'center') { context.translate(0, size / 2); } else if (vAlign == 'top') { context.translate(0, size); } } // Hoeizontal alignment - defaults to left if (arguments[7]) { var hAlign = arguments[7]; var width = context.measureText(text).width; if (hAlign) { if (hAlign == 'center') { context.translate(-1 * (width / 2), 0) } else if (hAlign == 'right') { context.translate(-1 * width, 0) } } } context.fillStyle = originalFillStyle; /** * Draw a bounding box if requested */ context.save(); context.fillText(text,0,0); context.lineWidth = 0.5; if (arguments[8]) { var width = context.measureText(text).width; var ieOffset = RGraph.isIE8() ? 2 : 0; context.translate(x, y); context.strokeRect(0 - 3, 0 - 3 - size - ieOffset, width + 6, 0 + size + 6); /** * If requested, draw a background for the text */ if (arguments[10]) { var offset = 3; var ieOffset = RGraph.isIE8() ? 2 : 0; var width = context.measureText(text).width //context.strokeStyle = 'gray'; context.fillStyle = arguments[10]; context.fillRect(x - offset, y - size - offset - ieOffset, width + (2 * offset), size + (2 * offset)); //context.strokeRect(x - offset, y - size - offset - ieOffset, width + (2 * offset), size + (2 * offset)); } /** * Do the actual drawing of the text */ context.fillStyle = originalFillStyle; context.fillText(text,0,0); if (arguments[12]) { context.fillRect( arguments[7] == 'left' ? 0 : (arguments[7] == 'center' ? width / 2 : width ) - 2, arguments[6] == 'bottom' ? 0 : (arguments[6] == 'center' ? (0 - size) / 2 : 0 - size) - 2, 4, 4 ); } } context.restore(); // Reset the lineWidth context.lineWidth = originalLineWidth; context.restore(); } /** * Clears the canvas by setting the width. You can specify a colour if you wish. * * @param object canvas The canvas to clear */ RGraph.Clear = function (canvas) { var context = canvas.getContext('2d'); context.fillStyle = arguments[1] ? String(arguments[1]) : 'white'; context = canvas.getContext('2d'); context.beginPath(); context.fillRect(-5,-5,canvas.width + 5,canvas.height + 5); context.fill(); if (RGraph.ClearAnnotations) { RGraph.ClearAnnotations(canvas.id); } } /** * Draws the title of the graph * * @param object canvas The canvas object * @param string text The title to write * @param integer gutter The size of the gutter * @param integer The center X point (optional - if not given it will be generated from the canvas width) * @param integer Size of the text. If not given it will be 14 */ RGraph.DrawTitle = function (canvas, text, gutter) { var obj = canvas.__object__; var context = canvas.getContext('2d'); var size = arguments[4] ? arguments[4] : 12; var centerx = (arguments[3] ? arguments[3] : canvas.width / 2); var keypos = obj.Get('chart.key.position'); var vpos = gutter / 2; var hpos = obj.Get('chart.title.hpos'); var bgcolor = obj.Get('chart.title.background'); // Account for 3D effect by faking the key position if (obj.type == 'bar' && obj.Get('chart.variant') == '3d') { keypos = 'gutter'; } context.beginPath(); context.fillStyle = obj.Get('chart.text.color') ? obj.Get('chart.text.color') : 'black'; /** * Vertically center the text if the key is not present */ if (keypos && keypos != 'gutter') { var vCenter = 'center'; } else if (!keypos) { var vCenter = 'center'; } else { var vCenter = 'bottom'; } // if chart.title.vpos does not equal 0.5, use that if (typeof(obj.Get('chart.title.vpos')) == 'number') { vpos = obj.Get('chart.title.vpos') * gutter; } // if chart.title.hpos is a number, use that. It's multiplied with the (entire) canvas width if (typeof(hpos) == 'number') { centerx = hpos * canvas.width; } // Set the colour if (typeof(obj.Get('chart.title.color') != null)) { var oldColor = context.fillStyle var newColor = obj.Get('chart.title.color') context.fillStyle = newColor ? newColor : 'black'; } /** * Default font is Verdana */ var font = obj.Get('chart.text.font'); /** * Draw the title itself */ RGraph.Text(context, font, size, centerx, vpos, text, vCenter, 'center', bgcolor != null, null, bgcolor, true); // Reset the fill colour context.fillStyle = oldColor; } /** * This function returns the mouse position in relation to the canvas * * @param object e The event object. */ RGraph.getMouseXY = function (e) { var obj = (RGraph.isIE8() ? event.srcElement : e.target); var x; var y; if (RGraph.isIE8()) e = event; // Browser with offsetX and offsetY if (typeof(e.offsetX) == 'number' && typeof(e.offsetY) == 'number') { x = e.offsetX; y = e.offsetY; // FF and other } else { x = 0; y = 0; while (obj != document.body && obj) { x += obj.offsetLeft; y += obj.offsetTop; obj = obj.offsetParent; } x = e.pageX - x; y = e.pageY - y; } return [x, y]; } /** * This function returns a two element array of the canvas x/y position in * relation to the page * * @param object canvas */ RGraph.getCanvasXY = function (canvas) { var x = 0; var y = 0; var obj = canvas; do { x += obj.offsetLeft; y += obj.offsetTop; obj = obj.offsetParent; } while (obj && obj.tagName.toLowerCase() != 'body'); return [x, y]; } /** * Registers a graph object (used when the canvas is redrawn) * * @param object obj The object to be registered */ RGraph.Register = function (obj) { var key = obj.id + '_' + obj.type; RGraph.objects[key] = obj; } /** * Causes all registered objects to be redrawn * * @param string An optional string indicating which canvas is not to be redrawn * @param string An optional color to use to clear the canvas */ RGraph.Redraw = function () { for (i in RGraph.objects) { // TODO FIXME Maybe include more intense checking for whether the object is an RGraph object, eg obj.isRGraph == true ...? if ( typeof(i) == 'string' && typeof(RGraph.objects[i]) == 'object' && typeof(RGraph.objects[i].type) == 'string' && RGraph.objects[i].isRGraph) { if (!arguments[0] || arguments[0] != RGraph.objects[i].id) { RGraph.Clear(RGraph.objects[i].canvas, arguments[1] ? arguments[1] : null); RGraph.objects[i].Draw(); } } } } /** * Loosly mimicks the PHP function print_r(); */ RGraph.pr = function (obj) { var str = ''; var indent = (arguments[2] ? arguments[2] : ''); switch (typeof(obj)) { case 'number': if (indent == '') { str+= 'Number: ' } str += String(obj); break; case 'string': if (indent == '') { str+= 'String (' + obj.length + '):' } str += '"' + String(obj) + '"'; break; case 'object': // In case of null if (obj == null) { str += 'null'; break; } str += 'Object\n' + indent + '(\n'; for (var i=0; i<obj.length; ++i) { str += indent + ' ' + i + ' => ' + RGraph.pr(obj[i], true, indent + ' ') + '\n'; } var str = str + indent + ')'; break; case 'function': str += obj; break; case 'boolean': str += 'Boolean: ' + (obj ? 'true' : 'false'); break; } /** * Finished, now either return if we're in a recursed call, or alert() * if we're not. */ if (arguments[1]) { return str; } else { alert(str); } } /** * The RGraph registry Set() function * * @param string name The name of the key * @param mixed value The value to set * @return mixed Returns the same value as you pass it */ RGraph.Registry.Set = function (name, value) { // Store the setting RGraph.Registry.store[name] = value; // Don't really need to do this, but ho-hum return value; } /** * The RGraph registry Get() function * * @param string name The name of the particular setting to fetch * @return mixed The value if exists, null otherwise */ RGraph.Registry.Get = function (name) { //return RGraph.Registry.store[name] == null ? null : RGraph.Registry.store[name]; return RGraph.Registry.store[name]; } /** * This function draws the background for the bar chart, line chart and scatter chart. * * @param object obj The graph object */ RGraph.background.Draw = function (obj) { var canvas = obj.canvas; var context = obj.context; var height = 0; var gutter = obj.Get('chart.gutter'); var variant = obj.Get('chart.variant'); context.fillStyle = obj.Get('chart.text.color'); // If it's a bar and 3D variant, translate if (variant == '3d') { context.save(); context.translate(10, -5); } // X axis title if (typeof(obj.Get('chart.title.xaxis')) == 'string' && obj.Get('chart.title.xaxis').length) { var size = obj.Get('chart.text.size'); var font = obj.Get('chart.text.font'); context.beginPath(); RGraph.Text(context, font, size + 2, obj.canvas.width / 2, canvas.height - (gutter * obj.Get('chart.title.xaxis.pos')), obj.Get('chart.title.xaxis'), 'center', 'center', false, false, false, true); context.fill(); } // Y axis title if (typeof(obj.Get('chart.title.yaxis')) == 'string' && obj.Get('chart.title.yaxis').length) { var size = obj.Get('chart.text.size'); var font = obj.Get('chart.text.font'); context.beginPath(); RGraph.Text(context, font, size + 2, gutter * obj.Get('chart.title.yaxis.pos'), canvas.height / 2, obj.Get('chart.title.yaxis'), 'center', 'center', false, 270, false, true); context.fill(); } obj.context.beginPath(); // Draw the horizontal bars context.fillStyle = obj.Get('chart.background.barcolor1'); height = (obj.canvas.height - obj.Get('chart.gutter')); for (var i=gutter; i < height ; i+=80) { obj.context.fillRect(gutter, i, obj.canvas.width - (gutter * 2), Math.min(40, obj.canvas.height - gutter - i) ); } context.fillStyle = obj.Get('chart.background.barcolor2'); height = (obj.canvas.height - gutter); for (var i= (40 + gutter); i < height; i+=80) { obj.context.fillRect(gutter, i, obj.canvas.width - (gutter * 2), i + 40 > (obj.canvas.height - gutter) ? obj.canvas.height - (gutter + i) : 40); } context.stroke(); // Draw the background grid if (obj.Get('chart.background.grid')) { // If autofit is specified, use the .numhlines and .numvlines along with the width to work // out the hsize and vsize if (obj.Get('chart.background.grid.autofit')) { var vsize = (canvas.width - (2 * obj.Get('chart.gutter')) - (obj.type == 'gantt' ? 2 * obj.Get('chart.gutter') : 0)) / obj.Get('chart.background.grid.autofit.numvlines'); var hsize = (canvas.height - (2 * obj.Get('chart.gutter'))) / obj.Get('chart.background.grid.autofit.numhlines'); obj.Set('chart.background.grid.vsize', vsize); obj.Set('chart.background.grid.hsize', hsize); } context.beginPath(); context.lineWidth = obj.Get('chart.background.grid.width') ? obj.Get('chart.background.grid.width') : 1; context.strokeStyle = obj.Get('chart.background.grid.color'); // Draw the horizontal lines if (obj.Get('chart.background.grid.hlines')) { height = (canvas.height - gutter) for (y=gutter; y < height; y+=obj.Get('chart.background.grid.hsize')) { context.moveTo(gutter, y); context.lineTo(canvas.width - gutter, y); } } if (obj.Get('chart.background.grid.vlines')) { // Draw the vertical lines var width = (canvas.width - gutter) for (x=gutter + (obj.type == 'gantt' ? (2 * gutter) : 0); x<=width; x+=obj.Get('chart.background.grid.vsize')) { context.moveTo(x, gutter); context.lineTo(x, obj.canvas.height - gutter); } } if (obj.Get('chart.background.grid.border')) { // Make sure a rectangle, the same colour as the grid goes around the graph context.strokeStyle = obj.Get('chart.background.grid.color'); context.strokeRect(gutter, gutter, canvas.width - (2 * gutter), canvas.height - (2 * gutter)); } } context.stroke(); // If it's a bar and 3D variant, translate if (variant == '3d') { context.restore(); } // Draw the title if one is set if ( typeof(obj.Get('chart.title')) == 'string') { if (obj.type == 'gantt') { gutter /= 2; } RGraph.DrawTitle(canvas, obj.Get('chart.title'), gutter, null, obj.Get('chart.text.size') + 2); } context.stroke(); } /** * Returns the day number for a particular date. Eg 1st February would be 32 * * @param object obj A date object * @return int The day number of the given date */ RGraph.GetDays = function (obj) { var year = obj.getFullYear(); var days = obj.getDate(); var month = obj.getMonth(); if (month == 0) return days; if (month >= 1) days += 31; if (month >= 2) days += 28; // Leap years. Crude, but if this code is still being used // when it stops working, then you have my permission to shoot // me. Oh, you won't be able to - I'll be dead... if (year >= 2008 && year % 4 == 0) days += 1; if (month >= 3) days += 31; if (month >= 4) days += 30; if (month >= 5) days += 31; if (month >= 6) days += 30; if (month >= 7) days += 31; if (month >= 8) days += 31; if (month >= 9) days += 30; if (month >= 10) days += 31; if (month >= 11) days += 30; return days; } /** * Draws the graph key (used by various graphs) * * @param object obj The graph object * @param array key An array of the texts to be listed in the key * @param colors An array of the colors to be used */ RGraph.DrawKey = function (obj, key, colors) { var canvas = obj.canvas; var context = obj.context; context.lineWidth = 1; context.beginPath(); /** * Key positioned in the gutter */ var keypos = obj.Get('chart.key.position'); var textsize = obj.Get('chart.text.size'); var gutter = obj.Get('chart.gutter'); /** * Change the older chart.key.vpos to chart.key.position.y */ if (typeof(obj.Get('chart.key.vpos')) == 'number') { obj.Set('chart.key.position.y', obj.Get('chart.key.vpos') * gutter); } if (keypos && keypos == 'gutter') { RGraph.DrawKey_gutter(obj, key, colors); /** * In-graph style key */ } else if (keypos && keypos == 'graph') { RGraph.DrawKey_graph(obj, key, colors); } else { alert('[COMMON] (' + obj.id + ') Unknown key position: ' + keypos); } } /** * This does the actual drawing of the key when it's in the graph * * @param object obj The graph object * @param array key The key items to draw * @param array colors An aray of colors that the key will use */ RGraph.DrawKey_graph = function (obj, key, colors) { var canvas = obj.canvas; var context = obj.context; var text_size = typeof(obj.Get('chart.key.text.size')) == 'number' ? obj.Get('chart.key.text.size') : obj.Get('chart.text.size'); var text_font = obj.Get('chart.text.font'); var gutter = obj.Get('chart.gutter'); var hpos = obj.Get('chart.yaxispos') == 'right' ? gutter + 10 : canvas.width - gutter - 10; var vpos = gutter + 10; var title = obj.Get('chart.title'); var blob_size = text_size; // The blob of color var hmargin = 8; // This is the size of the gaps between the blob of color and the text var vmargin = 4; // This is the vertical margin of the key var fillstyle = obj.Get('chart.key.background'); var strokestyle = 'black'; var height = 0; var width = 0; // Need to set this so that measuring the text works out OK context.font = text_size + 'pt ' + obj.Get('chart.text.font'); // Work out the longest bit of text for (i=0; i<key.length; ++i) { width = Math.max(width, context.measureText(key[i]).width); } width += 5; width += blob_size; width += 5; width += 5; width += 5; /** * Now we know the width, we can move the key left more accurately */ if ( obj.Get('chart.yaxispos') == 'left' || (obj.type == 'pie' && !obj.Get('chart.yaxispos')) || (obj.type == 'hbar' && !obj.Get('chart.yaxispos')) || (obj.type == 'rscatter' && !obj.Get('chart.yaxispos')) || (obj.type == 'tradar' && !obj.Get('chart.yaxispos')) || (obj.type == 'rose' && !obj.Get('chart.yaxispos')) || (obj.type == 'funnel' && !obj.Get('chart.yaxispos')) ) { hpos -= width; } /** * Specific location coordinates */ if (typeof(obj.Get('chart.key.position.x')) == 'number') { hpos = obj.Get('chart.key.position.x'); } if (typeof(obj.Get('chart.key.position.y')) == 'number') { vpos = obj.Get('chart.key.position.y'); } // Stipulate the shadow for the key box if (obj.Get('chart.key.shadow')) { context.shadowColor = obj.Get('chart.key.shadow.color'); context.shadowBlur = obj.Get('chart.key.shadow.blur'); context.shadowOffsetX = obj.Get('chart.key.shadow.offsetx'); context.shadowOffsetY = obj.Get('chart.key.shadow.offsety'); } // Draw the box that the key resides in context.beginPath(); context.fillStyle = obj.Get('chart.key.background'); context.strokeStyle = 'black'; if (arguments[3] != false) { /* // Manually draw the MSIE shadow if (RGraph.isIE8() && obj.Get('chart.key.shadow')) { context.beginPath(); context.fillStyle = '#666'; if (obj.Get('chart.key.rounded')) { RGraph.NoShadow(obj); context.beginPath(); RGraph.filledCurvyRect(context, xpos + obj.Get('chart.key.shadow.offsetx'), gutter + 5 + obj.Get('chart.key.shadow.offsety'), width - 5, 5 + ( (textsize + 5) * key.length), 5); context.closePath(); context.fill(); } else { context.fillRect(xpos + 2, gutter + 5 + 2, width - 5, 5 + ( (textsize + 5) * key.length)); } context.fill(); context.fillStyle = obj.Get('chart.key.background'); } */ // The older square rectangled key if (obj.Get('chart.key.rounded') == true) { context.beginPath(); context.strokeStyle = strokestyle; RGraph.strokedCurvyRect(context, hpos, vpos, width - 5, 5 + ( (text_size + 5) * key.length),4); context.stroke(); context.fill(); RGraph.NoShadow(obj); } else { context.strokeRect(hpos, vpos, width - 5, 5 + ( (text_size + 5) * key.length)); context.fillRect(hpos, vpos, width - 5, 5 + ( (text_size + 5) * key.length)); } } RGraph.NoShadow(obj); context.beginPath(); // Draw the labels given for (var i=key.length - 1; i>=0; i--) { var j = Number(i) + 1; // Draw the blob of color if (obj.Get('chart.key.color.shape') == 'circle') { context.beginPath(); context.strokeStyle = 'rgba(0,0,0,0)'; context.fillStyle = colors[i]; context.arc(hpos + 5 + (blob_size / 2), vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2), blob_size / 2, 0, 6.26, 0); context.fill(); } else if (obj.Get('chart.key.color.shape') == 'line') { context.beginPath(); context.strokeStyle = colors[i]; context.moveTo(hpos + 5, vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2)); context.lineTo(hpos + blob_size + 5, vpos + (5 * j) + (text_size * j) - text_size + (blob_size / 2)); context.stroke(); } else { context.fillStyle = colors[i]; context.fillRect(hpos + 5, vpos + (5 * j) + (text_size * j) - text_size, text_size, text_size + 1); } context.beginPath(); context.fillStyle = 'black'; RGraph.Text(context, text_font, text_size, hpos + blob_size + 5 + 5, vpos + (5 * j) + (text_size * j), key[i]); } context.fill(); } /** * This does the actual drawing of the key when it's in the gutter * * @param object obj The graph object * @param array key The key items to draw * @param array colors An aray of colors that the key will use */ RGraph.DrawKey_gutter = function (obj, key, colors) { var canvas = obj.canvas; var context = obj.context; var text_size = typeof(obj.Get('chart.key.text.size')) == 'number' ? obj.Get('chart.key.text.size') : obj.Get('chart.text.size'); var text_font = obj.Get('chart.text.font'); var gutter = obj.Get('chart.gutter'); var hpos = canvas.width / 2; var vpos = (gutter / 2) - 5; var title = obj.Get('chart.title'); var blob_size = text_size; // The blob of color var hmargin = 8; // This is the size of the gaps between the blob of color and the text var vmargin = 4; // This is the vertical margin of the key var fillstyle = obj.Get('chart.key.background'); var strokestyle = 'black'; var length = 0; // Need to work out the length of the key first context.font = text_size + 'pt ' + text_font; for (i=0; i<key.length; ++i) { length += hmargin; length += blob_size; length += hmargin; length += context.measureText(key[i]).width; } length += hmargin; /** * Work out hpos since in the Pie it isn't necessarily dead center */ if (obj.type == 'pie') { if (obj.Get('chart.align') == 'left') { var hpos = obj.radius + obj.Get('chart.gutter'); } else if (obj.Get('chart.align') == 'right') { var hpos = obj.canvas.width - obj.radius - obj.Get('chart.gutter'); } else { hpos = canvas.width / 2; } } /** * This makes the key centered */ hpos -= (length / 2); /** * Override the horizontal/vertical positioning */ if (typeof(obj.Get('chart.key.position.x')) == 'number') { hpos = obj.Get('chart.key.position.x'); } if (typeof(obj.Get('chart.key.position.y')) == 'number') { vpos = obj.Get('chart.key.position.y'); } /** * Draw the box that the key sits in */ if (obj.Get('chart.key.position.gutter.boxed')) { if (obj.Get('chart.key.shadow')) { context.shadowColor = obj.Get('chart.key.shadow.color'); context.shadowBlur = obj.Get('chart.key.shadow.blur'); context.shadowOffsetX = obj.Get('chart.key.shadow.offsetx'); context.shadowOffsetY = obj.Get('chart.key.shadow.offsety'); } context.beginPath(); context.fillStyle = fillstyle; context.strokeStyle = strokestyle; if (obj.Get('chart.key.rounded')) { RGraph.strokedCurvyRect(context, hpos, vpos - vmargin, length, text_size + vmargin + vmargin) // Odd... RGraph.filledCurvyRect(context, hpos, vpos - vmargin, length, text_size + vmargin + vmargin); } else { context.strokeRect(hpos, vpos - vmargin, length, text_size + vmargin + vmargin); context.fillRect(hpos, vpos - vmargin, length, text_size + vmargin + vmargin); } context.stroke(); context.fill(); RGraph.NoShadow(obj); } /** * Draw the blobs of color and the text */ for (var i=0, pos=hpos; i<key.length; ++i) { pos += hmargin; // Draw the blob of color - line if (obj.Get('chart.key.color.shape') =='line') { context.beginPath(); context.strokeStyle = colors[i]; context.moveTo(pos, vpos + (blob_size / 2)); context.lineTo(pos + blob_size, vpos + (blob_size / 2)); context.stroke(); // Circle } else if (obj.Get('chart.key.color.shape') == 'circle') { context.beginPath(); context.fillStyle = colors[i]; context.moveTo(pos, vpos + (blob_size / 2)); context.arc(pos + (blob_size / 2), vpos + (blob_size / 2), (blob_size / 2), 0, 6.28, 0); context.fill(); } else { context.beginPath(); context.fillStyle = colors[i]; context.fillRect(pos, vpos, blob_size, blob_size); context.fill(); } pos += blob_size; pos += hmargin; context.beginPath(); context.fillStyle = 'black'; RGraph.Text(context, text_font, text_size, pos, vpos + text_size - 1, key[i]); context.fill(); pos += context.measureText(key[i]).width; } } /** * A shortcut for RGraph.pr() */ function pd(variable) { RGraph.pr(variable); } function p(variable) { RGraph.pr(variable); } /** * A shortcut for console.log - as used by Firebug and Chromes console */ function cl (variable) { return console.log(variable); } /** * Makes a clone of an object * * @param obj val The object to clone */ RGraph.array_clone = function (obj) { if(obj == null || typeof(obj) != 'object') { return obj; } var temp = []; //var temp = new obj.constructor(); for(var i=0;i<obj.length; ++i) { temp[i] = RGraph.array_clone(obj[i]); } return temp; } /** * This function reverses an array */ RGraph.array_reverse = function (arr) { var newarr = []; for (var i=arr.length - 1; i>=0; i--) { newarr.push(arr[i]); } return newarr; } /** * Formats a number with thousand seperators so it's easier to read * * @param integer num The number to format * @param string The (optional) string to prepend to the string * @param string The (optional) string to ap * pend to the string * @return string The formatted number */ RGraph.number_format = function (obj, num) { var i; var prepend = arguments[2] ? String(arguments[2]) : ''; var append = arguments[3] ? String(arguments[3]) : ''; var output = ''; var decimal = ''; var decimal_seperator = obj.Get('chart.scale.point') ? obj.Get('chart.scale.point') : '.'; var thousand_seperator = obj.Get('chart.scale.thousand') ? obj.Get('chart.scale.thousand') : ','; RegExp.$1 = ''; var i,j; // Ignore the preformatted version of "1e-2" if (String(num).indexOf('e') > 0) { return String(prepend + String(num) + append); } // We need then number as a string num = String(num); // Take off the decimal part - we re-append it later if (num.indexOf('.') > 0) { num = num.replace(/\.(.*)/, ''); decimal = RegExp.$1; } // Thousand seperator //var seperator = arguments[1] ? String(arguments[1]) : ','; var seperator = thousand_seperator; /** * Work backwards adding the thousand seperators */ var foundPoint; for (i=(num.length - 1),j=0; i>=0; j++,i--) { var character = num.charAt(i); if ( j % 3 == 0 && j != 0) { output += seperator; } /** * Build the output */ output += character; } /** * Now need to reverse the string */ var rev = output; output = ''; for (i=(rev.length - 1); i>=0; i--) { output += rev.charAt(i); } // Tidy up output = output.replace(/^-,/, '-'); // Reappend the decimal if (decimal.length) { output = output + decimal_seperator + decimal; decimal = ''; RegExp.$1 = ''; } // Minor bugette if (output.charAt(0) == '-') { output *= -1; prepend = '-' + prepend; } return prepend + output + append; } /** * Draws horizontal coloured bars on something like the bar, line or scatter */ RGraph.DrawBars = function (obj) { var hbars = obj.Get('chart.background.hbars'); /** * Draws a horizontal bar */ obj.context.beginPath(); for (i=0; i<hbars.length; ++i) { // If null is specified as the "height", set it to the upper max value if (hbars[i][1] == null) { hbars[i][1] = obj.max; // If the first index plus the second index is greater than the max value, adjust accordingly } else if (hbars[i][0] + hbars[i][1] > obj.max) { hbars[i][1] = obj.max - hbars[i][0]; } // If height is negative, and the abs() value is greater than .max, use a negative max instead if (Math.abs(hbars[i][1]) > obj.max) { hbars[i][1] = -1 * obj.max; } // If start point is greater than max, change it to max if (Math.abs(hbars[i][0]) > obj.max) { hbars[i][0] = obj.max; } // If start point plus height is less than negative max, use the negative max plus the start point if (hbars[i][0] + hbars[i][1] < (-1 * obj.max) ) { hbars[i][1] = -1 * (obj.max + hbars[i][0]); } // If the X axis is at the bottom, and a negative max is given, warn the user if (obj.Get('chart.xaxispos') == 'bottom' && (hbars[i][0] < 0 || (hbars[i][1] + hbars[i][1] < 0)) ) { alert('[' + obj.type.toUpperCase() + ' (ID: ' + obj.id + ') BACKGROUND HBARS] You have a negative value in one of your background hbars values, whilst the X axis is in the center'); } var ystart = (obj.grapharea - ((hbars[i][0] / obj.max) * obj.grapharea)); var height = (Math.min(hbars[i][1], obj.max - hbars[i][0]) / obj.max) * obj.grapharea; // Account for the X axis being in the center if (obj.Get('chart.xaxispos') == 'center') { ystart /= 2; height /= 2; } ystart += obj.Get('chart.gutter') var x = obj.Get('chart.gutter'); var y = ystart - height; var w = obj.canvas.width - (2 * obj.Get('chart.gutter')); var h = height; // Accommodate Opera :-/ if (navigator.userAgent.indexOf('Opera') != -1 && obj.Get('chart.xaxispos') == 'center' && h < 0) { h *= -1; y = y - h; } obj.context.fillStyle = hbars[i][2]; obj.context.fillRect(x, y, w, h); } obj.context.fill(); } /** * Draws in-graph labels. * * @param object obj The graph object */ RGraph.DrawInGraphLabels = function (obj) { var canvas = obj.canvas; var context = obj.context; var labels = obj.Get('chart.labels.ingraph'); var labels_processed = []; // Defaults var fgcolor = 'black'; var bgcolor = 'white'; var direction = 1; if (!labels) { return; } /** * Preprocess the labels array. Numbers are expanded */ for (var i=0; i<labels.length; ++i) { if (typeof(labels[i]) == 'number') { for (var j=0; j<labels[i]; ++j) { labels_processed.push(null); } } else if (typeof(labels[i]) == 'string' || typeof(labels[i]) == 'object') { labels_processed.push(labels[i]); } else { labels_processed.push(''); } } /** * Turn off any shadow */ RGraph.NoShadow(obj); if (labels_processed && labels_processed.length > 0) { for (var i=0; i<labels_processed.length; ++i) { if (labels_processed[i]) { var coords = obj.coords[i]; if (coords && coords.length > 0) { var x = (obj.type == 'bar' ? coords[0] + (coords[2] / 2) : coords[0]); var y = (obj.type == 'bar' ? coords[1] + (coords[3] / 2) : coords[1]); var length = typeof(labels_processed[i][4]) == 'number' ? labels_processed[i][4] : 25; context.beginPath(); context.fillStyle = 'black'; context.strokeStyle = 'black'; if (obj.type == 'bar') { if (obj.Get('chart.variant') == 'dot') { context.moveTo(x, obj.coords[i][1] - 5); context.lineTo(x, obj.coords[i][1] - 5 - length); var text_x = x; var text_y = obj.coords[i][1] - 5 - length; } else if (obj.Get('chart.variant') == 'arrow') { context.moveTo(x, obj.coords[i][1] - 5); context.lineTo(x, obj.coords[i][1] - 5 - length); var text_x = x; var text_y = obj.coords[i][1] - 5 - length; } else { context.arc(x, y, 2.5, 0, 6.28, 0); context.moveTo(x, y); context.lineTo(x, y - length); var text_x = x; var text_y = y - length; } context.stroke(); context.fill(); } else if (obj.type == 'line') { if ( typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][3]) == 'number' && labels_processed[i][3] == -1 ) { context.moveTo(x, y + 5); context.lineTo(x, y + 5 + length); context.stroke(); context.beginPath(); // This draws the arrow context.moveTo(x, y + 5); context.lineTo(x - 3, y + 10); context.lineTo(x + 3, y + 10); context.closePath(); var text_x = x; var text_y = y + 5 + length; } else { var text_x = x; var text_y = y - 5 - length; context.moveTo(x, y - 5); context.lineTo(x, y - 5 - length); context.stroke(); context.beginPath(); // This draws the arrow context.moveTo(x, y - 5); context.lineTo(x - 3, y - 10); context.lineTo(x + 3, y - 10); context.closePath(); } context.fill(); } // Taken out on the 10th Nov 2010 - unnecessary //var width = context.measureText(labels[i]).width; context.beginPath(); // Fore ground color context.fillStyle = (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][1]) == 'string') ? labels_processed[i][1] : 'black'; RGraph.Text(context, obj.Get('chart.text.font'), obj.Get('chart.text.size'), text_x, text_y, (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][0]) == 'string') ? labels_processed[i][0] : labels_processed[i], 'bottom', 'center', true, null, (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][2]) == 'string') ? labels_processed[i][2] : 'white'); context.fill(); } } } } } /** * This function "fills in" key missing properties that various implementations lack * * @param object e The event object */ RGraph.FixEventObject = function (e) { if (RGraph.isIE8()) { var e = event; e.pageX = (event.clientX + document.body.scrollLeft); e.pageY = (event.clientY + document.body.scrollTop); e.target = event.srcElement; if (!document.body.scrollTop && document.documentElement.scrollTop) { e.pageX += parseInt(document.documentElement.scrollLeft); e.pageY += parseInt(document.documentElement.scrollTop); } } // This is mainly for FF which doesn't provide offsetX if (typeof(e.offsetX) == 'undefined' && typeof(e.offsetY) == 'undefined') { var coords = RGraph.getMouseXY(e); e.offsetX = coords[0]; e.offsetY = coords[1]; } // Any browser that doesn't implement stopPropagation() (MSIE) if (!e.stopPropagation) { e.stopPropagation = function () {window.event.cancelBubble = true;} } return e; } /** * Draw crosshairs if enabled * * @param object obj The graph object (from which we can get the context and canvas as required) */ RGraph.DrawCrosshairs = function (obj) { if (obj.Get('chart.crosshairs')) { var canvas = obj.canvas; var context = obj.context; // 5th November 2010 - removed now that tooltips are DOM2 based. //if (obj.Get('chart.tooltips') && obj.Get('chart.tooltips').length > 0) { //alert('[' + obj.type.toUpperCase() + '] Sorry - you cannot have crosshairs enabled with tooltips! Turning off crosshairs...'); //obj.Set('chart.crosshairs', false); //return; //} canvas.onmousemove = function (e) { var e = RGraph.FixEventObject(e); var canvas = obj.canvas; var context = obj.context; var gutter = obj.Get('chart.gutter'); var width = canvas.width; var height = canvas.height; var adjustments = obj.Get('chart.tooltips.coords.adjust'); var mouseCoords = RGraph.getMouseXY(e); var x = mouseCoords[0]; var y = mouseCoords[1]; if (typeof(adjustments) == 'object' && adjustments[0] && adjustments[1]) { x = x - adjustments[0]; y = y - adjustments[1]; } RGraph.Clear(canvas); obj.Draw(); if ( x >= gutter && y >= gutter && x <= (width - gutter) && y <= (height - gutter) ) { var linewidth = obj.Get('chart.crosshairs.linewidth'); context.lineWidth = linewidth ? linewidth : 1; context.beginPath(); context.strokeStyle = obj.Get('chart.crosshairs.color'); // Draw a top vertical line context.moveTo(x, gutter); context.lineTo(x, height - gutter); // Draw a horizontal line context.moveTo(gutter, y); context.lineTo(width - gutter, y); context.stroke(); /** * Need to show the coords? */ if (obj.Get('chart.crosshairs.coords')) { if (obj.type == 'scatter') { var xCoord = (((x - obj.Get('chart.gutter')) / (obj.canvas.width - (2 * obj.Get('chart.gutter')))) * (obj.Get('chart.xmax') - obj.Get('chart.xmin'))) + obj.Get('chart.xmin'); xCoord = xCoord.toFixed(obj.Get('chart.scale.decimals')); var yCoord = obj.max - (((y - obj.Get('chart.gutter')) / (obj.canvas.height - (2 * obj.Get('chart.gutter')))) * obj.max); if (obj.type == 'scatter' && obj.Get('chart.xaxispos') == 'center') { yCoord = (yCoord - (obj.max / 2)) * 2; } yCoord = yCoord.toFixed(obj.Get('chart.scale.decimals')); var div = RGraph.Registry.Get('chart.coordinates.coords.div'); var mouseCoords = RGraph.getMouseXY(e); var canvasXY = RGraph.getCanvasXY(canvas); if (!div) { div = document.createElement('DIV'); div.__object__ = obj; div.style.position = 'absolute'; div.style.backgroundColor = 'white'; div.style.border = '1px solid black'; div.style.fontFamily = 'Arial, Verdana, sans-serif'; div.style.fontSize = '10pt' div.style.padding = '2px'; div.style.opacity = 1; div.style.WebkitBorderRadius = '3px'; div.style.borderRadius = '3px'; div.style.MozBorderRadius = '3px'; document.body.appendChild(div); RGraph.Registry.Set('chart.coordinates.coords.div', div); } // Convert the X/Y pixel coords to correspond to the scale div.style.opacity = 1; div.style.display = 'inline'; if (!obj.Get('chart.crosshairs.coords.fixed')) { div.style.left = Math.max(2, (e.pageX - div.offsetWidth - 3)) + 'px'; div.style.top = Math.max(2, (e.pageY - div.offsetHeight - 3)) + 'px'; } else { div.style.left = canvasXY[0] + obj.Get('chart.gutter') + 3 + 'px'; div.style.top = canvasXY[1] + obj.Get('chart.gutter') + 3 + 'px'; } div.innerHTML = '<span style="color: #666">' + obj.Get('chart.crosshairs.coords.labels.x') + ':</span> ' + xCoord + '<br><span style="color: #666">' + obj.Get('chart.crosshairs.coords.labels.y') + ':</span> ' + yCoord; canvas.addEventListener('mouseout', RGraph.HideCrosshairCoords, false); } else { alert('[RGRAPH] Showing crosshair coordinates is only supported on the Scatter chart'); } } } else { RGraph.HideCrosshairCoords(); } } } } /** * Thisz function hides the crosshairs coordinates */ RGraph.HideCrosshairCoords = function () { var div = RGraph.Registry.Get('chart.coordinates.coords.div'); if ( div && div.style.opacity == 1 && div.__object__.Get('chart.crosshairs.coords.fadeout') ) { setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.9;}, 50); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.8;}, 100); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.7;}, 150); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.6;}, 200); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.5;}, 250); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.4;}, 300); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.3;}, 350); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.2;}, 400); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.1;}, 450); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0;}, 500); setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.display = 'none';}, 550); } } /** * Trims the right hand side of a string. Removes SPACE, TAB * CR and LF. * * @param string str The string to trim */ RGraph.rtrim = function (str) { return str.replace(/( |\n|\r|\t)+$/, ''); } /** * Draws the3D axes/background */ RGraph.Draw3DAxes = function (obj) { var gutter = obj.Get('chart.gutter'); var context = obj.context; var canvas = obj.canvas; context.strokeStyle = '#aaa'; context.fillStyle = '#ddd'; // Draw the vertical left side context.beginPath(); context.moveTo(gutter, gutter); context.lineTo(gutter + 10, gutter - 5); context.lineTo(gutter + 10, canvas.height - gutter - 5); context.lineTo(gutter, canvas.height - gutter); context.closePath(); context.stroke(); context.fill(); // Draw the bottom floor context.beginPath(); context.moveTo(gutter, canvas.height - gutter); context.lineTo(gutter + 10, canvas.height - gutter - 5); context.lineTo(canvas.width - gutter + 10, canvas.height - gutter - 5); context.lineTo(canvas.width - gutter, canvas.height - gutter); context.closePath(); context.stroke(); context.fill(); } /** * Turns off any shadow * * @param object obj The graph object */ RGraph.NoShadow = function (obj) { obj.context.shadowColor = 'rgba(0,0,0,0)'; obj.context.shadowBlur = 0; obj.context.shadowOffsetX = 0; obj.context.shadowOffsetY = 0; } /** * Sets the four shadow properties - a shortcut function * * @param object obj Your graph object * @param string color The shadow color * @param number offsetx The shadows X offset * @param number offsety The shadows Y offset * @param number blur The blurring effect applied to the shadow */ RGraph.SetShadow = function (obj, color, offsetx, offsety, blur) { obj.context.shadowColor = color; obj.context.shadowOffsetX = offsetx; obj.context.shadowOffsetY = offsety; obj.context.shadowBlur = blur; } /** * This function attempts to "fill in" missing functions from the canvas * context object. Only two at the moment - measureText() nd fillText(). * * @param object context The canvas 2D context */ RGraph.OldBrowserCompat = function (context) { if (!context.measureText) { // This emulates the measureText() function context.measureText = function (text) { var textObj = document.createElement('DIV'); textObj.innerHTML = text; textObj.style.backgroundColor = 'white'; textObj.style.position = 'absolute'; textObj.style.top = -100 textObj.style.left = 0; document.body.appendChild(textObj); var width = {width: textObj.offsetWidth}; textObj.style.display = 'none'; return width; } } if (!context.fillText) { // This emulates the fillText() method context.fillText = function (text, targetX, targetY) { return false; } } // If IE8, add addEventListener() if (!context.canvas.addEventListener) { window.addEventListener = function (ev, func, bubble) { return this.attachEvent('on' + ev, func); } context.canvas.addEventListener = function (ev, func, bubble) { return this.attachEvent('on' + ev, func); } } } /** * This function is for use with circular graph types, eg the Pie or Radar. Pass it your event object * and it will pass you back the corresponding segment details as an array: * * [x, y, r, startAngle, endAngle] * * Angles are measured in degrees, and are measured from the "east" axis (just like the canvas). * * @param object e Your event object */ RGraph.getSegment = function (e) { RGraph.FixEventObject(e); // The optional arg provides a way of allowing some accuracy (pixels) var accuracy = arguments[1] ? arguments[1] : 0; var obj = e.target.__object__; var canvas = obj.canvas; var context = obj.context; var mouseCoords = RGraph.getMouseXY(e); var x = mouseCoords[0] - obj.centerx; var y = mouseCoords[1] - obj.centery; var r = obj.radius; var theta = Math.atan(y / x); // RADIANS var hyp = y / Math.sin(theta); var angles = obj.angles; var ret = []; var hyp = (hyp < 0) ? hyp + accuracy : hyp - accuracy; // Put theta in DEGREES theta *= 57.3 // hyp should not be greater than radius if it's a Rose chart if (obj.type == 'rose') { if ( (isNaN(hyp) && Math.abs(mouseCoords[0]) < (obj.centerx - r) ) || (isNaN(hyp) && Math.abs(mouseCoords[0]) > (obj.centerx + r)) || (!isNaN(hyp) && Math.abs(hyp) > r)) { return; } } /** * Account for the correct quadrant */ if (x < 0 && y >= 0) { theta += 180; } else if (x < 0 && y < 0) { theta += 180; } else if (x > 0 && y < 0) { theta += 360; } /** * Account for the rose chart */ if (obj.type == 'rose') { theta += 90; } if (theta > 360) { theta -= 360; } for (var i=0; i<angles.length; ++i) { if (theta >= angles[i][0] && theta < angles[i][1]) { hyp = Math.abs(hyp); if (obj.type == 'rose' && hyp > angles[i][2]) { return null; } if (!hyp || (obj.type == 'pie' && obj.radius && hyp > obj.radius) ) { return null; } if (obj.type == 'pie' && obj.Get('chart.variant') == 'donut' && (hyp > obj.radius || hyp < (obj.radius / 2) ) ) { return null; } ret[0] = obj.centerx; ret[1] = obj.centery; ret[2] = (obj.type == 'rose') ? angles[i][2] : obj.radius; ret[3] = angles[i][0]; ret[4] = angles[i][1]; ret[5] = i; if (obj.type == 'rose') { ret[3] -= 90; ret[4] -= 90; if (x > 0 && y < 0) { ret[3] += 360; ret[4] += 360; } } if (ret[3] < 0) ret[3] += 360; if (ret[4] > 360) ret[4] -= 360; return ret; } } return null; } /** * This is a function that can be used to run code asynchronously, which can * be used to speed up the loading of you pages. * * @param string func This is the code to run. It can also be a function pointer. * The front page graphs show this function in action. Basically * each graphs code is made in a function, and that function is * passed to this function to run asychronously. */ RGraph.Async = function (func) { return setTimeout(func, arguments[1] ? arguments[1] : 1); } /** * A custom random number function * * @param number min The minimum that the number should be * @param number max The maximum that the number should be * @param number How many decimal places there should be. Default for this is 0 */ RGraph.random = function (min, max) { var dp = arguments[2] ? arguments[2] : 0; var r = Math.random(); return Number((((max - min) * r) + min).toFixed(dp)); } /** * Draws a rectangle with curvy corners * * @param context object The context * @param x number The X coordinate (top left of the square) * @param y number The Y coordinate (top left of the square) * @param w number The width of the rectangle * @param h number The height of the rectangle * @param number The radius of the curved corners * @param boolean Whether the top left corner is curvy * @param boolean Whether the top right corner is curvy * @param boolean Whether the bottom right corner is curvy * @param boolean Whether the bottom left corner is curvy */ RGraph.strokedCurvyRect = function (context, x, y, w, h) { // The corner radius var r = arguments[5] ? arguments[5] : 3; // The corners var corner_tl = (arguments[6] || arguments[6] == null) ? true : false; var corner_tr = (arguments[7] || arguments[7] == null) ? true : false; var corner_br = (arguments[8] || arguments[8] == null) ? true : false; var corner_bl = (arguments[9] || arguments[9] == null) ? true : false; context.beginPath(); // Top left side context.moveTo(x + (corner_tl ? r : 0), y); context.lineTo(x + w - (corner_tr ? r : 0), y); // Top right corner if (corner_tr) { context.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2, false); } // Top right side context.lineTo(x + w, y + h - (corner_br ? r : 0) ); // Bottom right corner if (corner_br) { context.arc(x + w - r, y - r + h, r, Math.PI * 2, Math.PI * 0.5, false); } // Bottom right side context.lineTo(x + (corner_bl ? r : 0), y + h); // Bottom left corner if (corner_bl) { context.arc(x + r, y - r + h, r, Math.PI * 0.5, Math.PI, false); } // Bottom left side context.lineTo(x, y + (corner_tl ? r : 0) ); // Top left corner if (corner_tl) { context.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5, false); } context.stroke(); } /** * Draws a filled rectangle with curvy corners * * @param context object The context * @param x number The X coordinate (top left of the square) * @param y number The Y coordinate (top left of the square) * @param w number The width of the rectangle * @param h number The height of the rectangle * @param number The radius of the curved corners * @param boolean Whether the top left corner is curvy * @param boolean Whether the top right corner is curvy * @param boolean Whether the bottom right corner is curvy * @param boolean Whether the bottom left corner is curvy */ RGraph.filledCurvyRect = function (context, x, y, w, h) { // The corner radius var r = arguments[5] ? arguments[5] : 3; // The corners var corner_tl = (arguments[6] || arguments[6] == null) ? true : false; var corner_tr = (arguments[7] || arguments[7] == null) ? true : false; var corner_br = (arguments[8] || arguments[8] == null) ? true : false; var corner_bl = (arguments[9] || arguments[9] == null) ? true : false; context.beginPath(); // First draw the corners // Top left corner if (corner_tl) { context.moveTo(x + r, y + r); context.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI, false); } else { context.fillRect(x, y, r, r); } // Top right corner if (corner_tr) { context.moveTo(x + w - r, y + r); context.arc(x + w - r, y + r, r, 1.5 * Math.PI, 0, false); } else { context.moveTo(x + w - r, y); context.fillRect(x + w - r, y, r, r); } // Bottom right corner if (corner_br) { context.moveTo(x + w - r, y + h - r); context.arc(x + w - r, y - r + h, r, 0, Math.PI / 2, false); } else { context.moveTo(x + w - r, y + h - r); context.fillRect(x + w - r, y + h - r, r, r); } // Bottom left corner if (corner_bl) { context.moveTo(x + r, y + h - r); context.arc(x + r, y - r + h, r, Math.PI / 2, Math.PI, false); } else { context.moveTo(x, y + h - r); context.fillRect(x, y + h - r, r, r); } // Now fill it in context.fillRect(x + r, y, w - r - r, h); context.fillRect(x, y + r, r + 1, h - r - r); context.fillRect(x + w - r - 1, y + r, r + 1, h - r - r); context.fill(); } /** * A crude timing function * * @param string label The label to use for the time */ RGraph.Timer = function (label) { var d = new Date(); // This uses the Firebug console console.log(label + ': ' + d.getSeconds() + '.' + d.getMilliseconds()); } /** * Hides the palette if it's visible */ RGraph.HidePalette = function () { var div = RGraph.Registry.Get('palette'); if (typeof(div) == 'object' && div) { div.style.visibility = 'hidden'; div.style.display = 'none'; RGraph.Registry.Set('palette', null); } } /** * Hides the zoomed canvas */ RGraph.HideZoomedCanvas = function () { if (typeof(__zoomedimage__) == 'object') { obj = __zoomedimage__.obj; } else { return; } if (obj.Get('chart.zoom.fade.out')) { for (var i=10,j=1; i>=0; --i, ++j) { if (typeof(__zoomedimage__) == 'object') { setTimeout("__zoomedimage__.style.opacity = " + String(i / 10), j * 30); } } if (typeof(__zoomedbackground__) == 'object') { setTimeout("__zoomedbackground__.style.opacity = " + String(i / 10), j * 30); } } if (typeof(__zoomedimage__) == 'object') { setTimeout("__zoomedimage__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? 310 : 0); } if (typeof(__zoomedbackground__) == 'object') { setTimeout("__zoomedbackground__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? 310 : 0); } } /** * Adds an event handler * * @param object obj The graph object * @param string event The name of the event, eg ontooltip * @param object func The callback function */ RGraph.AddCustomEventListener = function (obj, name, func) { if (typeof(RGraph.events[obj.id]) == 'undefined') { RGraph.events[obj.id] = []; } RGraph.events[obj.id].push([obj, name, func]); } /** * Used to fire one of the RGraph custom events * * @param object obj The graph object that fires the event * @param string event The name of the event to fire */ RGraph.FireCustomEvent = function (obj, name) { for (i in RGraph.events) { if (typeof(i) == 'string' && i == obj.id && RGraph.events[i].length > 0) { for(var j=0; j<RGraph.events[i].length; ++j) { if (RGraph.events[i][j][1] == name) { RGraph.events[i][j][2](obj); } } } } } /** * Checks the browser for traces of MSIE8 */ RGraph.isIE8 = function () { return navigator.userAgent.indexOf('MSIE 8') > 0; } /** * Checks the browser for traces of MSIE9 */ RGraph.isIE9 = function () { return navigator.userAgent.indexOf('MSIE 9') > 0; } /** * Checks the browser for traces of MSIE9 */ RGraph.isIE9up = function () { navigator.userAgent.match(/MSIE (\d+)/); return Number(RegExp.$1) >= 9; } /** * This clears a canvases event handlers. * * @param string id The ID of the canvas whose event handlers will be cleared */ RGraph.ClearEventListeners = function (id) { for (var i=0; i<RGraph.Registry.Get('chart.event.handlers').length; ++i) { var el = RGraph.Registry.Get('chart.event.handlers')[i]; if (el && (el[0] == id || el[0] == ('window_' + id)) ) { if (el[0].substring(0, 7) == 'window_') { window.removeEventListener(el[1], el[2], false); } else { document.getElementById(id).removeEventListener(el[1], el[2], false); } RGraph.Registry.Get('chart.event.handlers')[i] = null; } } } /** * */ RGraph.AddEventListener = function (id, e, func) { RGraph.Registry.Get('chart.event.handlers').push([id, e, func]); } /** * This function suggests a gutter size based on the widest left label. Given that the bottom * labels may be longer, this may be a little out. * * @param object obj The graph object * @param array data An array of graph data * @return int A suggested gutter setting */ RGraph.getGutterSuggest = function (obj, data) { var str = RGraph.number_format(obj, RGraph.array_max(RGraph.getScale(RGraph.array_max(data), obj)), obj.Get('chart.units.pre'), obj.Get('chart.units.post')); // Take into account the HBar if (obj.type == 'hbar') { var str = ''; var len = 0; for (var i=0; i<obj.Get('chart.labels').length; ++i) { str = (obj.Get('chart.labels').length > str.length ? obj.Get('chart.labels')[i] : str); } } obj.context.font = obj.Get('chart.text.size') + 'pt ' + obj.Get('chart.text.font'); len = obj.context.measureText(str).width + 5; return (obj.type == 'hbar' ? len / 3 : len); } /** * A basic Array shift gunction * * @param object The numerical array to work on * @return The new array */ RGraph.array_shift = function (arr) { var ret = []; for (var i=1; i<arr.length; ++i) ret.push(arr[i]); return ret; } /** * If you prefer, you can use the SetConfig() method to set the configuration information * for your chart. You may find that setting the configuration this way eases reuse. * * @param object obj The graph object * @param object config The graph configuration information */ RGraph.SetConfig = function (obj, config) { for (i in config) { if (typeof(i) == 'string') { obj.Set(i, config[i]); } } return obj; } /** * This function gets the canvas height. Defaults to the actual * height but this can be changed by setting chart.height. * * @param object obj The graph object */ RGraph.GetHeight = function (obj) { var height = obj.Get('chart.height'); return height ? height : obj.canvas.height; } /** * This function gets the canvas width. Defaults to the actual * width but this can be changed by setting chart.width. * * @param object obj The graph object */ RGraph.GetWidth = function (obj) { var width = obj.Get('chart.width'); return width ? width : obj.canvas.width; }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ if (typeof(RGraph) == 'undefined') RGraph = {}; /** * The scatter graph constructor * * @param object canvas The cxanvas object * @param array data The chart data */ RGraph.Scatter = function (id, data) { // Get the canvas and context objects this.id = id; this.canvas = document.getElementById(id); this.canvas.__object__ = this; this.context = this.canvas.getContext ? this.canvas.getContext("2d") : null; this.max = 0; this.coords = []; this.data = []; this.type = 'scatter'; this.isRGraph = true; /** * Compatibility with older browsers */ RGraph.OldBrowserCompat(this.context); // Various config properties this.properties = { 'chart.background.barcolor1': 'white', 'chart.background.barcolor2': 'white', 'chart.background.grid': true, 'chart.background.grid.width': 1, 'chart.background.grid.color': '#ddd', 'chart.background.grid.hsize': 20, 'chart.background.grid.vsize': 20, 'chart.background.hbars': null, 'chart.background.vbars': null, 'chart.background.grid.vlines': true, 'chart.background.grid.hlines': true, 'chart.background.grid.border': true, 'chart.background.grid.autofit':false, 'chart.background.grid.autofit.numhlines': 7, 'chart.background.grid.autofit.numvlines': 20, 'chart.text.size': 10, 'chart.text.angle': 0, 'chart.text.color': 'black', 'chart.text.font': 'Verdana', 'chart.tooltips.effect': 'fade', 'chart.tooltips.hotspot': 3, 'chart.tooltips.css.class': 'RGraph_tooltip', 'chart.tooltips.highlight': true, 'chart.tooltips.coords.adjust': [0,0], 'chart.units.pre': '', 'chart.units.post': '', 'chart.tickmarks': 'cross', 'chart.ticksize': 5, 'chart.xticks': true, 'chart.xaxis': true, 'chart.gutter': 25, 'chart.xmax': 0, 'chart.ymax': null, 'chart.ymin': null, 'chart.scale.decimals': null, 'chart.scale.point': '.', 'chart.scale.thousand': ',', 'chart.title': '', 'chart.title.background': null, 'chart.title.hpos': null, 'chart.title.vpos': null, 'chart.title.xaxis': '', 'chart.title.yaxis': '', 'chart.title.xaxis.pos': 0.25, 'chart.title.yaxis.pos': 0.25, 'chart.labels': [], 'chart.ylabels': true, 'chart.ylabels.count': 5, 'chart.contextmenu': null, 'chart.defaultcolor': 'black', 'chart.xaxispos': 'bottom', 'chart.yaxispos': 'left', 'chart.noendxtick': false, 'chart.crosshairs': false, 'chart.crosshairs.color': '#333', 'chart.crosshairs.linewidth': 1, 'chart.crosshairs.coords': false, 'chart.crosshairs.coords.fixed':true, 'chart.crosshairs.coords.fadeout':false, 'chart.crosshairs.coords.labels.x': 'X', 'chart.crosshairs.coords.labels.y': 'Y', 'chart.annotatable': false, 'chart.annotate.color': 'black', 'chart.line': false, 'chart.line.linewidth': 1, 'chart.line.colors': ['green', 'red'], 'chart.line.shadow.color': 'rgba(0,0,0,0)', 'chart.line.shadow.blur': 2, 'chart.line.shadow.offsetx': 3, 'chart.line.shadow.offsety': 3, 'chart.line.stepped': false, 'chart.noaxes': false, 'chart.key': [], 'chart.key.background': 'white', 'chart.key.position': 'graph', 'chart.key.shadow': false, 'chart.key.shadow.color': '#666', 'chart.key.shadow.blur': 3, 'chart.key.shadow.offsetx': 2, 'chart.key.shadow.offsety': 2, 'chart.key.position.gutter.boxed': true, 'chart.key.position.x': null, 'chart.key.position.y': null, 'chart.key.color.shape': 'square', 'chart.key.rounded': true, 'chart.axis.color': 'black', 'chart.zoom.factor': 1.5, 'chart.zoom.fade.in': true, 'chart.zoom.fade.out': true, 'chart.zoom.hdir': 'right', 'chart.zoom.vdir': 'down', 'chart.zoom.frames': 10, 'chart.zoom.delay': 50, 'chart.zoom.shadow': true, 'chart.zoom.mode': 'canvas', 'chart.zoom.thumbnail.width': 75, 'chart.zoom.thumbnail.height': 75, 'chart.zoom.background': true, 'chart.zoom.action': 'zoom', 'chart.boxplot.width': 8, 'chart.resizable': false, 'chart.xmin': 0 } // Handle multiple datasets being given as one argument if (arguments[1][0] && arguments[1][0][0] && typeof(arguments[1][0][0][0]) == 'number') { // Store the data set(s) for (var i=0; i<arguments[1].length; ++i) { this.data[i] = arguments[1][i]; } // Handle multiple data sets being supplied as seperate arguments } else { // Store the data set(s) for (var i=1; i<arguments.length; ++i) { this.data[i - 1] = arguments[i]; } } // Check for support if (!this.canvas) { alert('[SCATTER] No canvas support'); return; } // Check the common library has been included if (typeof(RGraph) == 'undefined') { alert('[SCATTER] Fatal error: The common library does not appear to have been included'); } } /** * A simple setter * * @param string name The name of the property to set * @param string value The value of the property */ RGraph.Scatter.prototype.Set = function (name, value) { /** * This is here because the key expects a name of "chart.colors" */ if (name == 'chart.line.colors') { this.properties['chart.colors'] = value; } /** * Allow compatibility with older property names */ if (name == 'chart.tooltip.hotspot') { name = 'chart.tooltips.hotspot'; } /** * chart.yaxispos should be left or right */ if (name == 'chart.yaxispos' && value != 'left' && value != 'right') { alert("[SCATTER] chart.yaxispos should be left or right. You've set it to: '" + value + "' Changing it to left"); value = 'left'; } this.properties[name.toLowerCase()] = value; } /** * A simple getter * * @param string name The name of the property to set */ RGraph.Scatter.prototype.Get = function (name) { return this.properties[name]; } /** * The function you call to draw the line chart */ RGraph.Scatter.prototype.Draw = function () { /** * Fire the onbeforedraw event */ RGraph.FireCustomEvent(this, 'onbeforedraw'); /** * Clear all of this canvases event handlers (the ones installed by RGraph) */ RGraph.ClearEventListeners(this.id); // Go through all the data points and see if a tooltip has been given this.Set('chart.tooltips', false); this.hasTooltips = false; var overHotspot = false; // Reset the coords array this.coords = []; if (!RGraph.isIE8()) { for (var i=0; i<this.data.length; ++i) { for (var j =0;j<this.data[i].length; ++j) { if (this.data[i][j] && this.data[i][j][3] && typeof(this.data[i][j][3]) == 'string' && this.data[i][j][3].length) { this.Set('chart.tooltips', [1]); // An array this.hasTooltips = true; } } } } // Reset the maximum value this.max = 0; // Work out the maximum Y value if (this.Get('chart.ymax') && this.Get('chart.ymax') > 0) { this.scale = []; this.max = this.Get('chart.ymax'); this.min = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; this.scale[0] = ((this.max - this.min) * (1/5)) + this.min; this.scale[1] = ((this.max - this.min) * (2/5)) + this.min; this.scale[2] = ((this.max - this.min) * (3/5)) + this.min; this.scale[3] = ((this.max - this.min) * (4/5)) + this.min; this.scale[4] = ((this.max - this.min) * (5/5)) + this.min; var decimals = this.Get('chart.scale.decimals'); this.scale = [ Number(this.scale[0]).toFixed(decimals), Number(this.scale[1]).toFixed(decimals), Number(this.scale[2]).toFixed(decimals), Number(this.scale[3]).toFixed(decimals), Number(this.scale[4]).toFixed(decimals) ]; } else { var i = 0; var j = 0; for (i=0; i<this.data.length; ++i) { for (j=0; j<this.data[i].length; ++j) { this.max = Math.max(this.max, typeof(this.data[i][j][1]) == 'object' ? RGraph.array_max(this.data[i][j][1]) : Math.abs(this.data[i][j][1])); } } this.scale = RGraph.getScale(this.max, this); this.max = this.scale[4]; this.min = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; if (this.min) { this.scale[0] = ((this.max - this.min) * (1/5)) + this.min; this.scale[1] = ((this.max - this.min) * (2/5)) + this.min; this.scale[2] = ((this.max - this.min) * (3/5)) + this.min; this.scale[3] = ((this.max - this.min) * (4/5)) + this.min; this.scale[4] = ((this.max - this.min) * (5/5)) + this.min; } if (typeof(this.Get('chart.scale.decimals')) == 'number') { var decimals = this.Get('chart.scale.decimals'); this.scale = [ Number(this.scale[0]).toFixed(decimals), Number(this.scale[1]).toFixed(decimals), Number(this.scale[2]).toFixed(decimals), Number(this.scale[3]).toFixed(decimals), Number(this.scale[4]).toFixed(decimals) ]; } } this.grapharea = this.canvas.height - (2 * this.Get('chart.gutter')); // Progressively Draw the chart RGraph.background.Draw(this); /** * Draw any horizontal bars that have been specified */ if (this.Get('chart.background.hbars') && this.Get('chart.background.hbars').length) { RGraph.DrawBars(this); } /** * Draw any vertical bars that have been specified */ if (this.Get('chart.background.vbars') && this.Get('chart.background.vbars').length) { this.DrawVBars(); } if (!this.Get('chart.noaxes')) { this.DrawAxes(); } this.DrawLabels(); i = 0; for(i=0; i<this.data.length; ++i) { this.DrawMarks(i); // Set the shadow this.context.shadowColor = this.Get('chart.line.shadow.color'); this.context.shadowOffsetX = this.Get('chart.line.shadow.offsetx'); this.context.shadowOffsetY = this.Get('chart.line.shadow.offsety'); this.context.shadowBlur = this.Get('chart.line.shadow.blur'); this.DrawLine(i); // Turn the shadow off RGraph.NoShadow(this); } if (this.Get('chart.line')) { for (var i=0;i<this.data.length; ++i) { this.DrawMarks(i); // Call this again so the tickmarks appear over the line } } /** * Setup the context menu if required */ if (this.Get('chart.contextmenu')) { RGraph.ShowContext(this); } /** * Install the event handler for tooltips */ if (this.hasTooltips) { /** * Register all charts */ RGraph.Register(this); var overHotspot = false; var canvas_onmousemove_func = function (e) { e = RGraph.FixEventObject(e); var canvas = e.target; var obj = canvas.__object__; var context = canvas.getContext('2d'); var mouseCoords = RGraph.getMouseXY(e); var overHotspot = false; /** * Now loop through each point comparing the coords */ var offset = obj.Get('chart.tooltips.hotspot'); // This is how far the hotspot extends for (var set=0; set<obj.coords.length; ++set) { for (var i=0; i<obj.coords[set].length; ++i) { var adjust = obj.Get('chart.tooltips.coords.adjust'); var xCoord = obj.coords[set][i][0] + adjust[0]; var yCoord = obj.coords[set][i][1] + adjust[1]; var tooltip = obj.coords[set][i][2]; if (mouseCoords[0] <= (xCoord + offset) && mouseCoords[0] >= (xCoord - offset) && mouseCoords[1] <= (yCoord + offset) && mouseCoords[1] >= (yCoord - offset) && tooltip && tooltip.length > 0) { overHotspot = true; canvas.style.cursor = 'pointer'; if ( !RGraph.Registry.Get('chart.tooltip') || RGraph.Registry.Get('chart.tooltip').__text__ != tooltip || RGraph.Registry.Get('chart.tooltip').__index__ != i || RGraph.Registry.Get('chart.tooltip').__dataset__ != set ) { if (obj.Get('chart.tooltips.highlight')) { RGraph.Redraw(); } /** * Get the tooltip text */ if (typeof(tooltip) == 'function') { var text = String(tooltip(i)); } else { var text = String(tooltip); } RGraph.Tooltip(canvas, text, e.pageX, e.pageY, i); RGraph.Registry.Get('chart.tooltip').__dataset__ = set; /** * Draw a circle around the mark */ if (obj.Get('chart.tooltips.highlight')) { context.beginPath(); context.fillStyle = 'rgba(255,255,255,0.5)'; context.arc(xCoord, yCoord, 3, 0, 6.28, 0); context.fill(); } } } } } /** * Reset the pointer */ if (!overHotspot) { canvas.style.cursor = 'default'; } } this.canvas.addEventListener('mousemove', canvas_onmousemove_func, false); RGraph.AddEventListener(this.id, 'mousemove', canvas_onmousemove_func); } /** * Draw the key if necessary */ if (this.Get('chart.key') && this.Get('chart.key').length) { RGraph.DrawKey(this, this.Get('chart.key'), this.Get('chart.line.colors')); } /** * Draw crosschairs */ RGraph.DrawCrosshairs(this); /** * If the canvas is annotatable, do install the event handlers */ if (this.Get('chart.annotatable')) { RGraph.Annotate(this); } /** * This bit shows the mini zoom window if requested */ if (this.Get('chart.zoom.mode') == 'thumbnail' || this.Get('chart.zoom.mode') == 'area') { RGraph.ShowZoomWindow(this); } /** * This function enables resizing */ if (this.Get('chart.resizable')) { RGraph.AllowResizing(this); } /** * Fire the RGraph ondraw event */ RGraph.FireCustomEvent(this, 'ondraw'); } /** * Draws the axes of the scatter graph */ RGraph.Scatter.prototype.DrawAxes = function () { var canvas = this.canvas; var context = this.context; var graphHeight = this.canvas.height - (this.Get('chart.gutter') * 2); var gutter = this.Get('chart.gutter'); context.beginPath(); context.strokeStyle = this.Get('chart.axis.color'); context.lineWidth = 1; // Draw the Y axis if (this.Get('chart.yaxispos') == 'left') { context.moveTo(gutter, gutter); context.lineTo(gutter, this.canvas.height - gutter); } else { context.moveTo(canvas.width - gutter, gutter); context.lineTo(canvas.width - gutter, canvas.height - gutter); } // Draw the X axis if (this.Get('chart.xaxis')) { if (this.Get('chart.xaxispos') == 'center') { context.moveTo(gutter, canvas.height / 2); context.lineTo(canvas.width - gutter, canvas.height / 2); } else { context.moveTo(gutter, canvas.height - gutter); context.lineTo(canvas.width - gutter, canvas.height - gutter); } } /** * Draw the Y tickmarks */ for (y=gutter; y < canvas.height - gutter + (this.Get('chart.xaxispos') == 'center' ? 1 : 0) ; y+=(graphHeight / 5) / 2) { // This is here to accomodate the X axis being at the center if (y == (canvas.height / 2) ) continue; if (this.Get('chart.yaxispos') == 'left') { context.moveTo(gutter, y); context.lineTo(gutter - 3, y); } else { context.moveTo(canvas.width - gutter +3, y); context.lineTo(canvas.width - gutter, y); } } /** * Draw the X tickmarks */ if (this.Get('chart.xticks') && this.Get('chart.xaxis')) { var x = 0; var y = (this.Get('chart.xaxispos') == 'center') ? (this.canvas.height / 2) : (this.canvas.height - gutter); this.xTickGap = (this.canvas.width - (2 * gutter) ) / this.Get('chart.labels').length; for (x = (gutter + (this.Get('chart.yaxispos') == 'left' ? this.xTickGap / 2 : 0) ); x<=(canvas.width - gutter - (this.Get('chart.yaxispos') == 'left' ? 0 : 1)); x += this.xTickGap / 2) { if (this.Get('chart.yaxispos') == 'left' && this.Get('chart.noendxtick') == true && x == (canvas.width - gutter) ) { continue; } else if (this.Get('chart.yaxispos') == 'right' && this.Get('chart.noendxtick') == true && x == gutter) { continue; } context.moveTo(x, y - (this.Get('chart.xaxispos') == 'center' ? 3 : 0)); context.lineTo(x, y + 3); } } context.stroke(); } /** * Draws the labels on the scatter graph */ RGraph.Scatter.prototype.DrawLabels = function () { this.context.fillStyle = this.Get('chart.text.color'); var font = this.Get('chart.text.font'); var xMin = this.Get('chart.xmin'); var xMax = this.Get('chart.xmax'); var yMax = this.scale[4]; var gutter = this.Get('chart.gutter'); var text_size = this.Get('chart.text.size'); var units_pre = this.Get('chart.units.pre'); var units_post = this.Get('chart.units.post'); var numYLabels = this.Get('chart.ylabels.count'); var context = this.context; var canvas = this.canvas; this.halfTextHeight = text_size / 2; this.halfGraphHeight = (this.canvas.height - (2 * this.Get('chart.gutter'))) / 2; /** * Draw the Y yaxis labels, be it at the top or center */ if (this.Get('chart.ylabels')) { var xPos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : canvas.width - gutter + 5; var align = this.Get('chart.yaxispos') == 'right' ? 'left' : 'right'; if (this.Get('chart.xaxispos') == 'center') { /** * Specific Y labels */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); for (var i=0; i<this.Get('chart.ylabels.specific').length; ++i) { var y = gutter + (i * (this.grapharea / (labels.length * 2) ) ); RGraph.Text(context, font, text_size, xPos, y, labels[i], 'center', align); } var reversed_labels = RGraph.array_reverse(labels); for (var i=0; i<reversed_labels.length; ++i) { var y = gutter + (this.grapharea / 2) + ((i+1) * (this.grapharea / (labels.length * 2) ) ); RGraph.Text(context, font, text_size, xPos, y, reversed_labels[i], 'center', align); } return; } if (numYLabels == 1 || numYLabels == 3 || numYLabels == 5) { // Draw the top halves labels RGraph.Text(context, font, text_size, xPos, gutter, RGraph.number_format(this, this.scale[4], units_pre, units_post), 'center', align); if (numYLabels >= 5) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (1/10) ), RGraph.number_format(this, this.scale[3], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (3/10) ), RGraph.number_format(this, this.scale[1], units_pre, units_post), 'center', align); } if (numYLabels >= 3) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (2/10) ), RGraph.number_format(this, this.scale[2], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (4/10) ), RGraph.number_format(this, this.scale[0], units_pre, units_post), 'center', align); } // Draw the bottom halves labels if (numYLabels >= 3) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (1/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[0], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (3/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[2], units_pre, units_post), 'center', align); } if (numYLabels == 5) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (2/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[1], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (4/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[3], units_pre, units_post), 'center', align); } RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (5/10) ) + this.halfGraphHeight, '-' + RGraph.number_format(this, this.scale[4], units_pre, units_post), 'center', align); } else if (numYLabels == 10) { // 10 Y labels var interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xPos,gutter + ((canvas.height - (2 * gutter)) * (i/20) ),RGraph.number_format(this, (this.max - (this.max * (i/10))).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post),'center', align); RGraph.Text(context, font, text_size, xPos,gutter + ((canvas.height - (2 * gutter)) * (i/20) ) + (this.grapharea / 2) + (this.grapharea / 20),'-' + RGraph.number_format(this, ((this.max * (i/10)) + (this.max * (1/10))).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align); } } else { alert('[SCATTER SCALE] Number of Y labels can be 1/3/5/10 only'); } } else { var xPos = this.Get('chart.yaxispos') == 'left' ? gutter - 5 : canvas.width - gutter + 5; var align = this.Get('chart.yaxispos') == 'right' ? 'left' : 'right'; /** * Specific Y labels */ if (typeof(this.Get('chart.ylabels.specific')) == 'object') { var labels = this.Get('chart.ylabels.specific'); for (var i=0; i<this.Get('chart.ylabels.specific').length; ++i) { var y = gutter + (i * (this.grapharea / labels.length) ); RGraph.Text(context, font, text_size, xPos, y, labels[i], 'center', align); } return; } if (numYLabels == 1 || numYLabels == 3 || numYLabels == 5) { RGraph.Text(context, font, text_size, xPos, gutter, RGraph.number_format(this, this.scale[4], units_pre, units_post), 'center', align); if (numYLabels >= 5) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (1/5) ), RGraph.number_format(this, this.scale[3], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (3/5) ), RGraph.number_format(this, this.scale[1], units_pre, units_post), 'center', align); } if (numYLabels >= 3) { RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (2/5) ), RGraph.number_format(this, this.scale[2], units_pre, units_post), 'center', align); RGraph.Text(context, font, text_size, xPos, gutter + ((canvas.height - (2 * gutter)) * (4/5) ), RGraph.number_format(this, this.scale[0], units_pre, units_post), 'center', align); } } else if (numYLabels == 10) { // 10 Y labels var interval = (this.grapharea / numYLabels) / 2; for (var i=0; i<numYLabels; ++i) { RGraph.Text(context, font, text_size, xPos,gutter + ((canvas.height - (2 * gutter)) * (i/10) ),RGraph.number_format(this,(this.max - (this.max * (i/10))).toFixed((this.Get('chart.scale.decimals'))), units_pre, units_post), 'center', align); } } else { alert('[SCATTER SCALE] Number of Y labels can be 1/3/5/10 only'); } if (this.Get('chart.ymin')) { RGraph.Text(context, font, text_size, xPos, canvas.height - gutter,RGraph.number_format(this, this.Get('chart.ymin').toFixed(this.Get('chart.scale.decimals')), units_pre, units_post),'center', align); } } } // Put the text on the X axis var graphArea = this.canvas.width - (2 * gutter); var xInterval = graphArea / this.Get('chart.labels').length; var xPos = gutter; var yPos = (this.canvas.height - gutter) + 15; var labels = this.Get('chart.labels'); /** * Text angle */ var angle = 0; var valign = null; var halign = 'center'; if (this.Get('chart.text.angle') > 0) { angle = -1 * this.Get('chart.text.angle'); valign = 'center'; halign = 'right'; yPos -= 10; } for (i=0; i<labels.length; ++i) { if (typeof(labels[i]) == 'object') { RGraph.Text(context, font, this.Get('chart.text.size'), gutter + (graphArea * ((labels[i][1] - xMin) / (this.Get('chart.xmax') - xMin))) + 5, yPos, String(labels[i][0]), valign, angle != 0 ? 'right' : 'left', null, angle); /** * Draw the gray indicator line */ this.context.beginPath(); this.context.strokeStyle = '#bbb'; this.context.moveTo(gutter + (graphArea * ((labels[i][1] - xMin)/ (this.Get('chart.xmax') - xMin))), this.canvas.height - gutter); this.context.lineTo(gutter + (graphArea * ((labels[i][1] - xMin)/ (this.Get('chart.xmax') - xMin))), this.canvas.height - gutter + 20); this.context.stroke(); } else { RGraph.Text(context, font, this.Get('chart.text.size'), xPos + (this.xTickGap / 2), yPos, String(labels[i]), valign, halign, null, angle); } // Do this for the next time around xPos += xInterval; } } /** * Draws the actual scatter graph marks * * @param i integer The dataset index */ RGraph.Scatter.prototype.DrawMarks = function (i) { /** * Reset the coords array */ this.coords[i] = []; /** * Plot the values */ var xmax = this.Get('chart.xmax'); var default_color = this.Get('chart.defaultcolor'); for (var j=0; j<this.data[i].length; ++j) { /** * This is here because tooltips are optional */ var data_point = this.data[i]; var xCoord = data_point[j][0]; var yCoord = data_point[j][1]; var color = data_point[j][2] ? data_point[j][2] : default_color; var tooltip = (data_point[j] && data_point[j][3]) ? data_point[j][3] : null; this.DrawMark( i, xCoord, yCoord, xmax, this.scale[4], color, tooltip, this.coords[i], data_point ); } } /** * Draws a single scatter mark */ RGraph.Scatter.prototype.DrawMark = function (index, x, y, xMax, yMax, color, tooltip, coords, data) { var tickmarks = this.Get('chart.tickmarks'); var tickSize = this.Get('chart.ticksize'); var gutter = this.Get('chart.gutter'); var xMin = this.Get('chart.xmin'); var x = ((x - xMin) / (xMax - xMin)) * (this.canvas.width - (2 * gutter)); var originalX = x; var originalY = y; /** * This allows chart.tickmarks to be an array */ if (tickmarks && typeof(tickmarks) == 'object') { tickmarks = tickmarks[index]; } /** * This allows chart.ticksize to be an array */ if (typeof(tickSize) == 'object') { var tickSize = tickSize[index]; var halfTickSize = tickSize / 2; } else { var halfTickSize = tickSize / 2; } /** * This bit is for boxplots only */ if ( typeof(y) == 'object' && typeof(y[0]) == 'number' && typeof(y[1]) == 'number' && typeof(y[2]) == 'number' && typeof(y[3]) == 'number' && typeof(y[4]) == 'number' ) { var yMin = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; this.Set('chart.boxplot', true); this.graphheight = this.canvas.height - (2 * gutter); if (this.Get('chart.xaxispos') == 'center') { this.graphheight /= 2; } var y0 = (this.graphheight) - ((y[4] - yMin) / (yMax - yMin)) * (this.graphheight); var y1 = (this.graphheight) - ((y[3] - yMin) / (yMax - yMin)) * (this.graphheight); var y2 = (this.graphheight) - ((y[2] - yMin) / (yMax - yMin)) * (this.graphheight); var y3 = (this.graphheight) - ((y[1] - yMin) / (yMax - yMin)) * (this.graphheight); var y4 = (this.graphheight) - ((y[0] - yMin) / (yMax - yMin)) * (this.graphheight); var col1 = y[5]; var col2 = y[6]; // Override the boxWidth if (typeof(y[7]) == 'number') { var boxWidth = y[7]; } var y = this.graphheight - y2; } else { var yMin = this.Get('chart.ymin') ? this.Get('chart.ymin') : 0; var y = (( (y - yMin) / (yMax - yMin)) * (this.canvas.height - (2 * gutter))); } /** * Account for the X axis being at the centre */ if (this.Get('chart.xaxispos') == 'center') { y /= 2; y += this.halfGraphHeight; } // This is so that points are on the graph, and not the gutter x += gutter; y = this.canvas.height - gutter - y; this.context.beginPath(); // Color this.context.strokeStyle = color; /** * Boxplots */ if ( this.Get('chart.boxplot') && typeof(y0) == 'number' && typeof(y1) == 'number' && typeof(y2) == 'number' && typeof(y3) == 'number' && typeof(y4) == 'number' ) { var boxWidth = boxWidth ? boxWidth : this.Get('chart.boxplot.width'); var halfBoxWidth = boxWidth / 2; this.context.beginPath(); // Draw the upper coloured box if a value is specified if (col1) { this.context.fillStyle = col1; this.context.fillRect(x - halfBoxWidth, y1 + gutter, boxWidth, y2 - y1); } // Draw the lower coloured box if a value is specified if (col2) { this.context.fillStyle = col2; this.context.fillRect(x - halfBoxWidth, y2 + gutter, boxWidth, y3 - y2); } this.context.strokeRect(x - halfBoxWidth, y1 + gutter, boxWidth, y3 - y1); this.context.stroke(); // Now draw the whiskers this.context.beginPath(); this.context.moveTo(x - halfBoxWidth, y0 + gutter); this.context.lineTo(x + halfBoxWidth, y0 + gutter); this.context.moveTo(x, y0 + gutter); this.context.lineTo(x, y1 + gutter); this.context.moveTo(x - halfBoxWidth, y4 + gutter); this.context.lineTo(x + halfBoxWidth, y4 + gutter); this.context.moveTo(x, y4 + gutter); this.context.lineTo(x, y3 + gutter); this.context.stroke(); } /** * Draw the tickmark, but not for boxplots */ if (!y0 && !y1 && !y2 && !y3 && !y4) { this.graphheight = this.canvas.height - (2 * gutter); if (tickmarks == 'circle') { this.context.arc(x, y, halfTickSize, 0, 6.28, 0); this.context.fillStyle = color; this.context.fill(); } else if (tickmarks == 'plus') { this.context.moveTo(x, y - halfTickSize); this.context.lineTo(x, y + halfTickSize); this.context.moveTo(x - halfTickSize, y); this.context.lineTo(x + halfTickSize, y); this.context.stroke(); } else if (tickmarks == 'square') { this.context.strokeStyle = color; this.context.fillStyle = color; this.context.fillRect( x - halfTickSize, y - halfTickSize, tickSize, tickSize ); //this.context.fill(); } else if (tickmarks == 'cross') { this.context.moveTo(x - halfTickSize, y - halfTickSize); this.context.lineTo(x + halfTickSize, y + halfTickSize); this.context.moveTo(x + halfTickSize, y - halfTickSize); this.context.lineTo(x - halfTickSize, y + halfTickSize); this.context.stroke(); /** * Diamond shape tickmarks */ } else if (tickmarks == 'diamond') { this.context.fillStyle = this.context.strokeStyle; this.context.moveTo(x, y - halfTickSize); this.context.lineTo(x + halfTickSize, y); this.context.lineTo(x, y + halfTickSize); this.context.lineTo(x - halfTickSize, y); this.context.lineTo(x, y - halfTickSize); this.context.fill(); this.context.stroke(); /** * Custom tickmark style */ } else if (typeof(tickmarks) == 'function') { var graphWidth = this.canvas.width - (2 * this.Get('chart.gutter')) var xVal = ((x - this.Get('chart.gutter')) / graphWidth) * xMax; var yVal = ((this.graphheight - (y - this.Get('chart.gutter'))) / this.graphheight) * yMax; tickmarks(this, data, x, y, xVal, yVal, xMax, yMax, color) /** * No tickmarks */ } else if (tickmarks == null) { /** * Unknown tickmark type */ } else { alert('[SCATTER] (' + this.id + ') Unknown tickmark style: ' + tickmarks ); } } /** * Add the tickmark to the coords array */ coords.push([x, y, tooltip]); } /** * Draws an optional line connecting the tick marks. * * @param i The index of the dataset to use */ RGraph.Scatter.prototype.DrawLine = function (i) { if (this.Get('chart.line') && this.coords[i].length >= 2) { this.context.lineCap = 'round'; this.context.lineJoin = 'round'; this.context.lineWidth = this.GetLineWidth(i);// i is the index of the set of coordinates this.context.strokeStyle = this.Get('chart.line.colors')[i]; this.context.beginPath(); var len = this.coords[i].length; for (var j=0; j<this.coords[i].length; ++j) { var xPos = this.coords[i][j][0]; var yPos = this.coords[i][j][1]; if (j == 0) { this.context.moveTo(xPos, yPos); } else { // Stepped? var stepped = this.Get('chart.line.stepped'); if ( (typeof(stepped) == 'boolean' && stepped) || (typeof(stepped) == 'object' && stepped[i]) ) { this.context.lineTo(this.coords[i][j][0], this.coords[i][j - 1][1]); } this.context.lineTo(xPos, yPos); } } this.context.stroke(); } /** * Set the linewidth back to 1 */ this.context.lineWidth = 1; } /** * Returns the linewidth * * @param number i The index of the "line" (/set of coordinates) */ RGraph.Scatter.prototype.GetLineWidth = function (i) { var linewidth = this.Get('chart.line.linewidth'); if (typeof(linewidth) == 'number') { return linewidth; } else if (typeof(linewidth) == 'object') { if (linewidth[i]) { return linewidth[i]; } else { return linewidth[0]; } alert('[SCATTER] Error! chart.linewidth should be a single number or an array of one or more numbers'); } } /** * Draws vertical bars. Line chart doesn't use a horizontal scale, hence this function * is not common */ RGraph.Scatter.prototype.DrawVBars = function () { var canvas = this.canvas; var context = this.context; var vbars = this.Get('chart.background.vbars'); var gutter = this.Get('chart.gutter'); var graphWidth = canvas.width - gutter - gutter; if (vbars) { var xmax = this.Get('chart.xmax'); for (var i=0; i<vbars.length; ++i) { var startX = ((vbars[i][0] / xmax) * graphWidth) + gutter; var width = (vbars[i][1] / xmax) * graphWidth; context.beginPath(); context.fillStyle = vbars[i][2]; context.fillRect(startX, gutter, width, (canvas.height - gutter - gutter)); context.fill(); } } }
JavaScript
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ if (typeof(RGraph) == 'undefined') RGraph = {isRGraph:true,type:'common'}; /** * This is used in two functions, hence it's here */ RGraph.tooltips = {}; RGraph.tooltips.padding = '3px'; RGraph.tooltips.font_face = 'Tahoma'; RGraph.tooltips.font_size = '10pt'; /** * Shows a tooltip next to the mouse pointer * * @param canvas object The canvas element object * @param text string The tooltip text * @param int x The X position that the tooltip should appear at. Combined with the canvases offsetLeft * gives the absolute X position * @param int y The Y position the tooltip should appear at. Combined with the canvases offsetTop * gives the absolute Y position * @param int idx The index of the tooltip in the graph objects tooltip array */ RGraph.Tooltip = function (canvas, text, x, y, idx) { /** * chart.tooltip.override allows you to totally take control of rendering the tooltip yourself */ if (typeof(canvas.__object__.Get('chart.tooltips.override')) == 'function') { return canvas.__object__.Get('chart.tooltips.override')(canvas, text, x, y, idx); } /** * This facilitates the "id:xxx" format */ text = RGraph.getTooltipText(text); /** * First clear any exising timers */ var timers = RGraph.Registry.Get('chart.tooltip.timers'); if (timers && timers.length) { for (i=0; i<timers.length; ++i) { clearTimeout(timers[i]); } } RGraph.Registry.Set('chart.tooltip.timers', []); /** * Hide the context menu if it's currently shown */ if (canvas.__object__.Get('chart.contextmenu')) { RGraph.HideContext(); } // Redraw the canvas? if (canvas.__object__.Get('chart.tooltips.highlight')) { RGraph.Redraw(canvas.id); } var effect = canvas.__object__.Get('chart.tooltips.effect').toLowerCase(); if (effect == 'snap' && RGraph.Registry.Get('chart.tooltip')) { if ( canvas.__object__.type == 'line' || canvas.__object__.type == 'tradar' || canvas.__object__.type == 'scatter' || canvas.__object__.type == 'rscatter' ) { var tooltipObj = RGraph.Registry.Get('chart.tooltip'); tooltipObj.style.width = null; tooltipObj.style.height = null; tooltipObj.innerHTML = text; tooltipObj.__text__ = text; /** * Now that the new content has been set, re-set the width & height */ RGraph.Registry.Get('chart.tooltip').style.width = RGraph.getTooltipWidth(text, canvas.__object__) + 'px'; RGraph.Registry.Get('chart.tooltip').style.height = RGraph.Registry.Get('chart.tooltip').offsetHeight - (RGraph.isIE9up() ? 7 : 0) + 'px'; var currentx = parseInt(RGraph.Registry.Get('chart.tooltip').style.left); var currenty = parseInt(RGraph.Registry.Get('chart.tooltip').style.top); var diffx = x - currentx - ((x + RGraph.Registry.Get('chart.tooltip').offsetWidth) > document.body.offsetWidth ? RGraph.Registry.Get('chart.tooltip').offsetWidth : 0); var diffy = y - currenty - RGraph.Registry.Get('chart.tooltip').offsetHeight; // Position the tooltip setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.2)) + 'px"', 25); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.4)) + 'px"', 50); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.6)) + 'px"', 75); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 0.8)) + 'px"', 100); setTimeout('RGraph.Registry.Get("chart.tooltip").style.left = "' + (currentx + (diffx * 1.0)) + 'px"', 125); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.2)) + 'px"', 25); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.4)) + 'px"', 50); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.6)) + 'px"', 75); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 0.8)) + 'px"', 100); setTimeout('RGraph.Registry.Get("chart.tooltip").style.top = "' + (currenty + (diffy * 1.0)) + 'px"', 125); } else { alert('[TOOLTIPS] The "snap" effect is only supported on the Line, Rscatter, Scatter and Tradar charts'); } /** * Fire the tooltip event */ RGraph.FireCustomEvent(canvas.__object__, 'ontooltip'); return; } /** * Hide any currently shown tooltip */ RGraph.HideTooltip(); /** * Show a tool tip */ var tooltipObj = document.createElement('DIV'); tooltipObj.className = canvas.__object__.Get('chart.tooltips.css.class'); tooltipObj.style.display = 'none'; tooltipObj.style.position = 'absolute'; tooltipObj.style.left = 0; tooltipObj.style.top = 0; tooltipObj.style.backgroundColor = '#ffe'; tooltipObj.style.color = 'black'; if (!document.all) tooltipObj.style.border = '1px solid rgba(0,0,0,0)'; tooltipObj.style.visibility = 'visible'; tooltipObj.style.paddingLeft = RGraph.tooltips.padding; tooltipObj.style.paddingRight = RGraph.tooltips.padding; tooltipObj.style.fontFamily = RGraph.tooltips.font_face; tooltipObj.style.fontSize = RGraph.tooltips.font_size; tooltipObj.style.zIndex = 3; tooltipObj.style.borderRadius = '5px'; tooltipObj.style.MozBorderRadius = '5px'; tooltipObj.style.WebkitBorderRadius = '5px'; tooltipObj.style.WebkitBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; tooltipObj.style.MozBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; tooltipObj.style.boxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; tooltipObj.style.filter = 'progid:DXImageTransform.Microsoft.Shadow(color=#666666,direction=135)'; tooltipObj.style.opacity = 0; tooltipObj.style.overflow = 'hidden'; tooltipObj.innerHTML = text; tooltipObj.__text__ = text; // This is set because the innerHTML can change when it's set tooltipObj.__canvas__ = canvas; tooltipObj.style.display = 'inline'; if (typeof(idx) == 'number') { tooltipObj.__index__ = idx; } document.body.appendChild(tooltipObj); var width = tooltipObj.offsetWidth; var height = tooltipObj.offsetHeight - (RGraph.isIE9up() ? 7 : 0); if ((y - height - 2) > 0) { y = y - height - 2; } else { y = y + 2; } /** * Set the width on the tooltip so it doesn't resize if the window is resized */ tooltipObj.style.width = width + 'px'; //tooltipObj.style.height = 0; // Initially set the tooltip height to nothing /** * If the mouse is towards the right of the browser window and the tooltip would go outside of the window, * move it left */ if ( (x + width) > document.body.offsetWidth ) { x = x - width - 7; var placementLeft = true; if (canvas.__object__.Get('chart.tooltips.effect') == 'none') { x = x - 3; } tooltipObj.style.left = x + 'px'; tooltipObj.style.top = y + 'px'; } else { x += 5; tooltipObj.style.left = x + 'px'; tooltipObj.style.top = y + 'px'; } if (effect == 'expand') { tooltipObj.style.left = (x + (width / 2)) + 'px'; tooltipObj.style.top = (y + (height / 2)) + 'px'; leftDelta = (width / 2) / 10; topDelta = (height / 2) / 10; tooltipObj.style.width = 0; tooltipObj.style.height = 0; tooltipObj.style.boxShadow = ''; tooltipObj.style.MozBoxShadow = ''; tooltipObj.style.WebkitBoxShadow = ''; tooltipObj.style.borderRadius = 0; tooltipObj.style.MozBorderRadius = 0; tooltipObj.style.WebkitBorderRadius = 0; tooltipObj.style.opacity = 1; // Progressively move the tooltip to where it should be (the x position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) - leftDelta) + 'px' }", 250)); // Progressively move the tooltip to where it should be (the Y position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) - topDelta) + 'px' }", 250)); // Progressively grow the tooltip width RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.1) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.2) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.3) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.4) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.6) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.7) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.8) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 0.9) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + width + "px'; }", 250)); // Progressively grow the tooltip height RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.1) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.2) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.3) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.4) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.6) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.7) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.8) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 0.9) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + height + "px'; }", 250)); // When the animation is finished, set the tooltip HTML RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').innerHTML = RGraph.Registry.Get('chart.tooltip').__text__; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.boxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.borderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBorderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBorderRadius = '5px'; }", 250)); } else if (effect == 'contract') { tooltipObj.style.left = (x - width) + 'px'; tooltipObj.style.top = (y - (height * 2)) + 'px'; tooltipObj.style.cursor = 'pointer'; leftDelta = width / 10; topDelta = height / 10; tooltipObj.style.width = (width * 5) + 'px'; tooltipObj.style.height = (height * 5) + 'px'; tooltipObj.style.opacity = 0.2; // Progressively move the tooltip to where it should be (the x position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.left = (parseInt(RGraph.Registry.Get('chart.tooltip').style.left) + leftDelta) + 'px' }", 250)); // Progressively move the tooltip to where it should be (the Y position) RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.top = (parseInt(RGraph.Registry.Get('chart.tooltip').style.top) + (topDelta*2)) + 'px' }", 250)); // Progressively shrink the tooltip width RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 5.5) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 5.0) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 4.5) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 4.0) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 3.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 3.0) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 2.5) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 2.0) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + (width * 1.5) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.width = '" + width + "px'; }", 250)); // Progressively shrink the tooltip height RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 5.5) + "px'; }", 25)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 5.0) + "px'; }", 50)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 4.5) + "px'; }", 75)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 4.0) + "px'; }", 100)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 3.5) + "px'; }", 125)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 3.0) + "px'; }", 150)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 2.5) + "px'; }", 175)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 2.0) + "px'; }", 200)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + (height * 1.5) + "px'; }", 225)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.height = '" + height + "px'; }", 250)); // When the animation is finished, set the tooltip HTML RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').innerHTML = RGraph.Registry.Get('chart.tooltip').__text__; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.boxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBoxShadow = 'rgba(96,96,96,0.5) 3px 3px 3px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.borderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.MozBorderRadius = '5px'; }", 250)); RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.WebkitBorderRadius = '5px'; }", 250)); /** * This resets the pointer */ RGraph.Registry.Get('chart.tooltip.timers').push(setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.cursor = 'default'; }", 275)); } else if (effect != 'fade' && effect != 'expand' && effect != 'none' && effect != 'snap' && effect != 'contract') { alert('[COMMON] Unknown tooltip effect: ' + effect); } if (effect != 'none') { setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.1; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 25); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.2; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 50); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.3; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 75); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.4; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 100); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.5; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 125); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.6; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.2)'; }", 150); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.7; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.4)'; }", 175); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.8; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.6)'; }", 200); setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 0.9; RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgba(96,96,96,0.8)'; }", 225); } setTimeout("if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.opacity = 1;RGraph.Registry.Get('chart.tooltip').style.border = '1px solid rgb(96,96,96)';}", effect == 'none' ? 50 : 250); /** * If the tooltip it self is clicked, cancel it */ tooltipObj.onmousedown = function (e) { e = RGraph.FixEventObject(e) e.stopPropagation(); } tooltipObj.onclick = function (e) { if (e.button == 0) { e = RGraph.FixEventObject(e); e.stopPropagation(); } } /** * Install the function for hiding the tooltip. */ document.body.onmousedown = function (event) { var tooltip = RGraph.Registry.Get('chart.tooltip'); if (tooltip) { RGraph.HideTooltip(); // Redraw if highlighting is enabled if (tooltip.__canvas__.__object__.Get('chart.tooltips.highlight')) { RGraph.Redraw(); } } } /** * If the window is resized, hide the tooltip */ window.onresize = function () { var tooltip = RGraph.Registry.Get('chart.tooltip'); if (tooltip) { tooltip.parentNode.removeChild(tooltip); tooltip.style.display = 'none'; tooltip.style.visibility = 'hidden'; RGraph.Registry.Set('chart.tooltip', null); // Redraw the graph if necessary if (canvas.__object__.Get('chart.tooltips.highlight')) { RGraph.Clear(canvas); canvas.__object__.Draw(); } } } /** * Keep a reference to the tooltip */ RGraph.Registry.Set('chart.tooltip', tooltipObj); /** * Fire the tooltip event */ RGraph.FireCustomEvent(canvas.__object__, 'ontooltip'); } /** * */ RGraph.getTooltipText = function (text) { var result = /^id:(.*)/.exec(text); if (result) { text = document.getElementById(result[1]).innerHTML; } return text; } /** * */ RGraph.getTooltipWidth = function (text, obj) { var div = document.createElement('DIV'); div.className = obj.Get('chart.tooltips.css.class'); div.style.paddingLeft = RGraph.tooltips.padding; div.style.paddingRight = RGraph.tooltips.padding; div.style.fontFamily = RGraph.tooltips.font_face; div.style.fontSize = RGraph.tooltips.font_size; div.style.visibility = 'hidden'; div.style.position = 'absolute'; div.style.top = '300px'; div.style.left = 0; div.style.display = 'inline'; div.innerHTML = RGraph.getTooltipText(text); document.body.appendChild(div); return div.offsetWidth; } /** * Hides the currently shown tooltip */ RGraph.HideTooltip = function () { var tooltip = RGraph.Registry.Get('chart.tooltip'); if (tooltip) { tooltip.parentNode.removeChild(tooltip); tooltip.style.display = 'none'; tooltip.style.visibility = 'hidden'; RGraph.Registry.Set('chart.tooltip', null); } }
JavaScript
// object encapsulating an hour-minute pair module.exports = (function() { "use strict"; // constructor function HourMinute(hour, minute) { function parseIntWithLeading0(thing) { if (typeof(thing) === "number") return thing; var match = thing.toString().match(/^0*(\d+)$/); return parseInt(match[1]); } this.hour = parseIntWithLeading0(hour); this.minute = parseIntWithLeading0(minute.toString()); } HourMinute.prototype.toString = function () { function formatNN(n) { if (n>=10) return n.toString(); return "0" + n; } return formatNN(this.hour) + formatNN(this.minute); } HourMinute.prototype.equals = function (that) { if (this === that) return true; if (!(that instanceof HourMinute)) return false; return this.hour === that.hour && this.minute === that.minute; } HourMinute.prototype.smallerNotEqual = function (that) { if (!(that instanceof HourMinute)) throw "bug!"; if (this.hour < that.hour) return true; if (this.hour > that.hour) return false; return this.minute < that.minute; } HourMinute.regexp = /(\d{1,2}):?(\d\d)/; HourMinute.parse = function(text) { var match = text.match(HourMinute.regexp); if (!match) throw "cannot parse hours: " + text; return new HourMinute(match[1], match[2]); } HourMinute.REsrc = /\d{1,2}:?\d\d/.source; return HourMinute; }());
JavaScript
// A list of TimeInterval objects module.exports = (function() { "use strict"; var TimeInterval = require("../lib/timeInterval"); // constructor function TimeIntervalList() { this.list = []; } TimeIntervalList.delimRE = /\s*[,;\uff1b]\s*/; TimeIntervalList.parse = function(text) { var hoursRanges = text.split(TimeIntervalList.delimRE); var list = new TimeIntervalList(); for (var i in hoursRanges) { list.add(TimeInterval.parse(hoursRanges[i])); } return list; }; TimeIntervalList.REsrc = "(?:" + TimeInterval.REsrc + ")(?:(?:" + TimeIntervalList.delimRE.source + ")(?:" + TimeInterval.REsrc + "))*"; TimeIntervalList.prototype.add = function(timeInterval) { var n = this.list.length; var i = 0; while (i < n) { var curr = this.list[i]; if (curr.overlaps(timeInterval)) { timeInterval = timeInterval.merge(curr); this.list.splice(i, 1); --n; } else { ++i; } } for (i=0; i<n; ++i) { var curr2 = this.list[i]; if (timeInterval.start.smallerNotEqual(curr2.start)) { this.list.splice(i, 0, timeInterval); return; } } this.list.push(timeInterval); } TimeIntervalList.prototype.addList = function(that) { for (var i in that.list) { this.add(that.list[i]); } } TimeIntervalList.prototype.length = function() { return this.list.length; } TimeIntervalList.prototype.equals = function(that) { if (this === that) return true; if (!(that instanceof TimeIntervalList)) return false; var n = that.list.length; if (this.list.length !== n) return false; for (var i=0; i<n; ++i) { if (!this.list[i].equals(that.list[i])) return false; } return true; } TimeIntervalList.prototype.toString = function() { return this.list.join(","); } return TimeIntervalList; }());
JavaScript
// Parser for day-of-week (DOW) specifications module.exports = (function() { "use strict"; function DOWParser(dowRE, dowREc1, rangeDelimRE, listDelimRE, convert2num) { function getREsrc(re) { if (re instanceof RegExp) return re.source; return re.toString(); } this.dowREsrc = getREsrc(dowRE); this.dowREc1src = getREsrc(dowREc1); this.rangeDelimREsrc = getREsrc(rangeDelimRE); this.listDelimREsrc = getREsrc(listDelimRE); this.convert2num = convert2num instanceof Function? convert2num : function(text) { return convert2num[text]; }; this.rangeREsrc = "(?:" + this.dowREsrc + ")(?:(?:" + this.rangeDelimREsrc + ")(?:" + this.dowREsrc + "))?"; this.rangeREc2src = "(?:" + this.dowREc1src + ")(?:(?:" + this.rangeDelimREsrc + ")(?:" + this.dowREc1src + "))?"; this.listREsrc = "(?:" + this.rangeREsrc + ")(?:(?:" + this.listDelimREsrc + ")(?:" + this.rangeREsrc + "|.*?))*"; this.listDelimRE = new RegExp(this.listDelimREsrc, "i"); this.rangeREc2 = new RegExp(this.rangeREc2src, "i"); } var rangeDelimREsrc = /\s*(?:to|[-\u2013])\s*/.source; var dowParserEN = new DOWParser(/Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Weekday|Weekend|(?:(?:Sun|Mon|Tue|Wed|Thur?|Fri|Sat)\.?)/, /(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Weekday|Weekend|Sun|Mon|Tue|Wed|Thur?|Fri|Sat)\.?/, rangeDelimREsrc, /\s*(?:\band\b|&)\s*/, { Sunday: 0, Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6, Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Thur: 4, Fri: 5, Sat: 6, Weekday: [1, 5], Weekend: [6, 0], }); var dowParserZH = new DOWParser(/(?:星期)?[日一二三四五六]/, /(?:星期)?([日一二三四五六])/, /\s*[-至–]\s*/, /\s*[、及&]\s*/, { 日: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, }); //overrides: dowParserZH.listREsrc = "星期" + dowParserZH.listREsrc; dowParserZH.listRE = new RegExp(dowParserZH.listREsrc); function chooseInstance(text) { if (text.match(dowParserZH.listRE)) return dowParserZH; return dowParserEN; } return { listREsrc: "(?:" + dowParserEN.listREsrc + ")|(?:" + dowParserZH.listREsrc + ")", chooseInstance: chooseInstance, }; }());
JavaScript
/******************************************************************************* * * A blank reference implementation exists below. Replace it with your * implementation. * * [n=80] ******************************************************************************/ module.exports = (function() { "use strict"; var dowParser = require("../lib/dowParser"); var TimeIntervalList = require("../lib/timeIntervalList"); var phraseRE2csrc = "(" + dowParser.listREsrc +")|(" + TimeIntervalList.REsrc + ")"; var hours = {}; hours.parse = function(text) { function parsePhrases(text, results) { var phraseRE2c = new RegExp(phraseRE2csrc, "ig"); var currDOWrangesText; var match; while ((match = phraseRE2c.exec(text))) { var dowRangesText = match[1]; var hoursRangesText = match[2]; if (dowRangesText !== undefined) { currDOWrangesText = dowRangesText; continue; } if (hoursRangesText !== undefined) { if (currDOWrangesText === undefined) continue; // skip hours spec without preceding DOW spec parseDOWhours(currDOWrangesText, hoursRangesText, results) } } } function parseDOWhours(dowRangesText, hoursRangesText, results) { var dows = parseDOWranges(dowRangesText); var hoursRanges = TimeIntervalList.parse(hoursRangesText); if (hoursRanges.length() < 1) return; for (var d=0; d<7; ++d) { if (!dows[d]) continue; if (!results[d]) results[d] = new TimeIntervalList(); results[d].addList(hoursRanges); } } function parseDOWranges(text) { // return an array, populated with Boolean 'true' entries at indices // indicating the days of weeks as specified in <text>. // e.g. if "Tue" is specified, returned_value[2] will be 'true'; var parser = dowParser.chooseInstance(text); var dow = []; var dowRangesText = text.split(parser.listDelimRE); for (var i in dowRangesText) { var rangeText = dowRangesText[i]; var match = rangeText.match(parser.rangeREc2); if (!match) { continue; // skip unrecognized parts (e.g. "PH") } var start = match[1]; // trim trailing '.', etc. start = start && parser.convert2num(start); var end = match[2]; end = end && parser.convert2num(end); if (end === undefined) end = start; if (typeof(start) !== "number") { // assume start == [a,b] end = start[1]; start = start[0]; } var d = start; for (;;) { dow[d] = true; if (d === end) break; d = (d+1) % 7; } } return dow; } function formatResults(results) { var dowDone = []; for (var d=0; d<7; ++d) if (results[d] === undefined) dowDone[d] = true; var strs = []; for (;;) { // find a result item to format var i = 0; while (i < 7 && dowDone[i]) ++i if (i >= 7) break; // all done var curr = results[i]; // find other items with identical time intervals var currentDOWs = []; currentDOWs[i] = true; dowDone[i] = true; for (var j=i+1; j<7; ++j) { if (!dowDone[j] && curr.equals(results[j])) { currentDOWs[j] = true; dowDone[j] = true; } } strs.push(formatDOWs(currentDOWs) + ":" + curr); } return "S" + strs.join(";"); } function formatDOWs(dows) { var strs = []; for (;;) { // find first empty entry var empty1 = 0; while (empty1 < 7 && dows[empty1]) ++empty1; // determine first non-empty item after the 'empty1' var nonEmpty1; if (empty1 >= 7) { // no empty entry in dows[] nonEmpty1 = 0; } else { nonEmpty1 = (empty1+1) % 7; while (nonEmpty1 !== empty1) { if (dows[nonEmpty1]) break; nonEmpty1 = (nonEmpty1+1) % 7; } if (nonEmpty1 === empty1) { // no more non-empty dows entry return strs.join(","); } } var d = nonEmpty1; for (;;) { if (!dows[d]) { break; } dows[d] = false; d = (d + 1) % 7; } d = (d+6)%7; if (nonEmpty1 === d) { strs.push(nonEmpty1); } else { strs.push(nonEmpty1 + "-" + d); } } } var results = []; parsePhrases(text, results); return formatResults(results); } return hours }());
JavaScript
// object encapsulating a time interval, specified by two HourMinute objects module.exports = (function() { "use strict"; var HourMinute = require("../lib/hourMinute"); // constructor function TimeInterval(start, end) { this.start = start; this.end = end; } TimeInterval.prototype.toString = function() { return this.start + "-" + this.end; } TimeInterval.prototype.equals = function(that) { if (this === that) return true; if (!(that instanceof TimeInterval)) return false; return this.start.equals(that.start) && this.end.equals(that.end); } TimeInterval.prototype.overlaps = function(that) { if (!(that instanceof TimeInterval)) throw "bug!"; if (this.end.smallerNotEqual(that.start)) return false; if (that.end.smallerNotEqual(this.start)) return false; return true; } TimeInterval.prototype.merge = function(that) { if (!(that instanceof TimeInterval)) throw "bug!"; var newStart = this.start.smallerNotEqual(that.start)? this.start : that.start; var newEnd = this.end.smallerNotEqual(that.end)? that.end : this.end; return new TimeInterval(newStart, newEnd); } TimeInterval.delimRE = /\s*(?:to|[-\u2013])\s*/; TimeInterval.parse = function(text) { var hoursText = text.split(TimeInterval.delimRE); var from = HourMinute.parse(hoursText[0]); var to = HourMinute.parse(hoursText[1]); if (to.hour < from.hour) to.hour += 24; return new TimeInterval(from, to); } TimeInterval.REsrc = "(?:" + HourMinute.REsrc + ")(?:" + TimeInterval.delimRE.source + ")(?:" + HourMinute.REsrc + ")"; return TimeInterval; }());
JavaScript
/******************************************************************************* * * Copyright:: Copyright 2013 Kites Ltd * Original Author:: Edwin Shao (eshao@kitesplex.com) * * [n=80] ******************************************************************************/ (function() { "use strict"; var assert = require('assert') , _ = require('underscore') var hours = require('../lib') /** * Generates a single mocha test case. * * @params {string} expected result after calling parse function * @params {string} freetext to pass to hours.parse */ var check = function(expected, freetext) { test(freetext, function() { var result = hours.parse(freetext) assert.equal(result, expected) }) } suite('Parses simple sentences correctly') var cases = { 'Sunday: 7:00 to 11:00': 'S0:0700-1100' , 'Sunday: 15:00 to 1:00': 'S0:1500-2500' , 'Sun: 07:00-00:00': 'S0:0700-2400' } _.each(cases, check) suite('Parses THROUGH sentences correctly') cases = { 'Mon-Sun: 12:30-01:00': 'S0-6:1230-2500' , 'Mon to Sun: 06:30 - 22:30': 'S0-6:0630-2230' , 'Fri to Tue: 06:30 - 22:30': 'S5-2:0630-2230' , 'Mon - Wed: 07:00-01:00': 'S1-3:0700-2500' } _.each(cases, check) suite('Parses AND sentences correctly') cases = { 'Mon-Thu & Sun: 09:30-22:30': 'S0-4:0930-2230' , 'Fri-Sat & PH: 09:30-23:00': 'S5-6:0930-2300' } _.each(cases, check) suite('Parses sentences with multiple times correctly') cases = { 'Mon-Fri: 11:45-16:30; 17:45-23:30': 'S1-5:1145-1630,1745-2330' , 'Monday to Sunday: 12:00-15:00, 18:00-22:00': 'S0-6:1200-1500,1800-2200' } _.each(cases, check) suite('Deals with strange Unicode characters correctly') cases = { 'Mon:18:00-00:00': 'S1:1800-2400' // : , 'Sat & Sun: 12:00-14:30;18:00-23:00': 'S6-0:1200-1430,1800-2300' // ; , 'Mon to Fri: 6:30 – 20:30': 'S1-5:0630-2030' // - } _.each(cases, check) suite('Tokenizes multiline hours correctly') cases = { 'Mon.-Sat.: 11:30-22:30; Sun.: 10:30-22:30': 'S0:1030-2230;1-6:1130-2230' , 'Sun.-Thur. 11:00-23:00, Fri.-Sat. 11:00-00:00': 'S0-4:1100-2300;5-6:1100-2400' } _.each(cases, check) suite('Parses complex sentences correctly') cases = { 'Mon-Sun\nBreakfast 07:00-11:00\nLunch 11:30-14:30\nTea 14:00-18:00\nSun-Thu Dinner 18:30-22:30\nFri & Sat Dinner 18:30-23:30': 'S0-4:0700-1100,1130-1800,1830-2230;5-6:0700-1100,1130-1800,1830-2330' , 'Mon-Sun: 06:00-23:00\n(Tea: 06:00-16:00)': 'S0-6:0600-2300' , 'Mon-Sat: 11:00-21:00 until 300 quotas soldout': 'S1-6:1100-2100' , 'Monday to Sunday & Public Holiday:\n12:00-15:00, 18:00-00:00': 'S0-6:1200-1500,1800-2400' , 'Restaurant Mon-Sun: 06:30-23:00\nBar Mon-Sun: 15:00-00:00\nBe on Canton Mon-Sun: 12:00-00:00': 'S0-6:0630-2400' } _.each(cases, check) suite('Custom tests') cases = { 'Mon-Sat: 2300-2500,0600-0800': 'S1-6:0600-0800,2300-2500' , 'Mon-Sat: 0000-2300,2301-2800': 'S1-6:0000-2300,2301-2800' , 'Fri-Sat: 0000-2300, Mon: 0000-2300': 'S1,5-6:0000-2300' , 'Fri-Sat: 0000-2300, Mon: 0000-2301': 'S1:0000-2301;5-6:0000-2300' } _.each(cases, check) suite('Chinese') cases = { 'Mon.-Sun.: 12:00-22:30': 'S0-6:1200-2230' , '星期一至日: 12:00-22:30': 'S0-6:1200-2230' , 'Mon.-Sat.: 12:00-23:00': 'S1-6:1200-2300' , '星期一至六: 12:00-23:00 ': 'S1-6:1200-2300' , 'Mon.-Sun.: 12:00-14:30, 19:00-22:30': 'S0-6:1200-1430,1900-2230' , '星期一至日: 12:00-14:30, 19:00-22:30': 'S0-6:1200-1430,1900-2230' , 'Mon to Sat: 12:00 – 14:30; 18:30 – 23:00\nSun: 12:00 – 15:00; 18:30 – 23:00': 'S0:1200-1500,1830-2300;1-6:1200-1430,1830-2300' , '星期一至六:12:00 – 14:30; 18:30 – 23:00\n星期日:12:00 – 15:00; 18:30 – 23:00': 'S0:1200-1500,1830-2300;1-6:1200-1430,1830-2300' , 'Mon.-Fri.: 12:00-14:30; 18:00-22:30\nSat.-Sun.&Public Holidays: 11:30-15:00; 18:00-22:30': 'S6-0:1130-1500,1800-2230;1-5:1200-1430,1800-2230' , '星期一至五:12:00-14:30; 18:00-22:30\n星期六、日及公眾假期:11:30-15:00; 18:00-22:30': 'S6-0:1130-1500,1800-2230;1-5:1200-1430,1800-2230' , 'Mon.-Sat.: 11:30-14:30, 18:00-22:30; Sun.&Public Holidays: 11:00-14:30, 18:00-22:30': 'S0:1100-1430,1800-2230;1-6:1130-1430,1800-2230' , '星期一至六: 11:30-14:30, 18:00-22:30; 星期日及公眾假期: 11:00-14:30, 18:00-22:30': 'S0:1100-1430,1800-2230;1-6:1130-1430,1800-2230' , 'Breakfast (Weekday): 07:00-10:00\nBreakfast (Sunday and Public Holiday): 07:00-10:30\nLunch: 12:00-14:30\nDinner: 18:00-22:00\nVerandah Café : 07:00-23:00 (cakes and sandwiches only available from 14:00-18:00 daily)': 'S0:0700-2300;1-5:0700-1000' , '早餐(星期一至六): 07:00-10:00\n早餐(星期日及公眾假期): 07:00-10:30\n午餐: 12:00-14:30\n晚餐: 18:00-22:00\n露台咖啡廳: 07:00-23:00 (糕點及三文治於14:00-18:00供應)': 'S0:0700-2300;1-6:0700-1000' , '星期一至星期日: 07:00-21:00': 'S0-6:0700-2100' } _.each(cases, check) }());
JavaScript
$(function() { $('#funvote').find('form').submit(function(e) { e.preventDefault(); $.post(this.action + '&format=json' , $(this).serialize(), function(res) { if (res.success) { $("#funvote").hide(); $("#voteaccept").show(); } }); }); });
JavaScript
$(function() { var opentags = { b : 0, i : 0, u : 0, color : 0, list : 0, quote : 0, html : 0 }; var bbtags = []; function cstat() { var c = stacksize(bbtags); if ( (c < 1) || (c == null) ) {c = 0;} if ( ! bbtags[0] ) { c = 0; } btnClose.val("Close last, Open "+c); } function stacksize(thearray) { for (i = 0; i < thearray.length; i++ ) { if ( (thearray[i] == "") || (thearray[i] == null) || (thearray == 'undefined') ) {return i;} } return thearray.length; } function pushstack(thearray, newval) { arraysize = stacksize(thearray); thearray[arraysize] = newval; } function popstackd(thearray) { arraysize = stacksize(thearray); theval = thearray[arraysize - 1]; return theval; } function popstack(thearray) { arraysize = stacksize(thearray); theval = thearray[arraysize - 1]; delete thearray[arraysize - 1]; return theval; } function closeall() { if (bbtags[0]) { while (bbtags[0]) { tagRemove = popstack(bbtags) if ( (tagRemove != 'color') ) { doInsert("[/"+tagRemove+"]", "", false); document[hb.bbcode.form][tagRemove].value = tagRemove; opentags[tagRemove] = 0; } else { doInsert("[/"+tagRemove+"]", "", false); } cstat(); return; } } btnClose.val("Close last, Open 0"); bbtags = new Array(); document[hb.bbcode.form][hb.bbcode.text].focus(); } function add_code(NewCode) { document[hb.bbcode.form][hb.bbcode.text].value += NewCode; document[hb.bbcode.form][hb.bbcode.text].focus(); } function alterfont(theval, thetag) { if (theval == 0) return; if(doInsert("[" + thetag + "=" + theval + "]", "[/" + thetag + "]", true)) pushstack(bbtags, thetag); cstat(); } var url_inited = false; var dialog_type = ''; function url_form(t) { dialog_type = t; if (!url_inited) { url_inited = true; var dialog = $('<div></div>', { title : 'URL', 'class' : 'minor-list-vertical', id : 'url-form' }); $('#bbcode-toolbar').append(dialog); dialog.html('<ul><div id="validateTips"></div><li><label for="tag-url">' + lang.js_prompt_enter_url + '</label><input type="url" id="tag-url" class="text ui-widget-content ui-corner-all" /></li><li><label for="tag-url-title">' + lang.js_prompt_enter_title + '</label><input type="text" id="tag-url-title" class="text ui-widget-content ui-corner-all" /></li></ul>'); var urlfield = $('#tag-url'); var titlefield = $('#tag-url-title'); var allFields = $( [] ).add( urlfield ).add( titlefield ); function updateTips( t ) { var tips = $('#validateTips'); tips.text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 500 ); } function isUrl(s) { var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ return regexp.test(s); } function checkLength( o, n ) { if (!isUrl(o.val())) { o.addClass( "ui-state-error" ); updateTips( n + "无效。" ); return false; } else { return true; } } var onok = function() { allFields.removeClass( "ui-state-error" ); var valid = true; valid = valid && checkLength(urlfield, "URL"); if (valid) { var url = urlfield.val(); var title = $('#tag-url-title').val(); if (title.length === 0) { title = url; } if (dialog_type === 'url') { doInsert("[url="+url+"]"+title+"[/url]", "", false); } else if (dialog_type === 'image') { doInsert("[img]"+url+"[/img]", "", false); } dialog.dialog( "close" ); } }; allFields.keypress(function(e) { if (e.keyCode === 13) { onok(); } }); dialog.dialog({ modal: true, buttons: { OK: onok, Cancel: function() { $( this ).dialog( "close" ); } }, close: function() { allFields.val( "" ).removeClass( "ui-state-error" ); $('#validateTips').text(''); } }); } $('#tag-url-title').parent().toggle(dialog_type === 'url'); $('#tag-url').val('http://').select(); $('#url-form').dialog('open'); } function tag_url() { url_form('url'); } function tag_list(PromptEnterItem, PromptError) { var FoundErrors = ''; var enterTITLE = prompt(PromptEnterItem, ""); if (!enterTITLE) {FoundErrors += " " + PromptEnterItem;} if (FoundErrors) {alert(PromptError+FoundErrors);return;} doInsert("[*]"+enterTITLE+"", "", false); } function tag_image() { url_form('image'); } function tag_email(PromptEmail, PromptError) { var emailAddress = prompt(PromptEmail, ""); if (!emailAddress) { alert(PromptError+PromptEmail); return; } doInsert("[email]"+emailAddress+"[/email]", "", false); } var inited = false; $('#showmoresmilies').click(function (e) { e.preventDefault(); if (inited) { $('#moresmilies').dialog('open'); } else { inited = true; var uri = "moresmilies.php?form=" + hb.bbcode.form + "&text=" + hb.bbcode.text; $.get(uri, function(result) { $('#moresmilies').html(result).dialog({ width: '50%', position: 'right' }); }, 'html'); } }); function simpletag(thetag) { var tagOpen = opentags[thetag]; if (tagOpen == 0) { if(doInsert("[" + thetag + "]", "[/" + thetag + "]", true)) { opentags[thetag] = 1; document[hb.bbcode.form][thetag].value = '*'; pushstack(bbtags, thetag); cstat(); } } else { lastindex = 0; for (i = 0; i < bbtags.length; i++ ) { if ( bbtags[i] == thetag ) { lastindex = i; } } while (bbtags[lastindex]) { tagRemove = popstack(bbtags); doInsert("[/" + tagRemove + "]", "", false) if ((tagRemove != 'COLOR') ){ document[hb.bbcode.form][tagRemove].value = tagRemove.toUpperCase(); opentags[tagRemove] = 0; } } cstat(); } } var lang = hb.constant.lang; var buttons = [ $('<input />', { 'class' : 'codebuttons', style : "font-weight: bold;", type : 'button', name : 'b', value : 'B' }).click(function() { simpletag('b'); }), $('<input />', { 'class' : 'codebuttons', style : "font-style: italic;", type : 'button', name : 'i', value : 'I' }).click(function() { simpletag('i'); }), $('<input />', { 'class' : 'codebuttons', style : "text-decoration: underline;", type : 'button', name : 'u', value : 'U' }).click(function() { simpletag('u'); }), $('<input />', { 'class' : 'codebuttons', type : 'button', name : 'url', value : 'URL' }).click(tag_url), $('<input />', { 'class' : 'codebuttons', type : 'button', name : 'IMG', value : 'IMG' }).click(tag_image), $('<input />', { 'class' : 'codebuttons', type : 'button', value : 'List' }).click(function() { tag_list(lang.js_prompt_enter_item, lang.js_prompt_error); }), $('<input />', { 'class' : 'codebuttons', type : 'button', name : 'quote', value : 'QUOTE' }).click(function() { simpletag('quote'); })]; var btnClose = $('<input />', { 'class' : 'codebuttons', type : 'button', value : '关闭标签' }).click(closeall); buttons.push(btnClose); var selections = function(name, header, opts) { var sel = $('<select></select>', { 'class' : "med codebuttons no-validate", name : name }); sel.append('<option value="0">' + header + '</option>'); return sel.append($.map(opts, function(item, idx) { return '<option value="' + item.val + '"' + item.attrs + '>' + item.title + '</option>'; }).join()); }; var colorOpts = [{"title":"Black","val":"Black","attrs":" style=\"background-color: black;\""},{"title":"Sienna","val":"Sienna","attrs":" style=\"background-color: sienna;\""},{"title":"Dark Olive Green","val":"DarkOliveGreen","attrs":" style=\"background-color: darkolivegreen;\""},{"title":"Dark Green","val":"DarkGreen","attrs":" style=\"background-color: darkgreen;\""},{"title":"Dark Slate Blue","val":"DarkSlateBlue","attrs":" style=\"background-color: darkslateblue;\""},{"title":"Navy","val":"Navy","attrs":" style=\"background-color: navy;\""},{"title":"Indigo","val":"Indigo","attrs":" style=\"background-color: indigo;\""},{"title":"Dark Slate Gray","val":"DarkSlateGray","attrs":" style=\"background-color: darkslategray;\""},{"title":"Dark Red","val":"DarkRed","attrs":" style=\"background-color: darkred;\""},{"title":"Dark Orange","val":"DarkOrange","attrs":" style=\"background-color: darkorange;\""},{"title":"Olive","val":"Olive","attrs":" style=\"background-color: olive;\""},{"title":"Green","val":"Green","attrs":" style=\"background-color: green;\""},{"title":"Teal","val":"Teal","attrs":" style=\"background-color: teal;\""},{"title":"Blue","val":"Blue","attrs":" style=\"background-color: blue;\""},{"title":"Slate Gray","val":"SlateGray","attrs":" style=\"background-color: slategray;\""},{"title":"Dim Gray","val":"DimGray","attrs":" style=\"background-color: dimgray;\""},{"title":"Red","val":"Red","attrs":" style=\"background-color: red;\""},{"title":"Sandy Brown","val":"SandyBrown","attrs":" style=\"background-color: sandybrown;\""},{"title":"Yellow Green","val":"YellowGreen","attrs":" style=\"background-color: yellowgreen;\""},{"title":"Sea Green","val":"SeaGreen","attrs":" style=\"background-color: seagreen;\""},{"title":"Medium Turquoise","val":"MediumTurquoise","attrs":" style=\"background-color: mediumturquoise;\""},{"title":"Royal Blue","val":"RoyalBlue","attrs":" style=\"background-color: royalblue;\""},{"title":"Purple","val":"Purple","attrs":" style=\"background-color: purple;\""},{"title":"Gray","val":"Gray","attrs":" style=\"background-color: gray;\""},{"title":"Magenta","val":"Magenta","attrs":" style=\"background-color: magenta;\""},{"title":"Orange","val":"Orange","attrs":" style=\"background-color: orange;\""},{"title":"Yellow","val":"Yellow","attrs":" style=\"background-color: yellow;\""},{"title":"Lime","val":"Lime","attrs":" style=\"background-color: lime;\""},{"title":"Cyan","val":"Cyan","attrs":" style=\"background-color: cyan;\""},{"title":"Deep Sky Blue","val":"DeepSkyBlue","attrs":" style=\"background-color: deepskyblue;\""},{"title":"Dark Orchid","val":"DarkOrchid","attrs":" style=\"background-color: darkorchid;\""},{"title":"Silver","val":"Silver","attrs":" style=\"background-color: silver;\""},{"title":"Pink","val":"Pink","attrs":" style=\"background-color: pink;\""},{"title":"Wheat","val":"Wheat","attrs":" style=\"background-color: wheat;\""},{"title":"Lemon Chiffon","val":"LemonChiffon","attrs":" style=\"background-color: lemonchiffon;\""},{"title":"Pale Green","val":"PaleGreen","attrs":" style=\"background-color: palegreen;\""},{"title":"Pale Turquoise","val":"PaleTurquoise","attrs":" style=\"background-color: paleturquoise;\""},{"title":"Light Blue","val":"LightBlue","attrs":" style=\"background-color: lightblue;\""},{"title":"Plum","val":"Plum","attrs":" style=\"background-color: plum;\""},{"title":"White","val":"White","attrs":" style=\"background-color: white;\""}]; var fontOpts = [{"title":"Arial","val":"Arial"},{"title":"Arial Black","val":"Arial Black"},{"title":"Arial Narrow","val":"Arial Narrow"},{"title":"Book Antiqua","val":"Book Antiqua"},{"title":"Century Gothic","val":"Century Gothic"},{"title":"Comic Sans MS","val":"Comic Sans MS"},{"title":"Courier New","val":"Courier New"},{"title":"Fixedsys","val":"Fixedsys"},{"title":"Garamond","val":"Garamond"},{"title":"Georgia","val":"Georgia"},{"title":"Impact","val":"Impact"},{"title":"Lucida Console","val":"Lucida Console"},{"title":"Lucida Sans Unicode","val":"Lucida Sans Unicode"},{"title":"Microsoft Sans Serif","val":"Microsoft Sans Serif"},{"title":"Palatino Linotype","val":"Palatino Linotype"},{"title":"System","val":"System"},{"title":"Tahoma","val":"Tahoma"},{"title":"Times New Roman","val":"Times New Roman"},{"title":"Trebuchet MS","val":"Trebuchet MS"},{"title":"Verdana","val":"Verdana"}]; var sizeOpts = [{"title":"1","val":"1"},{"title":"2","val":"2"},{"title":"3","val":"3"},{"title":"4","val":"4"},{"title":"5","val":"5"},{"title":"6","val":"6"},{"title":"7","val":"7"}]; buttons.push(selections('color', lang.select_color, colorOpts).change(function() { alterfont(this.options[this.selectedIndex].value, 'color'); this.selectedIndex = 0; })); buttons.push(selections('font', lang.select_font, fontOpts).change(function() { alterfont(this.options[this.selectedIndex].value, 'font'); this.selectedIndex = 0; })); buttons.push(selections('size', lang.select_size, sizeOpts).change(function() { alterfont(this.options[this.selectedIndex].value, 'size'); this.selectedIndex = 0; })); var toolbar = $('#bbcode-toolbar'); $.each(buttons, function(idx,itm) { toolbar.append(itm.wrap('<li></li>')); }) }); // preview.js $(function() { var $tar = $('#commit-btn'); var $previewouter = $('#previewouter'); var $editorouter = $('#editorouter'); var previewing = false; var $preview = $('<input />', { type : 'button', 'class' : 'btn2', id : 'previewbutton', value : hb.constant.lang.submit_preview }).click(function() { if (!previewing) { $.post('preview.php', {body : $('#body').val()}, function(res) { $preview.attr('value', hb.constant.lang.submit_edit); $previewouter.html(res).slideDown(); $editorouter.slideUp(); previewing = true; }, 'html'); } else { $preview.attr('value', hb.constant.lang.submit_preview); $previewouter.html('').slideUp(); $editorouter.slideDown(); previewing = false; } }).appendTo($tar); $('#commit-btn input').button().parent().buttonset(); }); var allowedtypes = (function() { var lock = false; var dialog; return function (e, obja) { var a = $(obja); if (!dialog) { dialog = $('<div></div>', { title : a.parent().text(), text : a.attr('title') }).hide(); a.attr('title', ''); $('#bbcode-toolbar').after(dialog); dialog.dialog({ position : ['right', 'top'], autoOpen: false, close : function() {lock = false;} }); } if (e.type === 'mouseover') { dialog.dialog('open'); } else if (e.type === 'mouseout') { if (!lock) { dialog.dialog('close'); } } else if (e.type === 'click') { e.preventDefault(); lock = true; dialog.dialog('open'); } }; })(); function tag_extimage(content) { doInsert(content, "", false); }
JavaScript
$(function() { $('#test-form').submit(function (e) { e.preventDefault(); $.post('preview.php', {body : $('#test').val()} ,function(res) { $('#test-result').html('<fieldset>' + res + '</fieldset>'); }, 'html'); }); });
JavaScript
/** * TableSorter for MediaWiki * * Written 2011 Leo Koppelkamm * Based on tablesorter.com plugin, written (c) 2007 Christian Bach. * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @depends on mw.config (wgDigitTransformTable, wgMonthNames, wgMonthNamesShort, * wgDefaultDateFormat, wgContentLanguage) */ /** * * @description Create a sortable table with multi-column sorting capabilitys * * @example $( 'table' ).tablesorter(); * @desc Create a simple tablesorter interface. * * @option String cssHeader ( optional ) A string of the class name to be appended * to sortable tr elements in the thead of the table. Default value: * "header" * * @option String cssAsc ( optional ) A string of the class name to be appended to * sortable tr elements in the thead on a ascending sort. Default value: * "headerSortUp" * * @option String cssDesc ( optional ) A string of the class name to be appended * to sortable tr elements in the thead on a descending sort. Default * value: "headerSortDown" * * @option String sortInitialOrder ( optional ) A string of the inital sorting * order can be asc or desc. Default value: "asc" * * @option String sortMultisortKey ( optional ) A string of the multi-column sort * key. Default value: "shiftKey" * * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever * to use String.localeCampare method or not. Set to false. * * @option Boolean cancelSelection ( optional ) Boolean flag indicating if * tablesorter should cancel selection of the table headers text. * Default value: true * * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter * should display debuging information usefull for development. * * @type jQuery * * @name tablesorter * * @cat Plugins/Tablesorter * * @author Christian Bach/christian.bach@polyester.se */ ( function( $ ) { //Initialize for using outside Wikipedia mw = { msg : function(key) { return { 'sort-descending' : "降序排序", 'sort-ascending' : "升序排序" }[key]; }, config : { get : function(key) { return { wgSeparatorTransformTable : ["", ""], wgDigitTransformTable : ["", ""], wgMonthNames : ["", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], wgMonthNamesShort : ["", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"] }[key]; } } }; $.escapeRE = function(str){return str.replace(/([\\{}()|.?*+\-^$\[\]])/g,"\\$1");} /* Local scope */ var ts, parsers = []; /* Parser utility functions */ function getParserById( name ) { var len = parsers.length; for ( var i = 0; i < len; i++ ) { if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) { return parsers[i]; } } return false; } function getElementText( node ) { var $node = $( node ), data = $node.attr( 'data-sort-value' ); if ( data !== undefined ) { return data; } else { return $node.text(); } } function getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ) { if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) { return $.trim( getElementText( rows[rowIndex].cells[cellIndex] ) ); } else { return ''; } } function detectParserForColumn( table, rows, cellIndex ) { var l = parsers.length, nodeValue, // Start with 1 because 0 is the fallback parser i = 1, rowIndex = 0, concurrent = 0, needed = ( rows.length > 4 ) ? 5 : rows.length; while( i < l ) { nodeValue = getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ); if ( nodeValue !== '') { if ( parsers[i].is( nodeValue, table ) ) { concurrent++; rowIndex++; if ( concurrent >= needed ) { // Confirmed the parser for multiple cells, let's return it return parsers[i]; } } else { // Check next parser, reset rows i++; rowIndex = 0; concurrent = 0; } } else { // Empty cell rowIndex++; if ( rowIndex > rows.length ) { rowIndex = 0; i++; } } } // 0 is always the generic parser (text) return parsers[0]; } function buildParserCache( table, $headers ) { var rows = table.tBodies[0].rows, sortType, parsers = []; if ( rows[0] ) { var cells = rows[0].cells, len = cells.length, i, parser; for ( i = 0; i < len; i++ ) { parser = false; sortType = $headers.eq( i ).data( 'sort-type' ); if ( sortType !== undefined ) { parser = getParserById( sortType ); } if ( parser === false ) { parser = detectParserForColumn( table, rows, i ); } parsers.push( parser ); } } return parsers; } /* Other utility functions */ function buildCache( table ) { var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0, totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0, parsers = table.config.parsers, cache = { row: [], normalized: [] }; for ( var i = 0; i < totalRows; ++i ) { // Add the table data to main data array var $row = $( table.tBodies[0].rows[i] ), cols = []; // if this is a child row, add it to the last row's children and // continue to the next row if ( $row.hasClass( table.config.cssChildRow ) ) { cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row ); // go to the next for loop continue; } cache.row.push( $row ); for ( var j = 0; j < totalCells; ++j ) { cols.push( parsers[j].format( getElementText( $row[0].cells[j] ), table, $row[0].cells[j] ) ); } cols.push( cache.normalized.length ); // add position for rowCache cache.normalized.push( cols ); cols = null; } return cache; } function appendToTable( table, cache ) { var row = cache.row, normalized = cache.normalized, totalRows = normalized.length, checkCell = ( normalized[0].length - 1 ), fragment = document.createDocumentFragment(); for ( var i = 0; i < totalRows; i++ ) { var pos = normalized[i][checkCell]; var l = row[pos].length; for ( var j = 0; j < l; j++ ) { fragment.appendChild( row[pos][j] ); } } table.tBodies[0].appendChild( fragment ); } /** * Find all header rows in a thead-less table and put them in a <thead> tag. * This only treats a row as a header row if it contains only <th>s (no <td>s) * and if it is preceded entirely by header rows. The algorithm stops when * it encounters the first non-header row. * * After this, it will look at all rows at the bottom for footer rows * And place these in a tfoot using similar rules. * @param $table jQuery object for a <table> */ function emulateTHeadAndFoot( $table ) { var $rows = $table.find( '> tbody > tr' ); if( !$table.get(0).tHead ) { var $thead = $( '<thead>' ); $rows.each( function() { if ( $(this).children( 'td' ).length > 0 ) { // This row contains a <td>, so it's not a header row // Stop here return false; } $thead.append( this ); } ); $table.prepend( $thead ); } if( !$table.get(0).tFoot ) { var $tfoot = $( '<tfoot>' ); var len = $rows.length; for ( var i = len-1; i >= 0; i-- ) { if( $( $rows[i] ).children( 'td' ).length > 0 ){ break; } $tfoot.prepend( $( $rows[i] )); } $table.append( $tfoot ); } } function buildHeaders( table, msg ) { var maxSeen = 0, longest, realCellIndex = 0, $tableHeaders = $( 'thead:eq(0) tr', table ); if ( $tableHeaders.length > 1 ) { $tableHeaders.each(function() { if ( this.cells.length > maxSeen ) { maxSeen = this.cells.length; longest = this; } }); $tableHeaders = $( longest ); } $tableHeaders = $tableHeaders.children( 'th' ).each( function( index ) { this.column = realCellIndex; var colspan = this.colspan; colspan = colspan ? parseInt( colspan, 10 ) : 1; realCellIndex += colspan; this.order = 0; this.count = 0; if ( $( this ).is( '.unsortable' ) ) { this.sortDisabled = true; } if ( !this.sortDisabled ) { var $th = $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] ); } // add cell to headerList table.config.headerList[index] = this; } ); return $tableHeaders; } function isValueInArray( v, a ) { var l = a.length; for ( var i = 0; i < l; i++ ) { if ( a[i][0] == v ) { return true; } } return false; } function setHeadersCss( table, $headers, list, css, msg ) { // Remove all header information $headers.removeClass( css[0] ).removeClass( css[1] ); var h = []; $headers.each( function( offset ) { if ( !this.sortDisabled ) { h[this.column] = $( this ); } } ); var l = list.length; for ( var i = 0; i < l; i++ ) { h[ list[i][0] ].addClass( css[ list[i][1] ] ).attr( 'title', msg[ list[i][1] ] ); } } function sortText( a, b ) { return ( (a < b) ? false : ((a > b) ? true : 0) ); } function sortTextDesc( a, b ) { return ( (b < a) ? false : ((b > a) ? true : 0) ); } function checkSorting( array1, array2, sortList ) { var col, fn, ret; for ( var i = 0, len = sortList.length; i < len; i++ ) { col = sortList[i][0]; fn = ( sortList[i][1] ) ? sortTextDesc : sortText; ret = fn.call( this, array1[col], array2[col] ); if ( ret !== 0 ) { return ret; } } return ret; } // Merge sort algorithm // Based on http://en.literateprograms.org/Merge_sort_(JavaScript) function mergeSortHelper( array, begin, beginRight, end, sortList ) { for ( ; begin < beginRight; ++begin ) { if ( checkSorting( array[begin], array[beginRight], sortList ) ) { var v = array[begin]; array[begin] = array[beginRight]; var begin2 = beginRight; while ( begin2 + 1 < end && checkSorting( v, array[begin2 + 1], sortList ) ) { var tmp = array[begin2]; array[begin2] = array[begin2 + 1]; array[begin2 + 1] = tmp; ++begin2; } array[begin2] = v; } } } function mergeSort(array, begin, end, sortList) { var size = end - begin; if ( size < 2 ) { return; } var beginRight = begin + Math.floor(size / 2); mergeSort( array, begin, beginRight, sortList ); mergeSort( array, beginRight, end, sortList ); mergeSortHelper( array, begin, beginRight, end, sortList ); } function multisort( table, sortList, cache ) { var i = sortList.length; mergeSort( cache.normalized, 0, cache.normalized.length, sortList ); return cache; } function buildTransformTable() { var digits = '0123456789,.'.split( '' ); var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ); var digitTransformTable = mw.config.get( 'wgDigitTransformTable' ); if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) { ts.transformTable = false; } else { ts.transformTable = {}; // Unpack the transform table var ascii = separatorTransformTable[0].split( "\t" ).concat( digitTransformTable[0].split( "\t" ) ); var localised = separatorTransformTable[1].split( "\t" ).concat( digitTransformTable[1].split( "\t" ) ); // Construct regex for number identification for ( var i = 0; i < ascii.length; i++ ) { ts.transformTable[localised[i]] = ascii[i]; digits.push( $.escapeRE( localised[i] ) ); } } var digitClass = '[' + digits.join( '', digits ) + ']'; // We allow a trailing percent sign, which we just strip. This works fine // if percents and regular numbers aren't being mixed. ts.numberRegex = new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific "|" + "[-+\u2212]?" + digitClass + "+[\\s\\xa0]*%?" + // Generic localised "|" + "inf.*" + //Infinite ")$", "i"); } function buildDateTable() { var regex = []; ts.monthNames = [ [], [] ]; for ( var i = 1; i < 13; i++ ) { ts.monthNames[0][i] = mw.config.get( 'wgMonthNames' )[i].toLowerCase(); ts.monthNames[1][i] = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' ); regex.push( $.escapeRE( ts.monthNames[0][i] ) ); regex.push( $.escapeRE( ts.monthNames[1][i] ) ); } // Build piped string regex = regex.join( '|' ); // Build RegEx // Any date formated with . , ' - or / ts.dateRegex[0] = new RegExp( /^\s*\d{1,2}[\,\.\-\/'\s]{1,2}\d{1,2}[\,\.\-\/'\s]{1,2}\d{2,4}\s*?/i); // Written Month name, dmy ts.dateRegex[1] = new RegExp( '^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' ); // Written Month name, mdy ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' ); } function explodeRowspans( $table ) { // Split multi row cells into multiple cells with the same content $table.find( '> tbody > tr > [rowspan]' ).each(function() { var rowSpan = this.rowSpan; this.rowSpan = 1; var cell = $( this ); var next = cell.parent().nextAll(); for ( var i = 0; i < rowSpan - 1; i++ ) { var td = next.eq( i ).children( 'td' ); if ( !td.length ) { next.eq( i ).append( cell.clone() ); } else if ( this.cellIndex === 0 ) { td.eq( this.cellIndex ).before( cell.clone() ); } else { td.eq( this.cellIndex - 1 ).after( cell.clone() ); } } }); } function buildCollationTable() { ts.collationTable = mw.config.get( 'tableSorterCollation' ); ts.collationRegex = null; if ( ts.collationTable ) { var keys = []; // Build array of key names for ( var key in ts.collationTable ) { if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe keys.push(key); } } if (keys.length) { ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' ); } } } function cacheRegexs() { if ( ts.rgx ) { return; } ts.rgx = { IPAddress: [ new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/) ], currency: [ new RegExp( /^[£$€?.]/), new RegExp( /[£$€]/g) ], url: [ new RegExp( /^(https?|ftp|file):\/\/$/), new RegExp( /(https?|ftp|file):\/\//) ], isoDate: [ new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/) ], usLongDate: [ new RegExp( /^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/) ], time: [ new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/) ], fileSize : [ new RegExp( /((^[0-9]+(\.[0-9]+)?)|(\.[0-9]+))[ \t]*[kmgtp]?i?b/i) ] }; } /* Public scope */ $.tablesorter = { defaultOptions: { cssHeader: 'headerSort', cssAsc: 'headerSortUp', cssDesc: 'headerSortDown', cssChildRow: 'expand-child', sortInitialOrder: 'asc', sortMultiSortKey: 'shiftKey', sortLocaleCompare: false, parsers: {}, widgets: [], headers: {}, cancelSelection: true, sortList: [], headerList: [], selectorHeaders: 'thead tr:eq(0) th', debug: false }, dateRegex: [], monthNames: [], /** * @param $tables {jQuery} * @param settings {Object} (optional) */ construct: function( $tables, settings ) { return $tables.each( function( i, table ) { // Declare and cache. var $document, $headers, cache, config, sortOrder, $table = $( table ), shiftDown = 0, firstTime = true; // Quit if no tbody if ( !table.tBodies ) { return; } if ( !table.tHead ) { // No thead found. Look for rows with <th>s and // move them into a <thead> tag or a <tfoot> tag emulateTHeadAndFoot( $table ); // Still no thead? Then quit if ( !table.tHead ) { return; } } $table.addClass( "jquery-tablesorter" ); // New config object. table.config = {}; // Merge and extend. config = $.extend( table.config, $.tablesorter.defaultOptions, settings ); // Save the settings where they read $.data( table, 'tablesorter', config ); // Get the CSS class names, could be done else where. var sortCSS = [ config.cssDesc, config.cssAsc ]; var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ]; // Build headers $headers = buildHeaders( table, sortMsg ); // Grab and process locale settings buildTransformTable(); buildDateTable(); buildCollationTable(); // Precaching regexps can bring 10 fold // performance improvements in some browsers. cacheRegexs(); // Apply event handling to headers // this is too big, perhaps break it out? $headers.click( function( e ) { if ( e.target.nodeName.toLowerCase() == 'a' ) { // The user clicked on a link inside a table header // Do nothing and let the default link click action continue return true; } if ( firstTime ) { firstTime = false; // Legacy fix of .sortbottoms // Wrap them inside inside a tfoot (because that's what they actually want to be) & // and put the <tfoot> at the end of the <table> var $sortbottoms = $table.find( '> tbody > tr.sortbottom' ); if ( $sortbottoms.length ) { var $tfoot = $table.children( 'tfoot' ); if ( $tfoot.length ) { $tfoot.eq(0).prepend( $sortbottoms ); } else { $table.append( $( '<tfoot>' ).append( $sortbottoms ) ) } } explodeRowspans( $table ); // try to auto detect column type, and store in tables config table.config.parsers = buildParserCache( table, $headers ); // build the cache for the tbody cells cache = buildCache( table ); } var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0; if ( !table.sortDisabled && totalRows > 0 ) { // Cache jQuery object var $cell = $( this ); // Get current column index var i = this.column; // Get current column sort order this.order = this.count % 2; this.count++; // User only wants to sort on one column if ( !e[config.sortMultiSortKey] ) { // Flush the sort list config.sortList = []; // Add column to sort list config.sortList.push( [i, this.order] ); // Multi column sorting } else { // The user has clicked on an already sorted column. if ( isValueInArray( i, config.sortList ) ) { // Reverse the sorting direction for all tables. for ( var j = 0; j < config.sortList.length; j++ ) { var s = config.sortList[j], o = config.headerList[s[0]]; if ( s[0] == i ) { o.count = s[1]; o.count++; s[1] = o.count % 2; } } } else { // Add column to sort list array config.sortList.push( [i, this.order] ); } } // Set CSS for headers setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg ); appendToTable( $table[0], multisort( $table[0], config.sortList, cache ) ); // Stop normal event by returning false return false; } // Cancel selection } ).mousedown( function() { if ( config.cancelSelection ) { this.onselectstart = function() { return false; }; return false; } } ); } ); }, addParser: function( parser ) { var l = parsers.length, a = true; for ( var i = 0; i < l; i++ ) { if ( parsers[i].id.toLowerCase() == parser.id.toLowerCase() ) { a = false; } } if ( a ) { parsers.push( parser ); } }, formatDigit: function( s ) { s = s.replace( /^inf.*$/ig, 'Infinity' ); if ( ts.transformTable !== false ) { var out = '', c; for ( var p = 0; p < s.length; p++ ) { c = s.charAt(p); if ( c in ts.transformTable ) { out += ts.transformTable[c]; } else { out += c; } } s = out; } var i = parseFloat( s.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) ); return ( isNaN(i)) ? 0 : i; }, formatFloat: function( s ) { var i = parseFloat(s); return ( isNaN(i)) ? 0 : i; }, formatInt: function( s ) { var i = parseInt( s, 10 ); return ( isNaN(i)) ? 0 : i; }, clearTableBody: function( table ) { if ( $.browser.msie ) { var empty = function( el ) { while ( el.firstChild ) { el.removeChild( el.firstChild ); } }; empty( table.tBodies[0] ); } else { table.tBodies[0].innerHTML = ''; } } }; // Shortcut ts = $.tablesorter; // Register as jQuery prototype method $.fn.tablesorter = function( settings ) { return ts.construct( this, settings ); }; // Add default parsers ts.addParser( { id: 'text', is: function( s ) { return true; }, format: function( s ) { s = $.trim( s.toLowerCase() ); if ( ts.collationRegex ) { var tsc = ts.collationTable; s = s.replace( ts.collationRegex, function( match ) { var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()]; return r.toLowerCase(); } ); } return s; }, type: 'text' } ); ts.addParser( { id: 'IPAddress', is: function( s ) { return ts.rgx.IPAddress[0].test(s); }, format: function( s ) { var a = s.split( '.' ), r = '', l = a.length; for ( var i = 0; i < l; i++ ) { var item = a[i]; if ( item.length == 1 ) { r += '00' + item; } else if ( item.length == 2 ) { r += '0' + item; } else { r += item; } } return $.tablesorter.formatFloat(r); }, type: 'numeric' } ); ts.addParser( { id: 'currency', is: function( s ) { return ts.rgx.currency[0].test(s); }, format: function( s ) { return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) ); }, type: 'numeric' } ); ts.addParser( { id: 'url', is: function( s ) { return ts.rgx.url[0].test(s); }, format: function( s ) { return $.trim( s.replace( ts.rgx.url[1], '' ) ); }, type: 'text' } ); ts.addParser( { id: 'isoDate', is: function( s ) { return ts.rgx.isoDate[0].test(s); }, format: function( s ) { return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace( new RegExp( /-/g), '/')).getTime() : '0' ); }, type: 'numeric' } ); ts.addParser( { id: 'usLongDate', is: function( s ) { return ts.rgx.usLongDate[0].test(s); }, format: function( s ) { return $.tablesorter.formatFloat( new Date(s).getTime() ); }, type: 'numeric' } ); ts.addParser( { id: 'date', is: function( s ) { return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s )); }, format: function( s, table ) { s = $.trim( s.toLowerCase() ); for ( var i = 1, j = 0; i < 13 && j < 2; i++ ) { s = s.replace( ts.monthNames[j][i], i ); if ( i == 12 ) { j++; i = 0; } } s = s.replace( /[\-\.\,' ]/g, '/' ); // Replace double slashes s = s.replace( /\/\//g, '/' ); s = s.replace( /\/\//g, '/' ); s = s.split( '/' ); // Pad Month and Day if ( s[0] && s[0].length == 1 ) { s[0] = '0' + s[0]; } if ( s[1] && s[1].length == 1 ) { s[1] = '0' + s[1]; } var y; if ( !s[2] ) { // Fix yearless dates s[2] = 2000; } else if ( ( y = parseInt( s[2], 10) ) < 100 ) { // Guestimate years without centuries if ( y < 30 ) { s[2] = 2000 + y; } else { s[2] = 1900 + y; } } // Resort array depending on preferences if ( mw.config.get( 'wgDefaultDateFormat' ) == 'mdy' || mw.config.get( 'wgContentLanguage' ) == 'en' ) { s.push( s.shift() ); s.push( s.shift() ); } else if ( mw.config.get( 'wgDefaultDateFormat' ) == 'dmy' ) { var d = s.shift(); s.push( s.shift() ); s.push(d); } return parseInt( s.join( '' ), 10 ); }, type: 'numeric' } ); ts.addParser( { id: 'time', is: function( s ) { return ts.rgx.time[0].test(s); }, format: function( s ) { return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() ); }, type: 'numeric' } ); ts.addParser( { id: 'number', is: function( s, table ) { return $.tablesorter.numberRegex.test( $.trim( s )); }, format: function( s ) { return $.tablesorter.formatDigit(s); }, type: 'numeric' }); ts.addParser( { id: 'fileSize', is: function( s, table ) { return ts.rgx.fileSize[0].test( $.trim( s )); }, format: function( s ) { var base = $.tablesorter.formatDigit(s); var multiplier = 1; var b = 1024; if (/i/i.test(s)) { b = 1000; } if (/P/i.test(s)) { multiplier = Math.pow(b, 5); } if (/T/i.test(s)) { multiplier = Math.pow(b, 4); } else if (/G/i.test(s)) { multiplier = Math.pow(b, 3); } else if (/M/i.test(s)) { multiplier = b * b; } else if (/K/i.test(s)) { multiplier = b; } return base * multiplier; }, type: 'numeric' }); } )( jQuery );
JavaScript
/** $Id$ */ // Title: Fadomatic // Version: 1.2 // Homepage: http://chimpen.com/fadomatic // Author: Philip McCarthy <fadomatic@chimpen.com> // Fade interval in milliseconds // Make this larger if you experience performance issues Fadomatic.INTERVAL_MILLIS = 50; // Creates a fader // element - The element to fade // speed - The speed to fade at, from 0.0 to 100.0 // initialOpacity (optional, default 100) - element's starting opacity, 0 to 100 // minOpacity (optional, default 0) - element's minimum opacity, 0 to 100 // maxOpacity (optional, default 0) - element's minimum opacity, 0 to 100 function Fadomatic (element, rate, initialOpacity, minOpacity, maxOpacity) { this._element = element; this._intervalId = null; this._rate = rate; this._isFadeOut = true; // Set initial opacity and bounds // NB use 99 instead of 100 to avoid flicker at start of fade this._minOpacity = 0; this._maxOpacity = 99; this._opacity = 99; if (typeof minOpacity != 'undefined') { if (minOpacity < 0) { this._minOpacity = 0; } else if (minOpacity > 99) { this._minOpacity = 99; } else { this._minOpacity = minOpacity; } } if (typeof maxOpacity != 'undefined') { if (maxOpacity < 0) { this._maxOpacity = 0; } else if (maxOpacity > 99) { this._maxOpacity = 99; } else { this._maxOpacity = maxOpacity; } if (this._maxOpacity < this._minOpacity) { this._maxOpacity = this._minOpacity; } } if (typeof initialOpacity != 'undefined') { if (initialOpacity > this._maxOpacity) { this._opacity = this._maxOpacity; } else if (initialOpacity < this._minOpacity) { this._opacity = this._minOpacity; } else { this._opacity = initialOpacity; } } // See if we're using W3C opacity, MSIE filter, or just // toggling visiblity if(typeof element.style.opacity != 'undefined') { this._updateOpacity = this._updateOpacityW3c; } else if(typeof element.style.filter != 'undefined') { // If there's not an alpha filter on the element already, // add one if (element.style.filter.indexOf("alpha") == -1) { // Attempt to preserve existing filters var existingFilters=""; if (element.style.filter) { existingFilters = element.style.filter+" "; } element.style.filter = existingFilters+"alpha(opacity="+this._opacity+")"; } this._updateOpacity = this._updateOpacityMSIE; } else { this._updateOpacity = this._updateVisibility; } this._updateOpacity(); } // Initiates a fade out Fadomatic.prototype.fadeOut = function () { this._isFadeOut = true; this._beginFade(); } // Initiates a fade in Fadomatic.prototype.fadeIn = function () { this._isFadeOut = false; this._beginFade(); } // Makes the element completely opaque, stops any fade in progress Fadomatic.prototype.show = function () { this.haltFade(); this._opacity = this._maxOpacity; this._updateOpacity(); } // Makes the element completely transparent, stops any fade in progress Fadomatic.prototype.hide = function () { this.haltFade(); this._opacity = 0; this._updateOpacity(); } // Halts any fade in progress Fadomatic.prototype.haltFade = function () { clearInterval(this._intervalId); } // Resumes a fade where it was halted Fadomatic.prototype.resumeFade = function () { this._beginFade(); } // Pseudo-private members Fadomatic.prototype._beginFade = function () { this.haltFade(); var objref = this; this._intervalId = setInterval(function() { objref._tickFade(); },Fadomatic.INTERVAL_MILLIS); } Fadomatic.prototype._tickFade = function () { if (this._isFadeOut) { this._opacity -= this._rate; if (this._opacity < this._minOpacity) { this._opacity = this._minOpacity; this.haltFade(); } } else { this._opacity += this._rate; if (this._opacity > this._maxOpacity ) { this._opacity = this._maxOpacity; this.haltFade(); } } this._updateOpacity(); } Fadomatic.prototype._updateVisibility = function () { if (this._opacity > 0) { this._element.style.visibility = 'visible'; } else { this._element.style.visibility = 'hidden'; } } Fadomatic.prototype._updateOpacityW3c = function () { this._element.style.opacity = this._opacity/100; this._updateVisibility(); } Fadomatic.prototype._updateOpacityMSIE = function () { this._element.filters.alpha.opacity = this._opacity; this._updateVisibility(); } Fadomatic.prototype._updateOpacity = null;
JavaScript
$(function() { var lang = hb.constant.lang; var base = hb.constant.url.base; var title = $('title'); var origTitle = title.text(); var checkInt = 10; var alertMsg = $('#alert-message'); var dialogOpen = false; var localStorageReallyWorks = false; if("localStorage" in window){ try { window.localStorage.setItem('_tmptest', 'tmpval'); localStorageReallyWorks = true; window.localStorage.removeItem('_tmptest'); } catch(BogusQuotaExceededErrorOnIos5) { // Thanks be to iOS5 Private Browsing mode which throws // QUOTA_EXCEEDED_ERRROR DOM Exception 22. } } var markread = function(id, callback) { $.post('//' + base + '/messages.php?format=json&action=moveordel', { 'messages[]' : id, 'markread' : true }, callback); }; var bindClick = function(alertMsg, result) { if (location.pathname.split('/').pop() !== 'messages.php') { var click = function(result) { if (!dialogOpen) { var text = '<table cellpadding="2" class="no-vertical-line" style="width:100%"><thead><th>主题</th><th>发信人</th><th class="unsortable"></th><th class="unsortable"></th><th class="unsortable">预览 (点击显示全部)</th></thead><tbody></tbody></table>'; var dialog = $('<div></div>', { title : '站内信 (<a href="//' + base + '/messages.php">打开传统界面</a>)', html : text }); var tbody = dialog.find('tbody'); $.each(result, function() { var msg = this; var t = '<tr sender="' + msg.sender.id + '" msgid="' + msg.id + '"><td><a href="//' + base + '/messages.php?action=viewmessage&amp;id=' + msg.id + '" title="' + msg.added + '" class="alert-message-subject">' + msg.subject + '</a></td><td>'; if (msg.sender.id !== 0) { var userClass = msg.sender['class'].canonical; var userCss = userClass.replace(/\s/g, '') + '_Name username'; t += '<a href="//' + base + '/userdetails.php?id=' + msg.sender.id + '" class="' + userCss + '">'; } t += msg.sender.username; if (msg.sender.id !== 0) { t += '</a>'; } t += '</td><td>'; t += '<a href="#" class="alert-message-read">已读</a>'; t += '</td><td>'; if (msg.sender.id !== 0 && msg.sender.id != hb.config.user.id) { var replyUri = '//' + base + '/sendmessage.php?receiver=' + msg.sender.id + '&amp;replyto=' + msg.id; t += '<a href="' + replyUri + '" class="alert-message-reply">' + '回复' + '</a>'; } t += '</td><td style="position:relative;zoom:1" title="点击显示全部"><div class="alert-message-body">' + msg.msg + '</div></td></tr>'; var $t = $(t); $t.find('.alert-message-reply').click(function(e) { e.preventDefault(); jqui_form($('<form action="//' + base + '/takemessage.php?format=json&receiver=' + msg.sender.id + '&subject=Re%3A' + encodeURIComponent(msg.subject) + '&origmsg=' + msg.id + '" style="height:200px"><textarea name="body" style="width:100%;height:100%" autofocus="autofocus" required="required">' + msg.msg_bbcode + "\n\n-------- [user=" + msg.sender.id + '] [i] Wrote at ' + msg.added + ":[/i] --------\n\n</textarea></form>"), 'Re:' + msg.subject + ' (<a href="' + replyUri + '">打开完整编辑</a>)', function(result, dialog) { if (!result.success) { dialog.find('#dialog-hint').text(result.message); return false; } else { markread(msg.id, function(result) { if (result.success) { $t.remove(); } }); return true; } }, null, 500); }); $t.find('.alert-message-read').click(function(e) { e.preventDefault(); markread(msg.id, function(result) { if (result.success) { $t.remove(); } if (tbody.find('tr').length === 0) { dialogOpen = false; dialog.remove(); } }); }) var showAll = false; $t.find('.alert-message-body').click(function() { if (showAll) { return; } showAll = true; $(this).parent().prepend($('<div style="border:dashed silver 1px;position:absolute;top:0;background-color:white;z-index:999;padding:0.5em;border-radius:3px;display:none;">' + msg.msg + '</div>').show().click(function() { $(this).remove(); showAll = false; })); markread(msg.id, function(result) { if (result.success) { $t.find('.alert-message-read').remove(); } }); }); tbody.append($t); }); dialogOpen = true; dialog.dialog({ autoOpen : true, modal : true, width : '70%', 'close' : function() { dialogOpen = false; dialog.remove(); } }).find('table').tablesorter(); } }; alertMsg.unbind('click').click(function(e) { e.preventDefault(); if (typeof(result) === 'undefined') { getResult(click); } else { click(result); } }); } }; var processResult = function (result) { if (result.length !== 0) { title.text('(' + result.length + ') ' + origTitle); if (alertMsg.length === 0) { alertMsg = $('<li></li>', { style : 'background-color: red', id : 'alert-message' }).append($('<a></a>', { href : '//' + base + '/messages.php' })); $('#alert').append(alertMsg); } alertMsg.find('a').text(lang.text_you_have + result.length + lang.text_new_message + lang.text_click_here_to_read); bindClick(alertMsg, result); } else { alertMsg.remove(); title.text(origTitle); } }; var getResult = function(callback) { if (localStorageReallyWorks) { var lastGet = localStorage.getItem('pmGetTime'); if (lastGet && ((new Date()).getTime() - parseInt(lastGet)) < checkInt * 1000 ) { setTimeout(checkMsg, checkInt * 1000); callback($.parseJSON(localStorage.getItem('pmResult'))); return; } } $.getJSON('//' + base + '/messages.php?format=json&unread=yes', {'time' : (new Date()).getTime()}, function (result) { callback(result); if (localStorageReallyWorks) { localStorage.setItem('pmGetTime', (new Date().getTime())); localStorage.setItem('pmResult', $.toJSON(result)); } setTimeout(checkMsg, checkInt * 1000); }); }; var checkMsg = function() { getResult(processResult); }; bindClick($('#alert-message')); setTimeout(checkMsg, checkInt * 1000); });
JavaScript
function postvalid(form) { $('#qr').disabled = true; return true; } function dropmenu(obj){ $('#' + obj.id + 'list').slideToggle(); } function confirm_delete(id, note, addon) { if(confirm(note)) { self.location.href='?action=del'+(addon ? '&'+addon : '')+'&id='+id; } } // smileit.js $(function() { $('.smileit').click(function(e) { e.preventDefault(); var $this = $(this); SmileIT('[em' + $this.attr('smile') + ']', $this.attr('form')); }); }); function SmileIT(smile,form,text){ doInsert(smile, '', false, $(document.forms[form]).find('textarea')[0]); } var is_ie = $.browser.msie; function doInsert(ibTag, ibClsTag, isSingle, obj_ta) { var isClose = false; obj_ta = obj_ta || document[hb.bbcode.form][hb.bbcode.text]; if (obj_ta.selectionStart || obj_ta.selectionStart == '0') { var startPos = obj_ta.selectionStart; var endPos = obj_ta.selectionEnd; var val = obj_ta.value; obj_ta.value = val.substring(0, startPos) + ibTag + val.substring(startPos, endPos) + ibClsTag + obj_ta.value.substring(endPos, obj_ta.value.length); obj_ta.selectionStart = startPos + ibTag.length; obj_ta.selectionEnd = ibTag.length + endPos; } else if (is_ie && obj_ta.isTextEdit) { obj_ta.focus(); var sel = document.selection; var rng = sel.createRange(); rng.colapse; if ((sel.type == "Text" || sel.type == "None") && rng != null) { if(ibClsTag != "" && rng.text.length > 0) { ibTag += rng.text + ibClsTag; } else if (isSingle) { isClose = true; } rng.text = ibTag; } } else { if(isSingle) isClose = true; obj_ta.value += ibTag; } obj_ta.focus(); return isClose; } // java_klappe.js function klappe(id) { var klappText = document.getElementById('k' + id); var klappBild = document.getElementById('pic' + id); if (klappText.style.display == 'none') { klappText.style.display = 'block'; // klappBild.src = 'pic/blank.gif'; } else { klappText.style.display = 'none'; // klappBild.src = 'pic/blank.gif'; } } var klappe_news = (function() { var locks = {}; var unlock = function (id) { locks[id] = false; }; return function (id, noPic) { if (locks[id]) { return; } else { locks[id] = true; } var $klappText = $('#k' + id); if (noPic) { $klappText.slideToggle('normal', function() { unlock(id); }); } else { var klappBild = document.getElementById('pic' + id); if ($klappText.css('display') === 'none') { $klappText.slideDown('normal', function() { unlock(id); }); klappBild.className = 'minus'; } else { $klappText.slideUp('normal', function() { unlock(id); }); klappBild.className = 'plus'; } } } })(); function klappe_ext(id) { var klappText = document.getElementById('k' + id); var klappBild = document.getElementById('pic' + id); var klappPoster = document.getElementById('poster' + id); if (klappText.style.display == 'none') { klappText.style.display = 'block'; klappPoster.style.display = 'block'; klappBild.className = 'minus'; } else { klappText.style.display = 'none'; klappPoster.style.display = 'none'; klappBild.className = 'plus'; } } // disableother.js function disableother(select,target) { if (document.getElementById(select).value == 0) document.getElementById(target).disabled = false; else { document.getElementById(target).disabled = true; document.getElementById(select).disabled = false; } } function disableother2(oricat,newcat) { if (document.getElementById("movecheck").checked == true){ document.getElementById(oricat).disabled = true; document.getElementById(newcat).disabled = false; } else { document.getElementById(oricat).disabled = false; document.getElementById(newcat).disabled = true; } } // ctrlenter.js var submitted = false; function ctrlenter(event,formname,submitname){ if (submitted == false){ var keynum; if (event.keyCode){ keynum = event.keyCode; } else if (event.which){ keynum = event.which; } if (event.ctrlKey && keynum == 13){ submitted = true; document.getElementById(formname).submit(); } } } // bookmark.js function bookmark(torrentid) { $.getJSON('bookmark.php', {torrentid : torrentid}, function(result) { var status = result.status; bmicon(status, torrentid); }); } function bmicon(status,torrentid) { if (status=="added") { document.getElementById("bookmark"+torrentid).innerHTML="<img class=\"bookmark\" src=\"pic/trans.gif\" alt=\"Bookmarked\" />"; } else if (status=="deleted") { document.getElementById("bookmark"+torrentid).innerHTML="<img class=\"delbookmark\" src=\"pic/trans.gif\" src=\"pic/trans.gif\" alt=\"Unbookmarked\" />"; } } // check.js var checkflag = "false"; function check(field,checkall_name,uncheckall_name) { if (checkflag == "false") { for (i = 0; i < field.length; i++) { field[i].checked = true;} checkflag = "true"; return uncheckall_name; } else { for (i = 0; i < field.length; i++) { field[i].checked = false; } checkflag = "false"; return checkall_name; } } // in functions.php function get_ext_info_ajax(blockid,url,cache,type) { if (document.getElementById(blockid).innerHTML==""){ var infoblock=ajax.gets('getextinfoajax.php?url='+url+'&cache='+cache+'&type='+type); document.getElementById(blockid).innerHTML=infoblock; } return true; } //scroll commons var scrollToPosition = (function() { var $document = $(document); return function(top) { var goTop=setInterval(scrollMove,10); var buf = -1000; var buf_pos = -1000; function scrollMove(){ var pos = $document.scrollTop(); if (pos != buf_pos && buf_pos >= 0) { clearInterval(goTop); } var diff = pos - top; $document.scrollTop(diff / 1.2 + top); buf_pos = $document.scrollTop(); if(Math.abs(diff) < 1 || Math.abs(buf - pos) <1) { clearInterval(goTop); } buf = pos; } }; })(); $(function() { var $top = $('#top'); if ($top.length === 0) { return; } var top = $top.offset().top; var $document = $(document); $('a[href="#top"]').click(function(e) { e.preventDefault(); scrollToPosition(top); }); }); //curtain_imageresizer.js $(function() { if (navigator.appName=="Netscape") { $('body').css('overflow-y', 'scroll'); } var ie6 = $.browser.msie && $.browser.version < 7; var lightbox = $('#lightbox'); var curtain = $('#curtain'); lightbox.click(function () { lightbox.hide(); curtain.fadeOut(); }); $('img.scalable').click(function() { var url = $(this).attr('full') || this.src; if (!ie6){ lightbox.html("<img src=\"" + url + "\" />").fadeIn(); curtain.fadeIn(); } else{ window.open(url); } }); }); function findPosition( oElement ) { if( typeof( oElement.offsetParent ) != 'undefined' ) { for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) { posX += oElement.offsetLeft; posY += oElement.offsetTop; } return [ posX, posY ]; } else { return [ oElement.x, oElement.y ]; } } $(function() { //Back to top var backtotop = $('#back-to-top'); var $document = $(document); backtotop.click(function(e) { e.preventDefault(); scrollToPosition(0); }); window.onscroll=function() { $document.scrollTop() > 200 ? backtotop.css('display', "") : backtotop.css('display', 'none'); }; }); var argsFromUri = function(uri) { var args = new Object(); var query = uri.split('?'); if (query.length !== 2) { return {}; } query = query[1].split('#')[0]; $.each(query.split('&'), function(idx, obj) { var t = obj.split('='); args[t[0]] = decodeURIComponent(t[1]); }); return args; }; // Used in index.php & fun.php $(function() { $('#funcomment dt .username').each(function() { var user = $(this); user.after($('<a />', { href : '#', text : '回复', 'class' : 'funcomment-reply' }).click(function(e) { e.preventDefault(); var target = $('#fun_text'); var id = user.find('.user-id').text(); var val = target.val().replace(/^@\[user=[0-9]+\] */ig, ''); target.val('@[user=' + id + '] ' + val).focus(); })); }); }); var TimeLimit = function(check, target) { }; var timeLimit = function(check, time, timeTool) { var inited = false; var str2date = function(string) { var default_date = new Date(); date_part = string.split(' ')[0].split('-'); time_part = string.split(' ')[1].split(':'); default_date.setFullYear(date_part[0]); default_date.setMonth(date_part[1] - 1); default_date.setDate(date_part[2]); default_date.setHours(time_part[0]); default_date.setMinutes(time_part[1]); default_date.setSeconds(time_part[2]); return default_date; } var timeBox = time.find('input'); return function() { if (!check()) { time.slideUp(); timeTool.fadeOut(); } else { if (!inited) { inited = true; timeTool.html('<label><select id="time_select_day"><option value="0">0</option><option value="1" selected="selected">1</option><option value="2">2</option><option value="3">3</option><option value="5">5</option><option value="7">7</option><option value="10">10</option><option value="15">15</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option><option value="60">60</option><option value="90">90</option><option value="180">180</option><option value="365">365</option></select>天</label><label><select id="time_select_hour"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="8">8</option><option value="10">10</option><option value="12">12</option><option value="15">15</option><option value="18">18</option><option value="20">20</option></select>小时</label><label><select id="time_select_minute"><option value="0">0</option><option value="5">5</option><option value="10">10</option><option value="15">15</option><option value="20">20</option><option value="25">25</option><option value="30">30</option><option value="45">45</option></select>分钟</label>').append($('<input />', { type : 'button', value : '延长促销时间' }).click(function() { var new_date = new Date(); var day = $('#time_select_day').val(); var hour = $('#time_select_hour').val(); var minute = $('#time_select_minute').val(); // 换算成毫秒 var time_period = (day * 24 * 3600 + hour * 3600 + minute * 60) * 1000; var default_unixtime = str2date(timeBox.val()); new_date.setTime(default_unixtime.valueOf() + time_period); timeBox.val(new_date.getFullYear() + '-' + (new_date.getMonth() + 1) + '-' + new_date.getDate() + ' ' + new_date.getHours() + ':' + new_date.getMinutes() + ':' + new_date.getSeconds()); return false; })); } time.slideDown(); timeTool.fadeIn(); } } }; var editPr = function() { $pr_type = $('#sel_spstate'); if ($pr_type.length) { $pr_time_type = $('#promotion_time_type').attr("disabled", "disabled"); $pr_time = $('#promotionuntil'); var validatePrTimeType = function() { if ($pr_type.val() === '1') { $pr_time_type.attr("disabled", "disabled"); } else { $pr_time_type.removeAttr("disabled"); } validatePrTime(); }; var validatePrTime = timeLimit(function() { return ($pr_time_type.val() === '2'); }, $('#pr-expire'), $('#expand-pr')); validatePrTimeType(); $pr_type.change(validatePrTimeType); $pr_time_type.change(validatePrTime); } }; //edit position status Added by Eggsorer var editPos = function() { $pos_state = $('#sel_posstate'); $pos_time = $('#posstateuntil'); var validatePosTime = timeLimit(function() { return ($pos_state.val() === 'sticky'||$pos_state.val() === 'random'); }, $('#pos-expire'), $("#expand-pos")); validatePosTime(); $pos_state.change(validatePosTime); }; var createOptions = function(options, defaultOpt) { return $.map(options, function(v, k) { if (v.length === 0) { return ''; } var out = '<option value="' + k + '"'; if (k === defaultOpt) { out += ' selected="selected"'; } out += '>' + v + '</option>'; return out; }).join(''); }; var jqui_dialog = function(title, html, timeout, callback) { var dialog = $('<div />', { title : title, html : html }); var close = function() { dialog.dialog('close'); }; dialog.dialog({ modal : true, autoOpen : true, buttons : { OK : close }, 'close' : function() { dialog.remove(); if (callback) { callback(); } } }); if (timeout) { setTimeout(close, timeout); } }; var jqui_confirm = function(title, html, onOK) { var dialog = $('<div />', { title : title, html : html }); var close = function() { dialog.dialog('close'); }; dialog.dialog({ modal : true, autoOpen : true, buttons : { OK : function() { if (onOK()) { close(); } }, Cancel : close }, 'close' : function() { dialog.remove(); } }); }; var jqui_form = function(form, title, callback, buttons, width) { form.submit(function(e) { e.preventDefault(); onOK(); }); var dialog = $('<div />', { title : title }).append('<div id="dialog-hint"></div>').append(form); var onOK = function() { var valid = true; form.find('.required, input[required]').each(function() { var $this = $(this); if ($this.val().trim().length === 0) { $this.addClass('invalid'); valid = false; } }); if (!valid) { $('#dialog-hint').text('存在无效字段'); return; } $.post(form.attr('action'), form.serialize(), function(result) { if (callback) { if (callback(result, dialog)) { dialog.dialog('close'); } } else { dialog.dialog('close'); } }, 'json'); }; var defaultButtons = { OK : onOK, Cancel : function() { dialog.dialog('close'); } }; if (buttons) { for (var key in defaultButtons) { buttons[key] = defaultButtons[key]; } } else { buttons = defaultButtons; } dialog.dialog({ modal : true, autoOpen : true, buttons : buttons, width : width, 'close' : function() { dialog.remove(); } }); }; var editTorrent = (function() { var prDict = ['', '普通', '免费', '2X', '2X免费', '50%', '2X 50%', '30%']; var untilDict = ['使用全局设置', '永久', '直到']; var posDict = { normal : '普通', sticky : '置顶', random : '随机' }; return function(id, callback) { var cake = hb.constant.url.cake; $.getJSON('//' + cake + '/torrents/view/' + id + '.json', function(result) { var putTarget = '//' + cake + '/torrents/edit/' + id + '.json?%2Fcake%2Ftorrents%2Fedit%2F' + id + '='; var torrent = result.Torrent; var time; var pos_time; if (torrent.promotion_time_type === '2') { time = torrent.promotion_until; } else { var new_date = new Date(); time = new_date.getFullYear() + '-' + (new_date.getMonth() + 1) + '-' + new_date.getDate() + ' ' + new_date.getHours() + ':' + new_date.getMinutes() + ':' + new_date.getSeconds(); } //position if (torrent.pos_state === 'sticky') { pos_time = torrent.pos_state_until; } else { var pos_new_date = new Date(); pos_time = pos_new_date.getFullYear() + '-' + (pos_new_date.getMonth() + 1) + '-' + pos_new_date.getDate() + ' ' + pos_new_date.getHours() + ':' + pos_new_date.getMinutes() + ':' + pos_new_date.getSeconds(); } var html = '<div id="dialog-hint"></div><input type="hidden" name="_method" value="PUT" /><input type="hidden" name="data[Torrent][id]" value="' + id + '" id="TorrentId"><ul><li><label>促销种子<select id="sel_spstate" name="data[Torrent][sp_state]" style="width: 100px;">' + createOptions(prDict, parseInt(torrent.sp_state)) + '</select></label> <select id="promotion_time_type" name="data[Torrent][promotion_time_type]" style="width: 100px;" disabled="disabled">' + createOptions(untilDict, parseInt(torrent.promotion_time_type)) + '</select></li><li><label id="pr-expire">截止日期<input type="text" name="data[Torrent][promotion_until]" id="promotionuntil" style="width: 120px;" value="' + time + '"></label></li><li id="expand-pr" style="display: none; "></li><li><label>种子位置<select name="data[Torrent][pos_state]" style="width: 100px;" id="sel_posstate">' + createOptions(posDict, torrent.pos_state) +'</select></label></li><li><label id="pos-expire">截止日期<input type="text" name="data[Torrent][pos_state_until]" id="posstateuntil" style="width: 120px;" value="' + pos_time + '"></label></li><li id="expand-pos" style="display: none; "></li>'; html += '<li><input type="hidden" name="data[Torrent][oday]" value="no"><label><input type="checkbox" id="sel_oday" name="data[Torrent][oday]" value="yes"'; if (torrent.oday === 'yes') { html += ' checked="checked"'; } html += '>0day资源</label></li></ul>'; var form = $('<form></form>', { html : html, 'class' : 'minor-list', action : putTarget, method : 'post' }); var title = '设定优惠' jqui_form(form, title, function(result) { if (result.success) { if (callback) { callback(); } return true; } else { $('#dialog-hint').text(result.message); return false; } }, { '打开完整编辑' : function() { location.href = '//' + hb.constant.url.base + '/edit.php?id=' + id; }, }, '500'); editPr(); editPos(); }); } })(); var deleteTorrent = (function() { return (function(id, callback) { var cake = hb.constant.url.cake; var deleteTarget = '//' + cake + '/torrents/delete/' + id + '.json'; var reasons = ['断种', '重复', '劣质', '违规', '其它']; var html = '<input type="hidden" name="_method" value="DELETE" /><select id="reason-type" name="data[reasonType]">' + createOptions(reasons, 0) + '</select><input style="display: none;" type="text" id="reason-detail" name="data[reasonDetail]" title="详细理由" />'; var form = $('<form></form>', { html : html, 'class' : 'minor-list', action : deleteTarget, method : 'post' }); form.find('#reason-type').change(function() { var reasonDetail=$('#reason-detail'); var val=parseInt(this.value); if(val===0) { reasonDetail.fadeOut().removeClass('required'); } else { if(val===1||val===2) { reasonDetail.attr('placeholder','可选').removeClass('required').fadeIn(); } else { reasonDetail.attr('placeholder','必填').addClass('required').removeClass('invalid').fadeIn(); } } }); jqui_form(form, '删除种子', function(result) { if (result.success) { jqui_dialog('成功', result.message, 3000, callback); return true; } else { $('#dialog-hint').text(result.message); return false; } }); }); })(); $('form').submit(function() { $(this).find(':submit').attr('disabled', 'disabled'); }); $.getCSS = function(a) { var link = $('<link rel="stylesheet" type="text/css" />').attr('href', a); $("head").append(link); return link; };
JavaScript
$(function() { var file = $('#torrent'); file.change(function () { var filename = document.getElementById("torrent").value; var filename = filename.toString(); var lowcase = filename.toLowerCase(); var start = lowcase.lastIndexOf("\\"); //for Google Chrome on windows/mac if (start == -1){ start = lowcase.lastIndexOf("\/"); // for Google Chrome on linux if (start == -1) start == 0; else start = start + 1; } else start = start + 1; var end = lowcase.lastIndexOf(".torrent"); if (end === -1) { file.val(''); var dialog = $('<div></div>', { title : '警告', text : '请上传torrent文件。' }) dialog.dialog({ modal : true, autoOpen :true }); setTimeout(function() { dialog.dialog('close'); dialog.remove(); }, 3000); return; } var noext = filename.substring(start,end); noext = noext.replace(/H\.264/ig,"H_264"); noext = noext.replace(/5\.1/g,"5_1"); noext = noext.replace(/2\.1/g,"2_1"); noext = noext.replace(/\./g," "); noext = noext.replace(/H_264/g,"H.264"); noext = noext.replace(/5_1/g,"5.1"); noext = noext.replace(/2_1/g,"2.1"); document.getElementById("name").value=noext; }); var validateInputs = function(target, validateSelect) { var result = []; var dts = target.find('.required').next(); dts.find(':input[name!=""][value=""]').each(function() { if (this.value === '') { result.push(this); } }); if (validateSelect) { dts.find('select:not(.no-validate)').each(function() { if (parseInt(this.value) === 0) { result.push(this); } }); } if (result.length) { return result; } else { return false; } }; var form = $('#compose'); form.submit(function(e) { form.find('.invalid').removeClass('invalid'); var invalids = validateInputs(form, true); if (invalids) { e.preventDefault(); $.each(invalids, function() { var t = this; while (t && t.tagName.toLowerCase() !== 'dd') { t = t.parentElement; } if (t) { var dt = t.previousElementSibling; dt.classList.add('invalid'); } }); } }); }); $(function() { var compose = $('#compose'); var validating = (function() { var val = false; return function(newVal) { if (typeof(newVal) === 'undefined') { return val; } else { val = newVal; if (val) { compose.find(':submit').attr('disabled', 'disabled'); } else { compose.find(':submit').removeAttr('disabled'); } } } })(); var form = $('#tcategories'); var tcategory = function(inputs) { inputs.each(function() { var $inputs = $(this); var input = $inputs.find(':text'); var in_id = $inputs.find(':input[type="hidden"]'); //Auto complete var cache = {}; var lastXhr; input.autocomplete({ source: function( request, response ) { var term = request.term; if ( term in cache ) { response( cache[ term ] ); return; } lastXhr = $.getJSON( "/cake/tcategories/search/", request, function( data, status, xhr ) { data = $.map(data, function(item) { return item.Tcategory.name; }); cache[ term ] = data; if ( xhr === lastXhr ) { response( data ); } }); } }); input.blur(function() { $inputs.removeClass('invalid-ref'); var catName = this.value; if (catName !== '') { validating(true); $.getJSON("/cake/tcategories/search/" + catName, function(result) { var validation = true; if (result.length === 1) { var resultId = result[0].Tcategory.id; form.find(':input[type="hidden"]').each(function() { if (resultId == this.value && this !== in_id[0]) { $(this).parent().addClass('invalid-ref'); validation = false; } }); $inputs.find('.remove-tcategory').fadeIn(); } else { validation = false; } if (validation) { input.attr('value', result[0].Tcategory.name); $inputs.removeClass('invalid'); in_id.attr('value', result[0].Tcategory.id); } else { input.focus(); $inputs.addClass('invalid'); } validating(false); }); } else { $inputs.removeClass('invalid'); in_id.attr('value', ''); if (form.find('ul li:last')[0] !== $inputs[0]) { $inputs.remove(); } } }); }); return inputs; }; var removeTcategory = function(e) { e.preventDefault(); $(this).parent().remove(); }; tcategory(form.find('.tcategory')); var lastTcategoryEvent = function() { if (validating()) { setTimeout(lastTcategoryEvent, 100); return; } if (form.find('ul li:last input[type="hidden"]').val().length !== 0) { addTcategory(); lastTcategory(); } }; var lastTcategory = function() { form.find('ul :text').unbind('blur', lastTcategoryEvent); form.find('ul li:last :text').blur(lastTcategoryEvent); }; var addTcategory = function(e) { if (e) { e.preventDefault(); } form.find('ul').append(tcategory($('<li></li>', { 'class' : 'tcategory' }).append($('<input />', { type : 'text', placeholder : 'Tcategory' })).append($('<input />', { type : 'hidden', name : 'data[Tcategory][Tcategory][]' })).append($('<a></a>', { 'class' : 'remove-tcategory', href : '#', text : '-', style : 'display:none;' }).click(removeTcategory)))); lastTcategory(); }; addTcategory(); compose.submit(function(e) { if ($('.invalid').length !== 0) { e.preventDefault(); var dialog = $('<div></div>', { title : '警告', text : '存在无效字段' }); dialog.dialog({ modal : true, autoOpen : true, }); setTimeout(function() { dialog.dialog('close'); dialog.remove(); }, 3000); } }); });
JavaScript
(function() { var dt = new Date(); if (dt.getTime() > 1335715200000) { return; } var stime = $.jStorage.get('timeOverlay', -1); if (stime !== -1) { var today = dt.getDay(); if (stime == today) { return; } } $.jStorage.set('timeOverlay', dt.getDay()); $('body').prepend('<div style="display: block; " id="curtain" class="curtain"></div><div style="display: block;" id="lightbox" class="lightbox"><img src="pic/overlay.jpg" usemap="#ad-overlay-map"><map name="ad-overlay-map"><area shape="circle" coords ="119,95,63" href="#" title="Close" alt="Close" /><area shape="circle" coords ="525,542,63" href="/forums.php?action=viewtopic&amp;forumid=21&amp;topicid=14431" title="Details" alt="Details" /></map></div>'); })();
JavaScript
$(function() { $('#kfilelist table').tablesorter(); $('#saythanks:enabled').click(function() { var torrentid = hb.torrent.id; var list=$.post('thanks.php', { id : torrentid}); document.getElementById("thanksbutton").innerHTML = document.getElementById("thanksadded").innerHTML; document.getElementById("nothanks").innerHTML = ""; document.getElementById("addcuruser").innerHTML = document.getElementById("curuser").innerHTML; }); var showpeer = $('#showpeer'); var hidepeer = $('#hidepeer'); var peercount = $('#peercount'); var peerlist = $('#peerlist'); var showpeerlist = function(href, scrollToTable) { $.get(href, function(res) { peerlist.html(res); peerlist.slideDown(); peercount.slideUp(); showpeer.fadeOut(function() { hidepeer.fadeIn(); }); $('#peerlist table').tablesorter(); if (scrollToTable && window.location.hash) { var scrollTar = $(window.location.hash); if (scrollTar.length) { var top = scrollTar.offset().top - 50; scrollToPosition(top); } } }, 'html'); }; showpeer.click(function(e) { e.preventDefault(); showpeerlist(this.href); }); hidepeer.click(function(e) { e.preventDefault(); peerlist.slideUp(); peercount.slideDown(); hidepeer.fadeOut(function() { showpeer.fadeIn(); }); }); if (argsFromUri(window.location.search).dllist) { showpeerlist(showpeer.attr('href'), true); } }); //TorrentDonate $(function() { $('#to_donate a').click(function(e) { e.preventDefault(); var torrent_id = hb.torrent.id; var bonus = parseInt(hb.config.user.bonus); var to_donate = parseInt($(this).html()); if(bonus < to_donate) { alert('你的魔力值不足,谢谢你的好心,继续努力吧~'); } else if(confirm('确认向种子发布者捐赠 ' + to_donate +' 魔力值吗?')) { var url = 'donateBonus.php'; var data = {amount: to_donate, torrent_id : torrent_id, type: 'torrent'}; $.post(url, data, function(data) { if(data.status == 9) { var newDonate = '<div class="donate'+ data.amount +' donate" id="donated_successfully" title="' + data.message + '\n[' + data.amount + ' 魔力值] ' + data.date + '">' + data.donater + '</div>'; $('#donater_list').append(newDonate); $('#to_donate').html("你已经于 " + data.date + " 对种子发布者进行过魔力值捐赠,谢谢你!"); } else if(data.status == 1) { alert('谢谢你,但是你的魔力值不足,继续努力吧。'); } else if(data.status == 2) { alert('你要捐赠种子不存在。'); } else if(data.status == 3) { alert('你要捐赠的用户不存在。'); } else if(data.status == 4) { alert('只允许以下几个数量的捐赠数:64, 128, 256, 512, 1024。'); } else if(data.status == 5) { alert('不能给自己捐赠的哦!'); } else if(data.status == 6) { alert('你已经捐赠过了,谢谢!'); } else { alert('貌似系统出问题了,呼管理员!'); } }, 'json'); } }); }); // Tcategories $(function() { var form = $('#tcategories'); var cake = '//' + hb.constant.url.cake + '/'; var validating = false; var tcategory = function(inputs) { inputs.each(function() { var $inputs = $(this); var input = $inputs.find(':text'); var in_id = $inputs.find(':input[type="hidden"]'); //Auto complete var cache = {}; var lastXhr; var input_validate = function() { $inputs.removeClass('invalid-ref'); var catName = this.value; if (catName !== '') { validating = true; $.getJSON(cake + "tcategories/search/exact:1/" + catName, function(result) { var validation = true; if (result.length === 1) { var resultId = result[0].Tcategory.id; form.find(':input[type="hidden"]').each(function() { if (resultId == this.value && this !== in_id[0]) { $(this).parent().addClass('invalid-ref'); validation = false; } }); $inputs.find('.remove-tcategory').fadeIn(); } else { validation = false; } if (validation) { input.attr('value', result[0].Tcategory.name); $inputs.removeClass('invalid'); in_id.attr('value', result[0].Tcategory.id); lastTcategoryEvent(); } else { input.focus(); $inputs.addClass('invalid'); } validating = false; }); } else { $inputs.removeClass('invalid'); in_id.attr('value', ''); if (form.find('ul li:last')[0] !== $inputs[0]) { $inputs.remove(); } } }; input.blur(function() { var t = this; setTimeout(function() { input_validate.call(t); }, 100); }); input.autocomplete({ source: function( request, response ) { var term = request.term; if ( term in cache ) { response( cache[ term ] ); return; } lastXhr = $.getJSON(cake + "tcategories/search/", request, function( data, status, xhr ) { data = $.map(data, function(item) { return item.Tcategory.name; }); cache[ term ] = data; if ( xhr === lastXhr ) { response( data ); } }); }, }); }); inputs.find('.remove-tcategory').click(removeTcategory); inputs.find('.edit-tcategory').click(function(e) { e.preventDefault(); var aSpan = $(this).parent(); var li = aSpan.parent(); aSpan.remove(); li.find('.tcategory-edit').fadeIn(); form.find(':submit').fadeIn(); $('#hidden-tcategories').slideDown(); }); return inputs; }; var removeTcategory = function(e) { e.preventDefault(); $(this).parent().parent().remove(); }; tcategory(form.find('.tcategory')); form.submit(function(e) { e.preventDefault(); var params = form.serializeArray(); var warning = function() { if (validating) { setTimeout(warning, 200); return; } if (form.find('.tcategory.invalid').length !== 0) { e.preventDefault(); var dialog = $('<div></div>', { title : '警告', text : '存在无效字段' }).dialog({ modal : true, autoOpen : true, }); setTimeout(function() { dialog.dialog('close'); }, 3000); } else { $.post(form.attr('action'), params, function(result) { if (result.success) { form.find(':submit').hide(); form.find('#add-tcategory').show(); var shows =''; var hiddens = ''; $.each(result.tcategories, function() { var o = generateLi(this); if (this.hidden) { hiddens += o; } else { shows += o; } }); if (hiddens !== '') { shows += '<div style="display: none" id="hidden-tcategories">隐藏分类: ' + hiddens + '</div>'; addShowHiddens(); } tcategory(form.find('ul').html(shows).find('.tcategory')); } else { var dialog = $('<div></div>', { title : '警告', text : result.message }).dialog({ modal : true, autoOpen : true, }); setTimeout(function() { dialog.dialog('close'); }, 3000); } }, 'json'); } }; warning(); }); var lastTcategoryEvent = function() { if (validating) { setTimeout(lastTcategoryEvent, 100); return; } if (form.find('ul li:last input[type="hidden"]').val().length !== 0) { addTcategory(); lastTcategory(); } }; var lastTcategory = function() { form.find('ul :text').unbind('blur', lastTcategoryEvent); form.find('ul li:last :text').blur(lastTcategoryEvent); }; var addTcategory = function(e) { if (e) { e.preventDefault(); } form.find('ul').append(tcategory($('<li></li>', { 'class' : 'tcategory' }).append($('<input />', { type : 'text', placeholder : 'Tcategory' })).append($('<input />', { type : 'hidden', name : 'data[Tcategory][Tcategory][]' })).append($('<a></a>', { 'class' : 'remove-tcategory', href : '#', text : '-', style : 'display:none;' }).click(removeTcategory)))); lastTcategory(); }; var addShowHiddens = (function() { var added = false; return function() { if (added) { return; } added = true; $('#tcategories-title').append('<br />').append($('<a></a>', { href : '#', text : '[显示隐藏分类]', 'class' : 'sublink' }).click(function(e) { e.preventDefault(); $('#hidden-tcategories').slideToggle(); })); } })(); var clickAdd = function(e) { addTcategory(e); $(this).hide(); form.find(':submit').fadeIn(); $('#hidden-tcategories').slideDown(); }; form.find('#add-tcategory').click(clickAdd); if (form.find('.tcategory').length === 0) { clickAdd(); } else if ($('#hidden-tcategories').length !== 0) { addShowHiddens(); } var generateLi = function(tcategory) { return '<li class="tcategory"><span class="tcategory-show"><a href="//' + cake + '/tcategories/view/' + tcategory.id + '">' + tcategory.showName + '</a><a href="#" class="edit-tcategory">±</a></span><span class="tcategory-edit" style="display: none;"><input type="text" placeholder="Tcategory" value="' + tcategory.showName + '" /><input type="hidden" name="data[Tcategory][Tcategory][]" value="' + tcategory.id + '"/ ><a href="#" class="remove-tcategory">-</a></span></li>' }; }); $(function() { $('#set-pr').click(function(e) { e.preventDefault(); editTorrent(hb.torrent.id); }); $('#torrent-delete').click(function(e) { e.preventDefault(); deleteTorrent(hb.torrent.id, function() { location.href = "//" + hb.constant.url.base + '/torrents.php'; }); }); });
JavaScript
$(function() { if (!('config' in hb) || !('pager' in hb.config)) { return; } function gotothepage(page){ var url=window.location.href; var end=url.lastIndexOf("page"); url = url.replace(/#[0-9]+/g,""); if (end == -1){ if (url.lastIndexOf("?") == -1) window.location.href=url+"?page="+page; else window.location.href=url+"&page="+page; } else{ url = url.replace(/page=.+/g,""); window.location.href=url+"page="+page; } } function changepage(event){ var gotopage; var keynum; var altkey; var currentpage = hb.config.pager.current; var maxpage = hb.config.pager.max; if (navigator.userAgent.toLowerCase().indexOf('presto') != -1) altkey = event.shiftKey; else altkey = event.altKey; if (event.keyCode){ keynum = event.keyCode; } else if (event.which){ keynum = event.which; } if(altkey && keynum==33){ if(currentpage<=0) return; gotopage=currentpage-1; gotothepage(gotopage); } else if (altkey && keynum == 34){ if(currentpage>=maxpage) return; gotopage=currentpage+1; gotothepage(gotopage); } } $(window).keydown(changepage); $('.pager-more').click(function(e) { e.preventDefault(); var page = hb.config.pager; var onOK = function() { var target = parseInt($('#pager-go-to').val()) -1; if (target >= 0 && target <= page.max) { gotothepage(target); } else { $('#pager-go-to').addClass('invalid'); } }; var dialog = $('<div></div>', { title : '跳至页码' }).append($('<form></form>', { html : '<label>第<input type="text" id="pager-go-to" style="width:2em;" value="' + (page.current + 1) + '" />页,共' + page.max + '页</label>' }).submit(function(e) { e.preventDefault(); onOK(); })); dialog.dialog({ buttons : { OK : onOK, Cancel : function() { dialog.dialog('close'); } }, modal : false, autoOpen : true }); $('#pager-go-to').keydown(function(e) { if (e.keyCode === 13) { onOK(); } }); }); });
JavaScript
$(function() { var click = function(e) { e.preventDefault(); $.getJSON(this.href, {format : 'json'}, function(res) { document.title = res.title; $('#page-title').html(res.h1); $('#contents').html(res.content); $('#navbar li').each(function(idx, obj) { if (idx === res.navbar[2]) { var span = $('<span></span>', { text : res.navbar[0][idx], 'class' : 'selected' }); $(this).html('').append(span); } else { var a = $('<a></a>', { text : res.navbar[0][idx], href : '?action=' + res.navbar[1][idx] + '&id=' + hb.config.user.id }).click(click); $(this).html('').append(a); } }); }); }; $('#navbar a').click(click); });
JavaScript
var t; function startcountdown(time) { parent.document.getElementById('countdown').innerHTML=time; time=time-1; t=setTimeout("startcountdown("+time+")",1000); } function countdown(time) { if (time <= 0){ parent.document.getElementById("hbtext").disabled=false; parent.document.getElementById("hbsubmit").disabled=false; parent.document.getElementById("hbsubmit").value=parent.document.getElementById("sbword").innerHTML; } else { parent.document.getElementById("hbsubmit").value=time; time=time-1; setTimeout("countdown("+time+")", 1000); } } function hbquota() { parent.document.getElementById("hbtext").disabled=true; parent.document.getElementById("hbsubmit").disabled=true; var time=10; countdown(time); }
JavaScript
$(function() { var redirect = $('#redirect'); var chkRedirect = redirect.find(':checkbox'); var categoryName = $('#TcategoryName'); var cake = '//' + hb.constant.url.cake + '/'; chkRedirect.click(function() { if (chkRedirect.attr('checked')) { redirect.find('.tcategory').fadeIn(); $('#parents').slideUp(); } else { var tcategory = redirect.find('.tcategory').fadeOut(); tcategory.find(':input').val(''); $('#parents').slideDown(); } }); var validating = false; var tcategory = function(inputs) { inputs.each(function() { var $inputs = $(this); var input = $inputs.find(':text'); var in_id = $inputs.find(':input[type="hidden"]'); //Auto complete var cache = {}; var lastXhr; input.autocomplete({ source: function( request, response ) { var term = request.term; if ( term in cache ) { response( cache[ term ] ); return; } lastXhr = $.getJSON( cake + "tcategories/search/", request, function( data, status, xhr ) { data = $.map(data, function(item) { return item.Tcategory.name; }); cache[ term ] = data; if ( xhr === lastXhr ) { response( data ); } }); } }); input.blur(function() { $inputs.removeClass('invalid-ref'); categoryName.removeClass('invalid-ref'); var catName = this.value; if (catName !== '') { if ($inputs.parent().parent().attr('id') === 'parents' && catName === $('#TcategoryName').val()) { input.focus(); $inputs.addClass('invalid'); categoryName.addClass('invalid-ref'); } validating = true; $.getJSON(cake + "tcategories/search/exact:1/" + catName, function(result) { var validation = true; if (result.length === 1) { if ($inputs.parent().attr('id') === 'redirect') { chkRedirect.attr('checked', 'checked'); } else if ($inputs.parent().parent().attr('id') === 'parents') { var resultId = result[0].Tcategory.id; if (resultId == $('#TcategoryId').val()) { validation = false; categoryName.addClass('invalid-ref'); } else { $('#parents :input[type="hidden"]').each(function() { if (resultId == this.value && this !== in_id[0]) { $(this).parent().addClass('invalid-ref'); validation = false; } }); } $inputs.find('.remove-parent').fadeIn(); } } else { validation = false; } if (validation) { input.attr('value', result[0].Tcategory.name); $inputs.removeClass('invalid'); in_id.attr('value', result[0].Tcategory.id); } else { input.focus(); $inputs.addClass('invalid'); } validating = false; }); } else { $inputs.removeClass('invalid'); in_id.attr('value', ''); if ($inputs.parent().attr('id') === 'redirect') { chkRedirect.removeAttr('checked'); } else if ($inputs.parent().parent().attr('id') === 'parents' && $('#parents ul li:last')[0] !== $inputs[0]) { $inputs.remove(); } } }); }); return inputs; }; tcategory($('.tcategory')); categoryName.blur(function() { var act = function(valid) { if (valid) { categoryName.removeClass('invalid'); } else { categoryName.addClass('invalid').focus(); } }; var catName = categoryName.val(); if (catName.length === 0) { act(false); } else { validating = true; $.getJSON(cake + "tcategories/search/exact:true/" + categoryName.val(), function(result) { act(result.length === 0 || (hb.tcategory && result[0].Tcategory.id === hb.tcategory.id)); validating = false; }); } }); var form = $('#TcategoryEditForm'); form.submit(function(e) { e.preventDefault(); var params = form.serializeArray(); var warning = function() { if (validating) { setTimeout(warning, 200); return; } if (form.find('.tcategory.invalid').length !== 0) { e.preventDefault(); var dialog = $('<div></div>', { title : '警告', text : '存在无效字段' }).dialog({ modal : true, autoOpen : true, }); setTimeout(function() { dialog.dialog('close'); }, 3000); } else { $.post(form.attr('action'), params, function(result) { $('#outer').html(result); var state = { title : document.title, url : cake + 'tcategories' } window.history.pushState(state, document.title, cake + 'tcategories'); }); } }; warning(); }); var lastParentEvent = function() { if (validating) { setTimeout(lastParentEvent, 100); return; } if ($('#parents ul li:last input[type="hidden"]').val().length !== 0) { addParent(); lastParent(); } }; var lastParent = function() { $('#parents ul :text').unbind('blur', lastParentEvent); $('#parents ul li:last :text').blur(lastParentEvent); }; lastParent(); var addParent = function(e) { if (e) { e.preventDefault(); } $('#parents ul').append(tcategory($('<li></li>', { 'class' : 'tcategory' }).append($('<input />', { type : 'text', placeholder : 'New parent' })).append($('<input />', { type : 'hidden', name : 'data[Parent][Parent][]' })).append($('<a></a>', { 'class' : 'remove-parent', href : '#', text : '-', style : 'display:none;' }).click(removeParent)))); lastParent(); }; var removeParent = function(e) { e.preventDefault(); $(this).parent().remove(); }; $('.remove-parent').click(removeParent); });
JavaScript
/** $Id: domLib.js 2321 2006-06-12 06:45:41Z dallen $ */ // {{{ license /* * Copyright 2002-2005 Dan Allen, Mojavelinux.com (dan.allen@mojavelinux.com) * * 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. */ // }}} // {{{ intro /** * Title: DOM Library Core * Version: 0.70 * * Summary: * A set of commonly used functions that make it easier to create javascript * applications that rely on the DOM. * * Updated: 2005/05/17 * * Maintainer: Dan Allen <dan.allen@mojavelinux.com> * Maintainer: Jason Rust <jrust@rustyparts.com> * * License: Apache 2.0 */ // }}} // {{{ global constants (DO NOT EDIT) // -- Browser Detection -- var domLib_userAgent = navigator.userAgent.toLowerCase(); var domLib_isMac = navigator.appVersion.indexOf('Mac') != -1; var domLib_isWin = domLib_userAgent.indexOf('windows') != -1; // NOTE: could use window.opera for detecting Opera var domLib_isOpera = domLib_userAgent.indexOf('opera') != -1; var domLib_isOpera7up = domLib_userAgent.match(/opera.(7|8)/i); var domLib_isSafari = domLib_userAgent.indexOf('safari') != -1; var domLib_isKonq = domLib_userAgent.indexOf('konqueror') != -1; // Both konqueror and safari use the khtml rendering engine var domLib_isKHTML = (domLib_isKonq || domLib_isSafari || domLib_userAgent.indexOf('khtml') != -1); var domLib_isIE = (!domLib_isKHTML && !domLib_isOpera && domLib_userAgent.indexOf('msie') != -1); var domLib_isIE5up = domLib_isIE; var domLib_isIE50 = (domLib_isIE && domLib_userAgent.indexOf('msie 5.0') != -1); var domLib_isIE55 = (domLib_isIE && domLib_userAgent.indexOf('msie 5.5') != -1); var domLib_isIE5 = (domLib_isIE50 || domLib_isIE55); // safari and konq may use string "khtml, like gecko", so check for destinctive / var domLib_isGecko = domLib_userAgent.indexOf('gecko/') != -1; var domLib_isMacIE = (domLib_isIE && domLib_isMac); var domLib_isIE55up = domLib_isIE5up && !domLib_isIE50 && !domLib_isMacIE; var domLib_isIE6up = domLib_isIE55up && !domLib_isIE55; // -- Browser Abilities -- var domLib_standardsMode = (document.compatMode && document.compatMode == 'CSS1Compat'); var domLib_useLibrary = (domLib_isOpera7up || domLib_isKHTML || domLib_isIE5up || domLib_isGecko || domLib_isMacIE || document.defaultView); // fixed in Konq3.2 var domLib_hasBrokenTimeout = (domLib_isMacIE || (domLib_isKonq && domLib_userAgent.match(/konqueror\/3.([2-9])/) == null)); var domLib_canFade = (domLib_isGecko || domLib_isIE || domLib_isSafari || domLib_isOpera); var domLib_canDrawOverSelect = (domLib_isMac || domLib_isOpera || domLib_isGecko); var domLib_canDrawOverFlash = (domLib_isMac || domLib_isWin); // -- Event Variables -- var domLib_eventTarget = domLib_isIE ? 'srcElement' : 'currentTarget'; var domLib_eventButton = domLib_isIE ? 'button' : 'which'; var domLib_eventTo = domLib_isIE ? 'toElement' : 'relatedTarget'; var domLib_stylePointer = domLib_isIE ? 'hand' : 'pointer'; // NOTE: a bug exists in Opera that prevents maxWidth from being set to 'none', so we make it huge var domLib_styleNoMaxWidth = domLib_isOpera ? '10000px' : 'none'; var domLib_hidePosition = '-1000px'; var domLib_scrollbarWidth = 14; var domLib_autoId = 1; var domLib_zIndex = 100; // -- Detection -- var domLib_collisionElements; var domLib_collisionsCached = false; var domLib_timeoutStateId = 0; var domLib_timeoutStates = new Hash(); // }}} // {{{ DOM enhancements if (!document.ELEMENT_NODE) { document.ELEMENT_NODE = 1; document.ATTRIBUTE_NODE = 2; document.TEXT_NODE = 3; document.DOCUMENT_NODE = 9; document.DOCUMENT_FRAGMENT_NODE = 11; } function domLib_clone(obj) { var copy = {}; for (var i in obj) { var value = obj[i]; try { if (value != null && typeof(value) == 'object' && value != window && !value.nodeType) { copy[i] = domLib_clone(value); } else { copy[i] = value; } } catch(e) { copy[i] = value; } } return copy; } // }}} // {{{ class Hash() function Hash() { this.length = 0; this.numericLength = 0; this.elementData = []; for (var i = 0; i < arguments.length; i += 2) { if (typeof(arguments[i + 1]) != 'undefined') { this.elementData[arguments[i]] = arguments[i + 1]; this.length++; if (arguments[i] == parseInt(arguments[i])) { this.numericLength++; } } } } // using prototype as opposed to inner functions saves on memory Hash.prototype.get = function(in_key) { if (typeof(this.elementData[in_key]) != 'undefined') { return this.elementData[in_key]; } return null; } Hash.prototype.set = function(in_key, in_value) { if (typeof(in_value) != 'undefined') { if (typeof(this.elementData[in_key]) == 'undefined') { this.length++; if (in_key == parseInt(in_key)) { this.numericLength++; } } return this.elementData[in_key] = in_value; } return false; } Hash.prototype.remove = function(in_key) { var tmp_value; if (typeof(this.elementData[in_key]) != 'undefined') { this.length--; if (in_key == parseInt(in_key)) { this.numericLength--; } tmp_value = this.elementData[in_key]; delete this.elementData[in_key]; } return tmp_value; } Hash.prototype.size = function() { return this.length; } Hash.prototype.has = function(in_key) { return typeof(this.elementData[in_key]) != 'undefined'; } Hash.prototype.find = function(in_obj) { for (var tmp_key in this.elementData) { if (this.elementData[tmp_key] == in_obj) { return tmp_key; } } return null; } Hash.prototype.merge = function(in_hash) { for (var tmp_key in in_hash.elementData) { if (typeof(this.elementData[tmp_key]) == 'undefined') { this.length++; if (tmp_key == parseInt(tmp_key)) { this.numericLength++; } } this.elementData[tmp_key] = in_hash.elementData[tmp_key]; } } Hash.prototype.compare = function(in_hash) { if (this.length != in_hash.length) { return false; } for (var tmp_key in this.elementData) { if (this.elementData[tmp_key] != in_hash.elementData[tmp_key]) { return false; } } return true; } // }}} // {{{ domLib_isDescendantOf() function domLib_isDescendantOf(in_object, in_ancestor, in_bannedTags) { if (in_object == null) { return false; } if (in_object == in_ancestor) { return true; } if (typeof(in_bannedTags) != 'undefined' && (',' + in_bannedTags.join(',') + ',').indexOf(',' + in_object.tagName + ',') != -1) { return false; } while (in_object != document.documentElement) { try { if ((tmp_object = in_object.offsetParent) && tmp_object == in_ancestor) { return true; } else if ((tmp_object = in_object.parentNode) == in_ancestor) { return true; } else { in_object = tmp_object; } } // in case we get some wierd error, assume we left the building catch(e) { return false; } } return false; } // }}} // {{{ domLib_detectCollisions() /** * For any given target element, determine if elements on the page * are colliding with it that do not obey the rules of z-index. */ function domLib_detectCollisions(in_object, in_recover, in_useCache) { // the reason for the cache is that if the root menu is built before // the page is done loading, then it might not find all the elements. // so really the only time you don't use cache is when building the // menu as part of the page load if (!domLib_collisionsCached) { var tags = []; if (!domLib_canDrawOverFlash) { tags[tags.length] = 'object'; } if (!domLib_canDrawOverSelect) { tags[tags.length] = 'select'; } domLib_collisionElements = domLib_getElementsByTagNames(tags, true); domLib_collisionsCached = in_useCache; } // if we don't have a tip, then unhide selects if (in_recover) { for (var cnt = 0; cnt < domLib_collisionElements.length; cnt++) { var thisElement = domLib_collisionElements[cnt]; if (!thisElement.hideList) { thisElement.hideList = new Hash(); } thisElement.hideList.remove(in_object.id); if (!thisElement.hideList.length) { domLib_collisionElements[cnt].style.visibility = 'visible'; if (domLib_isKonq) { domLib_collisionElements[cnt].style.display = ''; } } } return; } else if (domLib_collisionElements.length == 0) { return; } // okay, we have a tip, so hunt and destroy var objectOffsets = domLib_getOffsets(in_object); for (var cnt = 0; cnt < domLib_collisionElements.length; cnt++) { var thisElement = domLib_collisionElements[cnt]; // if collision element is in active element, move on // WARNING: is this too costly? if (domLib_isDescendantOf(thisElement, in_object)) { continue; } // konqueror only has trouble with multirow selects if (domLib_isKonq && thisElement.tagName == 'SELECT' && (thisElement.size <= 1 && !thisElement.multiple)) { continue; } if (!thisElement.hideList) { thisElement.hideList = new Hash(); } var selectOffsets = domLib_getOffsets(thisElement); var center2centerDistance = Math.sqrt(Math.pow(selectOffsets.get('leftCenter') - objectOffsets.get('leftCenter'), 2) + Math.pow(selectOffsets.get('topCenter') - objectOffsets.get('topCenter'), 2)); var radiusSum = selectOffsets.get('radius') + objectOffsets.get('radius'); // the encompassing circles are overlapping, get in for a closer look if (center2centerDistance < radiusSum) { // tip is left of select if ((objectOffsets.get('leftCenter') <= selectOffsets.get('leftCenter') && objectOffsets.get('right') < selectOffsets.get('left')) || // tip is right of select (objectOffsets.get('leftCenter') > selectOffsets.get('leftCenter') && objectOffsets.get('left') > selectOffsets.get('right')) || // tip is above select (objectOffsets.get('topCenter') <= selectOffsets.get('topCenter') && objectOffsets.get('bottom') < selectOffsets.get('top')) || // tip is below select (objectOffsets.get('topCenter') > selectOffsets.get('topCenter') && objectOffsets.get('top') > selectOffsets.get('bottom'))) { thisElement.hideList.remove(in_object.id); if (!thisElement.hideList.length) { thisElement.style.visibility = 'visible'; if (domLib_isKonq) { thisElement.style.display = ''; } } } else { thisElement.hideList.set(in_object.id, true); thisElement.style.visibility = 'hidden'; if (domLib_isKonq) { thisElement.style.display = 'none'; } } } } } // }}} // {{{ domLib_getOffsets() function domLib_getOffsets(in_object, in_preserveScroll) { if (typeof(in_preserveScroll) == 'undefined') { in_preserveScroll = false; } var originalObject = in_object; var originalWidth = in_object.offsetWidth; var originalHeight = in_object.offsetHeight; var offsetLeft = 0; var offsetTop = 0; while (in_object) { offsetLeft += in_object.offsetLeft; offsetTop += in_object.offsetTop; in_object = in_object.offsetParent; // consider scroll offset of parent elements if (in_object && !in_preserveScroll) { offsetLeft -= in_object.scrollLeft; offsetTop -= in_object.scrollTop; } } // MacIE misreports the offsets (even with margin: 0 in body{}), still not perfect if (domLib_isMacIE) { offsetLeft += 10; offsetTop += 10; } return new Hash( 'left', offsetLeft, 'top', offsetTop, 'right', offsetLeft + originalWidth, 'bottom', offsetTop + originalHeight, 'leftCenter', offsetLeft + originalWidth/2, 'topCenter', offsetTop + originalHeight/2, 'radius', Math.max(originalWidth, originalHeight) ); } // }}} // {{{ domLib_setTimeout() function domLib_setTimeout(in_function, in_timeout, in_args) { if (typeof(in_args) == 'undefined') { in_args = []; } if (in_timeout == -1) { // timeout event is disabled return 0; } else if (in_timeout == 0) { in_function(in_args); return 0; } // must make a copy of the arguments so that we release the reference var args = domLib_clone(in_args); if (!domLib_hasBrokenTimeout) { return setTimeout(function() { in_function(args); }, in_timeout); } else { var id = domLib_timeoutStateId++; var data = new Hash(); data.set('function', in_function); data.set('args', args); domLib_timeoutStates.set(id, data); data.set('timeoutId', setTimeout('domLib_timeoutStates.get(' + id + ').get(\'function\')(domLib_timeoutStates.get(' + id + ').get(\'args\')); domLib_timeoutStates.remove(' + id + ');', in_timeout)); return id; } } // }}} // {{{ domLib_clearTimeout() function domLib_clearTimeout(in_id) { if (!domLib_hasBrokenTimeout) { if (in_id > 0) { clearTimeout(in_id); } } else { if (domLib_timeoutStates.has(in_id)) { clearTimeout(domLib_timeoutStates.get(in_id).get('timeoutId')) domLib_timeoutStates.remove(in_id); } } } // }}} // {{{ domLib_getEventPosition() function domLib_getEventPosition(in_eventObj) { var eventPosition = new Hash('x', 0, 'y', 0, 'scrollX', 0, 'scrollY', 0); // IE varies depending on standard compliance mode if (domLib_isIE) { var doc = (domLib_standardsMode ? document.documentElement : document.body); // NOTE: events may fire before the body has been loaded if (doc) { eventPosition.set('x', in_eventObj.clientX + doc.scrollLeft); eventPosition.set('y', in_eventObj.clientY + doc.scrollTop); eventPosition.set('scrollX', doc.scrollLeft); eventPosition.set('scrollY', doc.scrollTop); } } else { eventPosition.set('x', in_eventObj.pageX); eventPosition.set('y', in_eventObj.pageY); eventPosition.set('scrollX', in_eventObj.pageX - in_eventObj.clientX); eventPosition.set('scrollY', in_eventObj.pageY - in_eventObj.clientY); } return eventPosition; } // }}} // {{{ domLib_cancelBubble() function domLib_cancelBubble(in_event) { var eventObj = in_event ? in_event : window.event; eventObj.cancelBubble = true; } // }}} // {{{ domLib_getIFrameReference() function domLib_getIFrameReference(in_frame) { if (domLib_isGecko || domLib_isIE) { return in_frame.frameElement; } else { // we could either do it this way or require an id on the frame // equivalent to the name var name = in_frame.name; if (!name || !in_frame.parent) { return null; } var candidates = in_frame.parent.document.getElementsByTagName('iframe'); for (var i = 0; i < candidates.length; i++) { if (candidates[i].name == name) { return candidates[i]; } } return null; } } // }}} // {{{ domLib_getElementsByClass() function domLib_getElementsByClass(in_class) { var elements = domLib_isIE5 ? document.all : document.getElementsByTagName('*'); var matches = []; var cnt = 0; for (var i = 0; i < elements.length; i++) { if ((" " + elements[i].className + " ").indexOf(" " + in_class + " ") != -1) { matches[cnt++] = elements[i]; } } return matches; } // }}} // {{{ domLib_getElementsByTagNames() function domLib_getElementsByTagNames(in_list, in_excludeHidden) { var elements = []; for (var i = 0; i < in_list.length; i++) { var matches = document.getElementsByTagName(in_list[i]); for (var j = 0; j < matches.length; j++) { // skip objects that have nested embeds, or else we get "flashing" if (matches[j].tagName == 'OBJECT' && domLib_isGecko) { var kids = matches[j].childNodes; var skip = false; for (var k = 0; k < kids.length; k++) { if (kids[k].tagName == 'EMBED') { skip = true; break; } } if (skip) continue; } if (in_excludeHidden && domLib_getComputedStyle(matches[j], 'visibility') == 'hidden') { continue; } elements[elements.length] = matches[j]; } } return elements; } // }}} // {{{ domLib_getComputedStyle() function domLib_getComputedStyle(in_obj, in_property) { if (domLib_isIE) { var humpBackProp = in_property.replace(/-(.)/, function (a, b) { return b.toUpperCase(); }); return eval('in_obj.currentStyle.' + humpBackProp); } // getComputedStyle() is broken in konqueror, so let's go for the style object else if (domLib_isKonq) { //var humpBackProp = in_property.replace(/-(.)/, function (a, b) { return b.toUpperCase(); }); return eval('in_obj.style.' + in_property); } else { return document.defaultView.getComputedStyle(in_obj, null).getPropertyValue(in_property); } } // }}} // {{{ makeTrue() function makeTrue() { return true; } // }}} // {{{ makeFalse() function makeFalse() { return false; } // }}}
JavaScript
//Persist searchbox status (function() { var searchbox = $('#ksearchboxmain'); var toggleSearchbox = function() { klappe_news('searchboxmain'); klappe_news('searchbox-simple', true); } $('#searchbox-header a').click(function(e) { e.preventDefault(); $.jStorage.set('hideSearchbox', (searchbox.css('display') === 'none')); toggleSearchbox(); }); if ($.jStorage.get('hideSearchbox', false)) { searchbox.show(); $('#ksearchbox-simple').hide(); document.getElementById('picsearchboxmain').className = 'minus'; } })();
JavaScript