code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
(function () {
"use strict";
var appViewState = Windows.UI.ViewManagement.ApplicationViewState;
var ui = WinJS.UI;
ui.Pages.define("/pages/groupDetail/groupDetail.html", {
/// <field type="WinJS.Binding.List" />
_items: null,
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var listView = element.querySelector(".itemslist").winControl;
var group = (options && options.groupKey) ? Data.resolveGroupReference(options.groupKey) : Data.groups.getAt(0);
this._items = Data.getItemsFromGroup(group);
var pageList = this._items.createGrouped(
function groupKeySelector(item) { return group.key; },
function groupDataSelector(item) { return group; }
);
element.querySelector("header[role=banner] .pagetitle").textContent = group.title;
listView.itemDataSource = pageList.dataSource;
listView.itemTemplate = element.querySelector(".itemtemplate");
listView.groupDataSource = pageList.groups.dataSource;
listView.groupHeaderTemplate = element.querySelector(".headertemplate");
listView.oniteminvoked = this._itemInvoked.bind(this);
this._initializeLayout(listView, Windows.UI.ViewManagement.ApplicationView.value);
listView.element.focus();
},
unload: function () {
this._items.dispose();
},
// This function updates the page layout in response to viewState changes.
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
var listView = element.querySelector(".itemslist").winControl;
if (lastViewState !== viewState) {
if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {
var handler = function (e) {
listView.removeEventListener("contentanimating", handler, false);
e.preventDefault();
}
listView.addEventListener("contentanimating", handler, false);
var firstVisible = listView.indexOfFirstVisible;
this._initializeLayout(listView, viewState);
if (firstVisible >= 0 && listView.itemDataSource.list.length > 0) {
listView.indexOfFirstVisible = firstVisible;
}
}
}
},
// This function updates the ListView with new layouts
_initializeLayout: function (listView, viewState) {
/// <param name="listView" value="WinJS.UI.ListView.prototype" />
if (viewState === appViewState.snapped) {
listView.layout = new ui.ListLayout();
} else {
listView.layout = new ui.GridLayout({ groupHeaderPosition: "left" });
}
},
_itemInvoked: function (args) {
var item = this._items.getAt(args.detail.itemIndex);
WinJS.Navigation.navigate("/pages/itemDetail/itemDetail.html", { item: Data.getItemReference(item) });
}
});
})();
| JavaScript |
// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
"use strict";
var nav = WinJS.Navigation;
WinJS.UI.Pages.define("/pages/aboutUs/aboutUs.html", {
ready: function (element, options) {
},
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
/// <param name="viewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
/// <param name="lastViewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
// TODO: Respond to changes in viewState.
},
unload: function () {
// TODO: Respond to navigations away from this page.
}
});
})(); | JavaScript |
// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
"use strict";
var nav = WinJS.Navigation;
WinJS.UI.Pages.define("/pages/settings/settings.html", {
ready: function (element, options) {
},
updateLayout: function (element, viewState, lastViewState) {
/// <param name="element" domElement="true" />
/// <param name="viewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
/// <param name="lastViewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
// TODO: Respond to changes in viewState.
},
unload: function () {
// TODO: Respond to navigations away from this page.
}
});
})(); | JavaScript |
(function(){
var _1,_2="";
if(typeof (inPipe)!="undefined"){
_1=true;
}
for(var i=0;i<16;i++){
_2+=String.fromCharCode(Math.floor(Math.random()*26)+97);
}
window[_2]={};
if(_1){
pipeListBadge=window[_2];
}
var $=window[_2];
$.f=function(){
return {runFunction:[],timeoutCount:10,inpipe:(typeof (inPipe)!="undefined")?true:false,init:function(_5){
var _6=document.getElementsByTagName("SCRIPT");
for(var i=0;i<_6.length;i++){
var _8=(this.inpipe)?_6[i].id:_6[i].src;
if(_8.match(_5)){
$.a={};
if(_6[i].innerHTML){
$.a=$.f.parseJson(_6[i].innerHTML);
}
$.w=document.createElement("DIV");
_6[i].parentNode.insertBefore($.w,_6[i]);
_6[i].parentNode.removeChild(_6[i]);
$.f.buildStructure();
break;
}
}
},parseJson:function(_9){
this.parseJson.data=_9;
if(typeof _9!=="string"){
return {"err":"trying to parse a non-string JSON object"};
}
try{
var f=Function(["var document,top,self,window,parent,Number,Date,Object,Function,","Array,String,Math,RegExp,Image,ActiveXObject;","return (",_9.replace(/<\!--.+-->/gim,"").replace(/\bfunction\b/g,"function­"),");"].join(""));
return f();
}
catch(e){
return {"err":"trouble parsing JSON object"};
}
},buildStructure:function(){
$.d={"title":" ","height":"300px","width":"100%","border":"none","margin":"0","padding":"0","containerPadding":"0","evenBackgroundColor":"transparent","oddBackgroundColor":"transparent","pipesTitleFontSize":"inherit","pipesDescriptionFontSize":"12px","count":25};
var _b="";
if(this.inpipe){
$.d.width="100%";
$.d.height="100%";
$.a.count=25;
$.a.hideHeader="true";
}else{
_b="overflow:auto;overflow-x:hidden;";
var _c=document.getElementById("YUIcontainer");
if(_c==null){
$.f.createSSLink("http://yui.yahooapis.com/2.4.1/build/container/assets/container.css","YUIcontainer");
}
}
for(var k in $.d){
if($.a[k]===undefined){
$.a[k]=$.d[k];
}
}
$.w.className=_2;
if($.a.addClassName!==undefined){
try{
$.w.className+=" "+$.a.addClassName;
}
catch(eClassName){
}
}
if($.a.id!==undefined){
try{
$.w.id=$.a.id;
}
catch(eId){
}
}
if($.a.width!==undefined){
try{
if($.a.width.indexOf("px")==-1&&$.a.width.indexOf("%")==-1&&$.a.width.indexOf("em")==-1){
$.a.width=$.a.width+"px";
}
$.w.style.width=$.a.width;
}
catch(eWidth){
}
}
if($.a.height!==undefined){
try{
if($.a.height.indexOf("px")==-1&&$.a.height.indexOf("%")==-1&&$.a.height.indexOf("em")==-1){
$.a.height=$.a.height+"px";
}
}
catch(eHeight){
}
}
var ns=document.createElement("style");
document.getElementsByTagName("head")[0].appendChild(ns);
if(!window.createPopup){
ns.appendChild(document.createTextNode(""));
}
var s=document.styleSheets[document.styleSheets.length-1];
var _10={"":"{zoom:1;position:"+$.a.position+";top:"+$.a.top+";left:"+$.a.left+";width:"+$.a.width+";height:"+$.a.height+";background-color:"+$.a.backgroundColor+";border:"+$.a.border+";font:"+$.a.font+";margin:"+$.a.margin+";padding:"+$.a.padding+";}","a":"{cursor:pointer;text-decoration:none;color:"+$.a.color+";}","a.yba":"{background:transparent url(http://3.bp.blogspot.com/-wsIqUGbMUyk/TchLsqCK3QI/AAAAAAAACmU/udeV22bGZ78/s400/blgo.png) 0 0 no-repeat;_background-image:url(http://l.yimg.com/a/i/us/pps/pipes-16.gif);float:left;height:16px;margin:5px 0 0 0px;width:16px;}","div.ybad":"{display:inline;height:16px;font-size:9px;font-weight:bold;line-height:22px;color:inherit;}","a.gt":"{position:absolute;height:16px;display:none;color:inherit;font-size:9px;font-weight:bold;line-height:22px;right:12px;cursor:pointer;text-decoration:underline;}","div.gts":"{position:absolute;height:16px;display:none;color:inherit;font-size:12px;font-weight:bold;line-height:20px;right:2px;cursor:none;text-decoration:none;}","a.ybaa":"{color:inherit;text-decoration:underline}","sup.ybas":"{font-size:100%;color:inherit}","a.ybt":"{font-weight:bold;color:"+$.a.headlineColor+";}","div.ybx":"{visibility:hidden;background-color:transparent;margin:"+$.a.containerPadding+";padding:0;position:relative;}","div.ybr":"{zoom:1;position:relative;display:block;font-size:1em;margin:3px 0 0 0;padding:0pt;width:100%;"+_b+"}","div.ybf":"{display:none;width:100%;background-color:transparent;height:20px;margin:0;padding:0;position:relative}","div.ybr li.ybi":"{background-color:"+$.a.evenBackgroundColor+";margin:0;padding:5px 5px 5px 0;list-style:none;list-style-position:outside;overflow:hidden;text-indent:0}","div.ybr li.ybi.odd":"{background-color:"+$.a.oddBackgroundColor+";}","h3.ybh":"{margin:0;padding:0;font-weight:bold;background-color:"+$.a.headerBackgroundColor+";}","h3.ybt":"{margin:0;padding:0;position:relative;}","div.PBajaxwait":"{position:relative;display:block;width:100%;height:100%;margin-top:-"+$.a.containerPadding+";background: #eee url('http://l.yimg.com/a/i/us/pps/logo_ani_1.gif') 50% 50% no-repeat;opacity:0.75;filter:alpha(opacity=75);}",".pipesImgdescription":"{display:block;width:100%;height:auto;color:"+$.a.descriptionColor+";}",".pipesImgdescription .pipesThumbnail":"{position:relative;float:left;background: url(http://4.bp.blogspot.com/-LOOjBWkPDOU/TcgzCKbFr1I/AAAAAAAACmE/RkFjOZVgkoU/s400/blogger.gif) no-repeat top center;border: 0px;height:72px;width:72px;overflow:hidden;margin: 0px 8px 0px 0px;}",".pipesImgdescription .pipesThumbnail img":"{position:static;width:82px;min-height:72px;border:0px solid #eee}",".pipesImgdescription .pipesTitle":"{font-size:"+$.a.pipesTitleFontSize+";font-weight:bold;padding-bottom:3px;width:100%;}",".pipesImgdescription .pipesDescription":"{font-size:"+$.a.pipesDescriptionFontSize+";}",".pipesHolder":"{padding:0px; margin:10px 0px 0px 0px;}",".pipesText":"{zoom:1;margin-left: 55px;}","ul":"{display:block;overflow:hidden;position:relative;width:300000px;z-index:2;padding:0;margin:auto;}","ul.pipesSmallthumb li":"{border:1px solid #eee;display:none;float:left;height:32px;list-style-image:none;list-style-position:outside;list-style-type:none;overflow:hidden;padding:2px;width:32px;}","ul.pipesSmallthumb li:hover":"{border:1px solid red;}","ul.pipesSmallthumb":"{margin: 10px 0 0;padding:0;width:auto;}","ul.pipesSmallthumb li a img":"{height:32px;width:32px;cursor:pointer;border: 0px;position:static;left:inherit;right:inherit;}",".ybf":"{display:none!important;}"};
var _11={"gin div.hd":"{background-color:#eee;border:none}"};
var _12="";
for(var r in _10){
var _14="."+_2+" "+r;
if(window.createPopup){
_12+=_14+_10[r];
}else{
var _15=document.createTextNode(_14+_10[r]);
ns.appendChild(_15);
}
}
for(var r in _11){
var _14="#"+_2+r;
if(window.createPopup){
_12+=_14+_11[r];
}else{
var _15=document.createTextNode(_14+_11[r]);
ns.appendChild(_15);
}
}
if(window.createPopup){
s.cssText=_12;
}
$.w.ajaxwait=document.createElement("DIV");
$.w.ajaxwait.className="PBajaxwait";
$.w.c=document.createElement("DIV");
$.w.c.className="ybx";
$.w.h=document.createElement("h3");
$.w.h.className="ybh";
if($.a.hideHeader!==undefined){
try{
$.w.h.style.display="none";
}
catch(eHideHeader){
}
}
$.w.t=document.createElement("A");
$.w.t.className="ybt";
$.w.t.innerHTML=$.a.title;
$.w.t.target="_blank";
$.w.h.appendChild($.w.t);
$.w.c.appendChild($.w.h);
$.w.r=document.createElement("DIV");
$.w.r.className="ybr";
$.w.c.appendChild($.w.r);
$.w.dtf=document.createElement("div");
$.w.dtf.className="ybf";
$.w.dtf.innerHTML="<a href=\"http://helplogger.blogspot.com\" class=\"yba\"></a> <div class=\"ybad\">Powered by <a class=\"ybaa\" href=\"http://helplogger.blogspot.com\">Helplogger</a><sup class=\"ybas\">e</sup></div><a class=\"gt\">Get This</a><div class=\"gts\">»</div>";
var _16=$.w.dtf.getElementsByTagName("a");
this.getThisDiv=_16[2];
var _17=$.w.dtf.getElementsByTagName("div");
this.getThisDivArrow=_17[1];
$.w.ajaxwait.appendChild($.w.c);
$.w.ajaxwait.appendChild($.w.dtf);
$.w.appendChild($.w.ajaxwait);
if(!this.inpipe){
if($.a.localJson===undefined){
$.f.runSearch();
}else{
$.f.renderResult($.a.localJson);
}
}
},runCalledFromPipe:function(){
$.f.renderResult(jsondata);
},runSearch:function(){
$.f.callback="pipesCallback";
pipesCallback=function(r){
if(pipesCallBackArr[r.value.requesturl]){
for(var e=0;e<pipesCallBackArr[r.value.requesturl].length;e++){
if(pipesCallBackArr[r.value.requesturl][e]){
pipesCallBackArr[r.value.requesturl][e].f.renderResult(r);
pipesCallBackArr[r.value.requesturl][e]=null;
}
}
}
};
var _1a="http://pipes.yahoo.com/pipes/pipe.info?_id="+$.a.pipe_id;
var url="http://run.pipes.yahoo.com/pipes/pipe.run?_id="+$.a.pipe_id+"&_render=badge&_callback="+$.f.callback;
this.queryparams="";
for(var key in $.a.pipe_params){
if($.a.pipe_params[key]===null){
continue;
}
url+="&"+encodeURIComponent(key)+"="+encodeURIComponent($.a.pipe_params[key]);
this.queryparams+="&"+decodeURIComponent(key)+"="+decodeURIComponent($.a.pipe_params[key]);
}
$.w.t.href=_1a;
if(typeof (pipesCallBackArr)=="undefined"){
pipesCallBackArr=[];
}
if(typeof (pipesCallBackArr[url])=="undefined"){
pipesCallBackArr[url]=[];
}
pipesCallBackArr[url].push($);
if(typeof (YAHOO)=="undefined"||!YAHOO||typeof (YAHOO.util)=="undefined"||!YAHOO.util){
var _1d=document.getElementById("yui");
if(_1d==null){
$.f.runScript("http://yui.yahooapis.com/2.3.1/build/utilities/utilities.js","yui");
}
}
$.f.runScript(url,_2);
},renderResult:function(r){
if(r.value.published==""){
var t=$.w.h.cloneNode(true);
t.innerHTML=r.value.title;
$.w.h.parentNode.replaceChild(t,$.w.h);
$.w.h=t;
this.getThisDiv.style.display="none";
this.getThisDivArrow.style.display="none";
}else{
var t=$.w.t.cloneNode(true);
t.innerHTML=r.value.title;
$.w.t.parentNode.replaceChild(t,$.w.t);
$.w.t=t;
}
this.listbadge.init(r);
},runScript:function(url,id){
var s=document.createElement("script");
s.id=id;
s.type="text/javascript";
s.src=url;
document.getElementsByTagName("head")[0].appendChild(s);
},createSSLink:function(url,id){
var l=document.createElement("link");
l.id=id;
l.rel="stylesheet";
l.type="text/css";
l.href=url;
document.getElementsByTagName("head")[0].appendChild(l);
},removeScript:function(id){
if(document.getElementById(id)){
var s=document.getElementById(id);
s.parentNode.removeChild(s);
}
},getthisfuncInside:function(){
YAHOO.util.Dom.addClass(document.body,"yui-skin-sam");
var _28=(_1)?pid:$.a.pipe_id;
var _29=(_1)?"":$.f.queryparams;
if(this.getitnow==undefined){
this.getitnow=new YAHOO.widget.Panel(_2+"gin",{width:"420px",fixedcenter:true,constraintoviewport:true,underlay:"none",close:true,visible:false,draggable:true,modal:true,iframe:true,zIndex:"11111"});
this.getitnow.setHeader("<div style=\"border:none;font:bold 16px arial;color:#626262;text-align:left;padding-left:5px\">Get this Yahoo! Pipes<sup>™</sup> Badge <div style=\"position:absolute;right:35px;letter-spacing:4px;top:3px;\"><a style=\"font-size:11px;color:#626262;\" href=\"http://pipes.yahoo.com/pipes/badgedocs\" target=\"_blank\">HELP</a></div></div>");
this.getitnow.setBody("<iframe width=\"415\" height=\"350\" allowtransparency=\"true\" marginwidth=\"0\" marginheight=\"0\" hspace=\"0\" vspace=\"0\" frameborder=\"0\" scrolling=\"no\" src=\"http://pipes.yahoo.com/pipes/badge.config?page=1&_btype=list&_id="+_28+_29+"\"></iframe>");
this.getitnow.render(document.body);
YAHOO.util.Event.addListener(_2+"ginClose","click",this.getitnow.hide,this.getitnow,true);
}
this.getitnow.show();
},getthisfuncOutside:function(){
var _2a=(_1)?pid:$.a.pipe_id;
var _2b=(_1)?"":$.f.queryparams;
var url="http://pipes.yahoo.com/pipes/badge.config?page=1&_btype=list&_id="+_2a+_2b;
window.open(url);
},listbadge:{init:function(r){
if(typeof (YAHOO)=="undefined"){
$.f.timeoutCount--;
if($.f.timeoutCount==0){
}else{
window.setTimeout(function(){
$.f.listbadge.init(r);
},1000);
}
return;
}
YAHOO.util.Dom.removeClass($.w.ajaxwait,"PBajaxwait");
if(!$.f.inpipe){
var _2e=document.getElementById("YUICscript");
if(_2e==null){
$.f.runScript("http://yui.yahooapis.com/2.4.1/build/container/container-min.js","YUICscript");
}
$.w.dtf.style.display="block";
if(r.value.published!=""){
this.checkViewport();
}
}
YAHOO.util.Event.addListener(window,"resize",this.resized,this,true);
var w=$.w.r.offsetWidth;
if(!$.f.inpipe){
var _30=(parseInt($.a.containerPadding,10)*2);
var h=$.w.offsetHeight-$.w.h.offsetHeight-$.w.dtf.offsetHeight-_30-5;
if(h>0){
$.w.r.style.height=h+"px";
}
}
this.w=w;
this.remove();
if(r&&r.value&&r.value.items&&r.value.items.length){
this.startnum=0;
this.orglen=r.value.items.length;
this.countby=$.a.count;
this.results=r;
var _32=(this.orglen<this.countby)?this.orglen:this.countby;
this.create(this.startnum,_32);
this.startnum=this.countby;
}else{
var t=$.w.r.cloneNode(true);
t.innerHTML="<h4>No results</h4>";
$.w.r.parentNode.replaceChild(t,$.w.r);
$.w.r=t;
}
YAHOO.util.Dom.setStyle($.w.c,"visibility","visible");
},checkViewport:function(){
YAHOO.util.Event.removeListener($.f.getThisDiv,"click");
if(YAHOO.util.Dom.getViewportWidth()>=422&&YAHOO.util.Dom.getViewportHeight()>=415){
YAHOO.util.Event.addListener($.f.getThisDiv,"click",$.f.getthisfuncInside,this,true);
}else{
YAHOO.util.Event.addListener($.f.getThisDiv,"click",$.f.getthisfuncOutside,this,true);
}
},resized:function(){
if(this.currheight!=document.documentElement.clientHeight&&this.currheight!=""){
this.checkViewport();
}
this.currheight=document.documentElement.clientHeight;
},createDescription:function(_34,_35){
var _36=(_34.smallimg==undefined)?"":"<img src='"+_34.smallimg+"' />";
var _37=(_35=="imgBadge")?"":"<div class='pipesThumbnail'>"+_36+"</div>";
var _38=(_36==""||_35=="imgBadge")?"style='margin-left:0px;'":"style='margin-left:55px;'";
var _39="<div class='pipesImgdescription'><div class='pipesHolder'>"+_37+"<div class='pipesText' "+_38+"><div class='pipesTitle'><a href='"+_34.link+"' target='_self'>"+_34.title+"</a></div><div class='pipesDescription'>"+_34.description+"</div><ul class='pipesSmallthumb'></ul></div></div></div>";
return _39;
},createDescThumbs:function(obj,w,_3c){
var _3d=obj.getElementsByTagName("ul");
this.smallthumbholder=_3d[0];
var ww=w-55;
this.smallitemimgcount=Math.round(ww/50);
var _3f="";
var _40=(this.smallitemimgcount>_3c.usethisimgarr.length)?_3c.usethisimgarr.length:this.smallitemimgcount;
for(var x=1;x<_40;x++){
_3f+="<li><a href="+_3c.usethisimgarr[x].url+" target='_blank'><img src='"+_3c.usethisimgarr[x].url+"'</a></li>";
}
if(_3f==""){
this.smallthumbholder.style.marginTop="0px";
}else{
var t=this.smallthumbholder.cloneNode(true);
t.innerHTML=_3f;
this.smallthumbholder.parentNode.replaceChild(t,this.smallthumbholder);
this.smallthumbholder=t;
var _43=this.smallthumbholder.getElementsByTagName("img");
this.thumbnails=_43;
for(i=0;i<_43.length;i++){
new this.makeGrow(_43[i]);
}
}
},makeGrow:function(img){
var _45=null;
var _46=img;
var _47,w,h;
var _4a=function(obj){
_47=YAHOO.util.Dom.getXY(_46);
w=parseInt(YAHOO.util.Dom.getStyle(_46,"width"));
h=parseInt(YAHOO.util.Dom.getStyle(_46,"height"));
_45=obj.cloneNode(false);
_45.style.position="absolute";
_45.style.width="32px";
_45.style.height="32px";
_45.style.top=_47[1]+"px";
_45.style.left=_47[0]+"px";
_45.style.zIndex="999";
_45.style.display="none";
_45.style.padding="2px";
_45.style.border="1px solid #eee";
_45.className="clonedSmallImg";
YAHOO.util.Event.addListener(_45,"mouseout");
document.body.appendChild(_45);
_4c();
};
var _4c=function(e){
if(_45==null){
_4a(_46);
return;
}
_45.style.display="inline";
var _4e=new YAHOO.util.Anim(_45,{width:{to:200},height:{to:200}},0.6,YAHOO.util.Easing.backOut);
var _4f=_4e.getEl();
_4e.onTween.subscribe(function(){
var nx=_47[0]-((_4f.offsetWidth-w)>>1);
var ny=_47[1]-((_4f.offsetHeight-h)>>1);
if(nx<0){
nx=0;
}
if(ny<0){
ny=0;
}
YAHOO.util.Dom.setXY(_4f,[nx,ny]);
});
_4e.animate();
$.f.listbadge.growAnim=_4e;
YAHOO.util.Event.addListener(_45,"mouseout",_52);
};
var _52=function(){
if($.f.listbadge.growAnim.isAnimated()==true){
window.setTimeout(function(){
_52();
},50);
return;
}
YAHOO.util.Event.removeListener(_45,"mouseout");
var _53=new YAHOO.util.Anim(_45,{width:{to:32},height:{to:32}},0.2);
var _54=_53.getEl();
_53.onTween.subscribe(function(){
var nx=_47[0]-((_54.offsetWidth-w)>>1);
var ny=_47[1]-((_54.offsetHeight-h)>>1);
if(nx<0){
nx=0;
}
if(ny<0){
ny=0;
}
YAHOO.util.Dom.setXY(_54,[nx,ny]);
});
_53.onComplete.subscribe(function(){
var _57=_53.getEl();
_57.style.display="none";
});
_53.animate();
};
YAHOO.util.Event.addListener(_46,"mouseover",_4c);
},remove:function(){
$.w.r.innerHTML="";
},create:function(_58,_59){
for(var i=_58;i<_59;i++){
var _5b=this.results.value.items[i];
var _5c=_5b.media.regular.length;
var _5d=_5b.media.thumbnails.length;
var _5e=(_5c>_5d)?_5b.media.regular:_5b.media.thumbnails;
_5b.usethisimgarr=_5e;
if(_5e.length!=0){
if(_5b.media.thumbnails.length!=0){
_5b.smallimg=_5b.media.thumbnails[0].url;
}else{
_5b.smallimg=_5e[0].url;
}
}
var li=document.createElement("LI");
this.li=li;
li.className="ybi";
if(i%2){
li.className+=" odd";
}
li.innerHTML=this.createDescription(_5b);
this.createDescThumbs(this.li,this.w,_5b);
var _60=li.getElementsByTagName("div")[2];
var _61=li.getElementsByTagName("div")[3];
var _62=li.getElementsByTagName("div")[4];
var _63=li.getElementsByTagName("div")[5];
if(_60.innerHTML!=""){
YAHOO.util.Dom.setStyle(_60,"margin-right","8px");
}
YAHOO.util.Dom.setStyle(_61,"margin-left","0px");
$.w.r.appendChild(li);
}
if($.f.inpipe){
if(this.orglen>_59||_58!=0){
this.pagDiv=document.createElement("div");
this.pagDiv.className="paginate";
}
if(this.orglen>_59){
var _64=document.createElement("a");
_64.innerHTML="Next >";
YAHOO.util.Event.addListener(_64,"click",this.next_pag,this,true);
this.pagDiv.appendChild(_64);
}
if(_58!=0){
var _65=document.createElement("a");
_65.innerHTML="< Prev";
if(this.orglen>_59){
_65.style.right="40px";
_65.style.position="absolute";
}else{
_65.style.right="";
_65.style.position="";
}
YAHOO.util.Event.addListener(_65,"click",this.prev_pag,this,true);
this.pagDiv.appendChild(_65);
}
if(this.orglen>_59||_58!=0){
$.w.r.appendChild(this.pagDiv);
this.pagDiv=null;
}
}
},prev_pag:function(){
this.remove();
var _66=this.startorg-this.countby;
var _67=_66+this.countby;
if(_67>=this.orglen){
_67=this.orglen;
}
this.create(_66,_67);
location.href="#";
this.startnum=_67;
this.startorg=_66;
},next_pag:function(){
this.remove();
var _68=this.startnum;
var _69=this.countby+_68;
if(_69>=this.orglen){
_69=this.orglen;
}
this.create(_68,_69);
location.href="#";
this.startnum=_69;
this.startorg=_68;
}}};
}();
var _6a=/listbadge.js$/;
var _6b=function(){
$.f.init(_6a);
};
if(_1){
_6b();
}else{
if(typeof window.addEventListener!=="undefined"){
if(window.opera){
_6b();
}else{
window.addEventListener("load",_6b,false);
}
}else{
if(typeof window.attachEvent!=="undefined"){
window.attachEvent("onload",_6b);
}
}
}
})(); | JavaScript |
// ----------------------------------------
// SHOW RECENT POSTS
// ----------------------------------------
// Mod by MyDigitalLemon
// Original by blogsolute.com
// ----------------------------------------
function showrecentposts(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}
}
posttitle = posttitle.link(posturl);
var readmorelink = "....";
readmorelink = readmorelink.link(posturl);
var postdate = entry.published.$t;
var cdyear = postdate.substring(0,4);
var cdmonth = postdate.substring(5,7);
var cdday = postdate.substring(8,10);
var monthnames = new Array();
monthnames[1] = "Jan";
monthnames[2] = "Feb";
monthnames[3] = "Mar";
monthnames[4] = "Apr";
monthnames[5] = "May";
monthnames[6] = "Jun";
monthnames[7] = "Jul";
monthnames[8] = "Aug";
monthnames[9] = "Sep";
monthnames[10] = "Oct";
monthnames[11] = "Nov";
monthnames[12] = "Dec";
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
var re = /<\S[^>]*>/g;
postcontent = postcontent.replace(re, "");
document.write('<div class="mtrpw">');
if (standardstyling) document.write('<br/>');
document.write(posttitle);
if (showpostdate == true) document.write(' - ' + monthnames[parseInt(cdmonth,10)] + ' ' + cdday + ' ' + cdyear);
document.write('</div><div class="mtrpwsumm">');
if (showpostsummary == true) {
if (standardstyling) document.write('');
if (postcontent.length < numchars) {
if (standardstyling) document.write('<i>');
document.write(postcontent);
if (standardstyling) document.write('</i>');}
else {
if (standardstyling) document.write('');
postcontent = postcontent.substring(0, numchars);
var quoteEnd = postcontent.lastIndexOf(" ");
postcontent = postcontent.substring(0,quoteEnd);
document.write(postcontent + ' ' + readmorelink);
if (standardstyling) document.write('');}
}
document.write('</div>');
if (standardstyling) document.write('');
}
if (!standardstyling) document.write('<div class="bbwidgetfooter">');
if (standardstyling) document.write('');
document.write('');
if (!standardstyling) document.write('');
} | JavaScript |
function showrecentpostswiththumbs(json) {document.write('<ul class="recent_posts_with_thumbs">'); for (var i = 0; i < numposts; i++) {var entry = json.feed.entry[i];var posttitle = entry.title.$t;var posturl;if (i == json.feed.entry.length) break;for (var k = 0; k < entry.link.length;k++){
if(entry.link[k].rel=='replies'&&entry.link[k].type=='text/html'){var commenttext=entry.link[k].title;var commenturl=entry.link[k].href;}
if (entry.link[k].rel == 'alternate') {posturl = entry.link[k].href;break;}}var thumburl;try {thumburl=entry.media$thumbnail.url;}catch (error)
{
s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5);if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")){
thumburl=d;} else thumburl='http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/s400/noimage.png';
}
var postdate = entry.published.$t;var cdyear = postdate.substring(0,4);var cdmonth = postdate.substring(5,7);var cdday = postdate.substring(8,10);var monthnames = new Array();monthnames[1] = "Jan";monthnames[2] = "Feb";monthnames[3] = "Mar";monthnames[4] = "Apr";monthnames[5] = "May";monthnames[6] = "Jun";monthnames[7] = "Jul";monthnames[8] = "Aug";monthnames[9] = "Sep";monthnames[10] = "Oct";monthnames[11] = "Nov";monthnames[12] = "Dec";document.write('<li class="clearfix">');
if(showpostthumbnails==true)
document.write('<img class="recent_thumb" src="'+thumburl+'"/>');
document.write('<b><a href="'+posturl+'" target ="_top">'+posttitle+'</a></b><br>');
if ("content" in entry) {
var postcontent = entry.content.$t;}
else
if ("summary" in entry) {
var postcontent = entry.summary.$t;}
else var postcontent = "";
var re = /<\S[^>]*>/g;
postcontent = postcontent.replace(re, "");
if (showpostsummary == true) {
if (postcontent.length < numchars) {
document.write('<i>');
document.write(postcontent);
document.write('</i>');}
else {
document.write('<i>');
postcontent = postcontent.substring(0, numchars);
var quoteEnd = postcontent.lastIndexOf(" ");
postcontent = postcontent.substring(0,quoteEnd);
document.write(postcontent + '...');
document.write('</i>');}
}
var towrite='';var flag=0;
document.write('<br><strong>');
if(showpostdate==true) {towrite=towrite+monthnames[parseInt(cdmonth,10)]+'-'+cdday+' - '+cdyear;flag=1;}
if(showcommentnum==true)
{
if (flag==1) {towrite=towrite+' | ';}
if(commenttext=='1 Comments') commenttext='1 Comment';
if(commenttext=='0 Comments') commenttext='No Comments';
commenttext = '<a href="'+commenturl+'" target ="_top">'+commenttext+'</a>';
towrite=towrite+commenttext;
flag=1;
;
}
if(displaymore==true)
{
if (flag==1) towrite=towrite+' | ';
towrite=towrite+'<a href="'+posturl+'" class="url" target ="_top">More -></a>';
flag=1;
;
}
document.write(towrite);
document.write('</strong></li>');
if(displayseparator==true)
if (i!=(numposts-1))
document.write('<hr size=0.5>');
}document.write('</ul>');
} | JavaScript |
(function(){
var _1,_2="";
if(typeof (inPipe)!="undefined"){
_1=true;
}
for(var i=0;i<16;i++){
_2+=String.fromCharCode(Math.floor(Math.random()*26)+97);
}
window[_2]={};
if(_1){
pipeListBadge=window[_2];
}
var $=window[_2];
$.f=function(){
return {runFunction:[],timeoutCount:10,inpipe:(typeof (inPipe)!="undefined")?true:false,init:function(_5){
var _6=document.getElementsByTagName("SCRIPT");
for(var i=0;i<_6.length;i++){
var _8=(this.inpipe)?_6[i].id:_6[i].src;
if(_8.match(_5)){
$.a={};
if(_6[i].innerHTML){
$.a=$.f.parseJson(_6[i].innerHTML);
}
$.w=document.createElement("DIV");
_6[i].parentNode.insertBefore($.w,_6[i]);
_6[i].parentNode.removeChild(_6[i]);
$.f.buildStructure();
break;
}
}
},parseJson:function(_9){
this.parseJson.data=_9;
if(typeof _9!=="string"){
return {"err":"trying to parse a non-string JSON object"};
}
try{
var f=Function(["var document,top,self,window,parent,Number,Date,Object,Function,","Array,String,Math,RegExp,Image,ActiveXObject;","return (",_9.replace(/<\!--.+-->/gim,"").replace(/\bfunction\b/g,"function­"),");"].join(""));
return f();
}
catch(e){
return {"err":"trouble parsing JSON object"};
}
},buildStructure:function(){
$.d={"title":" ","height":"300px","width":"100%","border":"none","margin":"0","padding":"0","containerPadding":"0","evenBackgroundColor":"transparent","oddBackgroundColor":"transparent","pipesTitleFontSize":"inherit","pipesDescriptionFontSize":"12px","count":25};
var _b="";
if(this.inpipe){
$.d.width="100%";
$.d.height="100%";
$.a.count=25;
$.a.hideHeader="true";
}else{
_b="overflow:auto;overflow-x:hidden;";
var _c=document.getElementById("YUIcontainer");
if(_c==null){
$.f.createSSLink("http://yui.yahooapis.com/2.4.1/build/container/assets/container.css","YUIcontainer");
}
}
for(var k in $.d){
if($.a[k]===undefined){
$.a[k]=$.d[k];
}
}
$.w.className=_2;
if($.a.addClassName!==undefined){
try{
$.w.className+=" "+$.a.addClassName;
}
catch(eClassName){
}
}
if($.a.id!==undefined){
try{
$.w.id=$.a.id;
}
catch(eId){
}
}
if($.a.width!==undefined){
try{
if($.a.width.indexOf("px")==-1&&$.a.width.indexOf("%")==-1&&$.a.width.indexOf("em")==-1){
$.a.width=$.a.width+"px";
}
$.w.style.width=$.a.width;
}
catch(eWidth){
}
}
if($.a.height!==undefined){
try{
if($.a.height.indexOf("px")==-1&&$.a.height.indexOf("%")==-1&&$.a.height.indexOf("em")==-1){
$.a.height=$.a.height+"px";
}
}
catch(eHeight){
}
}
var ns=document.createElement("style");
document.getElementsByTagName("head")[0].appendChild(ns);
if(!window.createPopup){
ns.appendChild(document.createTextNode(""));
}
var s=document.styleSheets[document.styleSheets.length-1];
var _10={"":"{zoom:1;position:"+$.a.position+";top:"+$.a.top+";left:"+$.a.left+";width:"+$.a.width+";height:"+$.a.height+";background-color:"+$.a.backgroundColor+";border:"+$.a.border+";font:"+$.a.font+";margin:"+$.a.margin+";padding:"+$.a.padding+";}","a":"{cursor:pointer;text-decoration:none;color:"+$.a.color+";}","a.yba":"{background:transparent url(http://3.bp.blogspot.com/-wsIqUGbMUyk/TchLsqCK3QI/AAAAAAAACmU/udeV22bGZ78/s400/blgo.png) 0 0 no-repeat;_background-image:url(http://l.yimg.com/a/i/us/pps/pipes-16.gif);float:left;height:16px;margin:5px 0 0 0px;width:16px;}","div.ybad":"{display:inline;height:16px;font-size:9px;font-weight:bold;line-height:22px;color:inherit;}","a.gt":"{position:absolute;height:16px;display:none;color:inherit;font-size:9px;font-weight:bold;line-height:22px;right:12px;cursor:pointer;text-decoration:underline;}","div.gts":"{position:absolute;height:16px;display:none;color:inherit;font-size:12px;font-weight:bold;line-height:20px;right:2px;cursor:none;text-decoration:none;}","a.ybaa":"{color:inherit;text-decoration:underline}","sup.ybas":"{font-size:100%;color:inherit}","a.ybt":"{font-weight:bold;color:"+$.a.headlineColor+";}","div.ybx":"{visibility:hidden;background-color:transparent;margin:"+$.a.containerPadding+";padding:0;position:relative;}","div.ybr":"{zoom:1;position:relative;display:block;font-size:1em;margin:3px 0 0 0;padding:0pt;width:100%;"+_b+"}","div.ybf":"{display:none;width:100%;background-color:transparent;height:20px;margin:0;padding:0;position:relative}","div.ybr li.ybi":"{background-color:"+$.a.evenBackgroundColor+";margin:0;padding:5px 5px 5px 0;list-style:none;list-style-position:outside;overflow:hidden;text-indent:0}","div.ybr li.ybi.odd":"{background-color:"+$.a.oddBackgroundColor+";}","h3.ybh":"{margin:0;padding:0;font-weight:bold;background-color:"+$.a.headerBackgroundColor+";}","h3.ybt":"{margin:0;padding:0;position:relative;}","div.PBajaxwait":"{position:relative;display:block;width:100%;height:100%;margin-top:-"+$.a.containerPadding+";background: #eee url('http://l.yimg.com/a/i/us/pps/logo_ani_1.gif') 50% 50% no-repeat;opacity:0.75;filter:alpha(opacity=75);}",".pipesImgdescription":"{display:block;width:100%;height:auto;color:"+$.a.descriptionColor+";}",".pipesImgdescription .pipesThumbnail":"{position:relative;float:left;background: url(http://4.bp.blogspot.com/-LOOjBWkPDOU/TcgzCKbFr1I/AAAAAAAACmE/RkFjOZVgkoU/s400/blogger.gif) no-repeat top center;border: 0px;height:72px;width:72px;overflow:hidden;margin: 0px 8px 0px 0px;}",".pipesImgdescription .pipesThumbnail img":"{position:static;width:82px;min-height:72px;border:0px solid #eee}",".pipesImgdescription .pipesTitle":"{font-size:"+$.a.pipesTitleFontSize+";font-weight:bold;padding-bottom:3px;width:100%;}",".pipesImgdescription .pipesDescription":"{font-size:"+$.a.pipesDescriptionFontSize+";}",".pipesHolder":"{padding:0px; margin:10px 0px 0px 0px;}",".pipesText":"{zoom:1;margin-left: 55px;}","ul":"{display:block;overflow:hidden;position:relative;width:300000px;z-index:2;padding:0;margin:auto;}","ul.pipesSmallthumb li":"{border:1px solid #eee;display:none;float:left;height:32px;list-style-image:none;list-style-position:outside;list-style-type:none;overflow:hidden;padding:2px;width:32px;}","ul.pipesSmallthumb li:hover":"{border:1px solid red;}","ul.pipesSmallthumb":"{margin: 10px 0 0;padding:0;width:auto;}","ul.pipesSmallthumb li a img":"{height:32px;width:32px;cursor:pointer;border: 0px;position:static;left:inherit;right:inherit;}",".ybf":"{display:none!important;}"};
var _11={"gin div.hd":"{background-color:#eee;border:none}"};
var _12="";
for(var r in _10){
var _14="."+_2+" "+r;
if(window.createPopup){
_12+=_14+_10[r];
}else{
var _15=document.createTextNode(_14+_10[r]);
ns.appendChild(_15);
}
}
for(var r in _11){
var _14="#"+_2+r;
if(window.createPopup){
_12+=_14+_11[r];
}else{
var _15=document.createTextNode(_14+_11[r]);
ns.appendChild(_15);
}
}
if(window.createPopup){
s.cssText=_12;
}
$.w.ajaxwait=document.createElement("DIV");
$.w.ajaxwait.className="PBajaxwait";
$.w.c=document.createElement("DIV");
$.w.c.className="ybx";
$.w.h=document.createElement("h3");
$.w.h.className="ybh";
if($.a.hideHeader!==undefined){
try{
$.w.h.style.display="none";
}
catch(eHideHeader){
}
}
$.w.t=document.createElement("A");
$.w.t.className="ybt";
$.w.t.innerHTML=$.a.title;
$.w.t.target="_blank";
$.w.h.appendChild($.w.t);
$.w.c.appendChild($.w.h);
$.w.r=document.createElement("DIV");
$.w.r.className="ybr";
$.w.c.appendChild($.w.r);
$.w.dtf=document.createElement("div");
$.w.dtf.className="ybf";
$.w.dtf.innerHTML="<a href=\"http://helplogger.blogspot.com\" class=\"yba\"></a> <div class=\"ybad\">Powered by <a class=\"ybaa\" href=\"http://helplogger.blogspot.com\">Helplogger</a><sup class=\"ybas\">e</sup></div><a class=\"gt\">Get This</a><div class=\"gts\">»</div>";
var _16=$.w.dtf.getElementsByTagName("a");
this.getThisDiv=_16[2];
var _17=$.w.dtf.getElementsByTagName("div");
this.getThisDivArrow=_17[1];
$.w.ajaxwait.appendChild($.w.c);
$.w.ajaxwait.appendChild($.w.dtf);
$.w.appendChild($.w.ajaxwait);
if(!this.inpipe){
if($.a.localJson===undefined){
$.f.runSearch();
}else{
$.f.renderResult($.a.localJson);
}
}
},runCalledFromPipe:function(){
$.f.renderResult(jsondata);
},runSearch:function(){
$.f.callback="pipesCallback";
pipesCallback=function(r){
if(pipesCallBackArr[r.value.requesturl]){
for(var e=0;e<pipesCallBackArr[r.value.requesturl].length;e++){
if(pipesCallBackArr[r.value.requesturl][e]){
pipesCallBackArr[r.value.requesturl][e].f.renderResult(r);
pipesCallBackArr[r.value.requesturl][e]=null;
}
}
}
};
var _1a="http://pipes.yahoo.com/pipes/pipe.info?_id="+$.a.pipe_id;
var url="http://run.pipes.yahoo.com/pipes/pipe.run?_id="+$.a.pipe_id+"&_render=badge&_callback="+$.f.callback;
this.queryparams="";
for(var key in $.a.pipe_params){
if($.a.pipe_params[key]===null){
continue;
}
url+="&"+encodeURIComponent(key)+"="+encodeURIComponent($.a.pipe_params[key]);
this.queryparams+="&"+decodeURIComponent(key)+"="+decodeURIComponent($.a.pipe_params[key]);
}
$.w.t.href=_1a;
if(typeof (pipesCallBackArr)=="undefined"){
pipesCallBackArr=[];
}
if(typeof (pipesCallBackArr[url])=="undefined"){
pipesCallBackArr[url]=[];
}
pipesCallBackArr[url].push($);
if(typeof (YAHOO)=="undefined"||!YAHOO||typeof (YAHOO.util)=="undefined"||!YAHOO.util){
var _1d=document.getElementById("yui");
if(_1d==null){
$.f.runScript("http://yui.yahooapis.com/2.3.1/build/utilities/utilities.js","yui");
}
}
$.f.runScript(url,_2);
},renderResult:function(r){
if(r.value.published==""){
var t=$.w.h.cloneNode(true);
t.innerHTML=r.value.title;
$.w.h.parentNode.replaceChild(t,$.w.h);
$.w.h=t;
this.getThisDiv.style.display="none";
this.getThisDivArrow.style.display="none";
}else{
var t=$.w.t.cloneNode(true);
t.innerHTML=r.value.title;
$.w.t.parentNode.replaceChild(t,$.w.t);
$.w.t=t;
}
this.listbadge.init(r);
},runScript:function(url,id){
var s=document.createElement("script");
s.id=id;
s.type="text/javascript";
s.src=url;
document.getElementsByTagName("head")[0].appendChild(s);
},createSSLink:function(url,id){
var l=document.createElement("link");
l.id=id;
l.rel="stylesheet";
l.type="text/css";
l.href=url;
document.getElementsByTagName("head")[0].appendChild(l);
},removeScript:function(id){
if(document.getElementById(id)){
var s=document.getElementById(id);
s.parentNode.removeChild(s);
}
},getthisfuncInside:function(){
YAHOO.util.Dom.addClass(document.body,"yui-skin-sam");
var _28=(_1)?pid:$.a.pipe_id;
var _29=(_1)?"":$.f.queryparams;
if(this.getitnow==undefined){
this.getitnow=new YAHOO.widget.Panel(_2+"gin",{width:"420px",fixedcenter:true,constraintoviewport:true,underlay:"none",close:true,visible:false,draggable:true,modal:true,iframe:true,zIndex:"11111"});
this.getitnow.setHeader("<div style=\"border:none;font:bold 16px arial;color:#626262;text-align:left;padding-left:5px\">Get this Yahoo! Pipes<sup>™</sup> Badge <div style=\"position:absolute;right:35px;letter-spacing:4px;top:3px;\"><a style=\"font-size:11px;color:#626262;\" href=\"http://pipes.yahoo.com/pipes/badgedocs\" target=\"_blank\">HELP</a></div></div>");
this.getitnow.setBody("<iframe width=\"415\" height=\"350\" allowtransparency=\"true\" marginwidth=\"0\" marginheight=\"0\" hspace=\"0\" vspace=\"0\" frameborder=\"0\" scrolling=\"no\" src=\"http://pipes.yahoo.com/pipes/badge.config?page=1&_btype=list&_id="+_28+_29+"\"></iframe>");
this.getitnow.render(document.body);
YAHOO.util.Event.addListener(_2+"ginClose","click",this.getitnow.hide,this.getitnow,true);
}
this.getitnow.show();
},getthisfuncOutside:function(){
var _2a=(_1)?pid:$.a.pipe_id;
var _2b=(_1)?"":$.f.queryparams;
var url="http://pipes.yahoo.com/pipes/badge.config?page=1&_btype=list&_id="+_2a+_2b;
window.open(url);
},listbadge:{init:function(r){
if(typeof (YAHOO)=="undefined"){
$.f.timeoutCount--;
if($.f.timeoutCount==0){
}else{
window.setTimeout(function(){
$.f.listbadge.init(r);
},1000);
}
return;
}
YAHOO.util.Dom.removeClass($.w.ajaxwait,"PBajaxwait");
if(!$.f.inpipe){
var _2e=document.getElementById("YUICscript");
if(_2e==null){
$.f.runScript("http://yui.yahooapis.com/2.4.1/build/container/container-min.js","YUICscript");
}
$.w.dtf.style.display="block";
if(r.value.published!=""){
this.checkViewport();
}
}
YAHOO.util.Event.addListener(window,"resize",this.resized,this,true);
var w=$.w.r.offsetWidth;
if(!$.f.inpipe){
var _30=(parseInt($.a.containerPadding,10)*2);
var h=$.w.offsetHeight-$.w.h.offsetHeight-$.w.dtf.offsetHeight-_30-5;
if(h>0){
$.w.r.style.height=h+"px";
}
}
this.w=w;
this.remove();
if(r&&r.value&&r.value.items&&r.value.items.length){
this.startnum=0;
this.orglen=r.value.items.length;
this.countby=$.a.count;
this.results=r;
var _32=(this.orglen<this.countby)?this.orglen:this.countby;
this.create(this.startnum,_32);
this.startnum=this.countby;
}else{
var t=$.w.r.cloneNode(true);
t.innerHTML="<h4>No results</h4>";
$.w.r.parentNode.replaceChild(t,$.w.r);
$.w.r=t;
}
YAHOO.util.Dom.setStyle($.w.c,"visibility","visible");
},checkViewport:function(){
YAHOO.util.Event.removeListener($.f.getThisDiv,"click");
if(YAHOO.util.Dom.getViewportWidth()>=422&&YAHOO.util.Dom.getViewportHeight()>=415){
YAHOO.util.Event.addListener($.f.getThisDiv,"click",$.f.getthisfuncInside,this,true);
}else{
YAHOO.util.Event.addListener($.f.getThisDiv,"click",$.f.getthisfuncOutside,this,true);
}
},resized:function(){
if(this.currheight!=document.documentElement.clientHeight&&this.currheight!=""){
this.checkViewport();
}
this.currheight=document.documentElement.clientHeight;
},createDescription:function(_34,_35){
var _36=(_34.smallimg==undefined)?"":"<img src='"+_34.smallimg+"' />";
var _37=(_35=="imgBadge")?"":"<div class='pipesThumbnail'>"+_36+"</div>";
var _38=(_36==""||_35=="imgBadge")?"style='margin-left:0px;'":"style='margin-left:55px;'";
var _39="<div class='pipesImgdescription'><div class='pipesHolder'>"+_37+"<div class='pipesText' "+_38+"><div class='pipesTitle'><a href='"+_34.link+"' target='_self'>"+_34.title+"</a></div><div class='pipesDescription'>"+_34.description+"</div><ul class='pipesSmallthumb'></ul></div></div></div>";
return _39;
},createDescThumbs:function(obj,w,_3c){
var _3d=obj.getElementsByTagName("ul");
this.smallthumbholder=_3d[0];
var ww=w-55;
this.smallitemimgcount=Math.round(ww/50);
var _3f="";
var _40=(this.smallitemimgcount>_3c.usethisimgarr.length)?_3c.usethisimgarr.length:this.smallitemimgcount;
for(var x=1;x<_40;x++){
_3f+="<li><a href="+_3c.usethisimgarr[x].url+" target='_blank'><img src='"+_3c.usethisimgarr[x].url+"'</a></li>";
}
if(_3f==""){
this.smallthumbholder.style.marginTop="0px";
}else{
var t=this.smallthumbholder.cloneNode(true);
t.innerHTML=_3f;
this.smallthumbholder.parentNode.replaceChild(t,this.smallthumbholder);
this.smallthumbholder=t;
var _43=this.smallthumbholder.getElementsByTagName("img");
this.thumbnails=_43;
for(i=0;i<_43.length;i++){
new this.makeGrow(_43[i]);
}
}
},makeGrow:function(img){
var _45=null;
var _46=img;
var _47,w,h;
var _4a=function(obj){
_47=YAHOO.util.Dom.getXY(_46);
w=parseInt(YAHOO.util.Dom.getStyle(_46,"width"));
h=parseInt(YAHOO.util.Dom.getStyle(_46,"height"));
_45=obj.cloneNode(false);
_45.style.position="absolute";
_45.style.width="32px";
_45.style.height="32px";
_45.style.top=_47[1]+"px";
_45.style.left=_47[0]+"px";
_45.style.zIndex="999";
_45.style.display="none";
_45.style.padding="2px";
_45.style.border="1px solid #eee";
_45.className="clonedSmallImg";
YAHOO.util.Event.addListener(_45,"mouseout");
document.body.appendChild(_45);
_4c();
};
var _4c=function(e){
if(_45==null){
_4a(_46);
return;
}
_45.style.display="inline";
var _4e=new YAHOO.util.Anim(_45,{width:{to:200},height:{to:200}},0.6,YAHOO.util.Easing.backOut);
var _4f=_4e.getEl();
_4e.onTween.subscribe(function(){
var nx=_47[0]-((_4f.offsetWidth-w)>>1);
var ny=_47[1]-((_4f.offsetHeight-h)>>1);
if(nx<0){
nx=0;
}
if(ny<0){
ny=0;
}
YAHOO.util.Dom.setXY(_4f,[nx,ny]);
});
_4e.animate();
$.f.listbadge.growAnim=_4e;
YAHOO.util.Event.addListener(_45,"mouseout",_52);
};
var _52=function(){
if($.f.listbadge.growAnim.isAnimated()==true){
window.setTimeout(function(){
_52();
},50);
return;
}
YAHOO.util.Event.removeListener(_45,"mouseout");
var _53=new YAHOO.util.Anim(_45,{width:{to:32},height:{to:32}},0.2);
var _54=_53.getEl();
_53.onTween.subscribe(function(){
var nx=_47[0]-((_54.offsetWidth-w)>>1);
var ny=_47[1]-((_54.offsetHeight-h)>>1);
if(nx<0){
nx=0;
}
if(ny<0){
ny=0;
}
YAHOO.util.Dom.setXY(_54,[nx,ny]);
});
_53.onComplete.subscribe(function(){
var _57=_53.getEl();
_57.style.display="none";
});
_53.animate();
};
YAHOO.util.Event.addListener(_46,"mouseover",_4c);
},remove:function(){
$.w.r.innerHTML="";
},create:function(_58,_59){
for(var i=_58;i<_59;i++){
var _5b=this.results.value.items[i];
var _5c=_5b.media.regular.length;
var _5d=_5b.media.thumbnails.length;
var _5e=(_5c>_5d)?_5b.media.regular:_5b.media.thumbnails;
_5b.usethisimgarr=_5e;
if(_5e.length!=0){
if(_5b.media.thumbnails.length!=0){
_5b.smallimg=_5b.media.thumbnails[0].url;
}else{
_5b.smallimg=_5e[0].url;
}
}
var li=document.createElement("LI");
this.li=li;
li.className="ybi";
if(i%2){
li.className+=" odd";
}
li.innerHTML=this.createDescription(_5b);
this.createDescThumbs(this.li,this.w,_5b);
var _60=li.getElementsByTagName("div")[2];
var _61=li.getElementsByTagName("div")[3];
var _62=li.getElementsByTagName("div")[4];
var _63=li.getElementsByTagName("div")[5];
if(_60.innerHTML!=""){
YAHOO.util.Dom.setStyle(_60,"margin-right","8px");
}
YAHOO.util.Dom.setStyle(_61,"margin-left","0px");
$.w.r.appendChild(li);
}
if($.f.inpipe){
if(this.orglen>_59||_58!=0){
this.pagDiv=document.createElement("div");
this.pagDiv.className="paginate";
}
if(this.orglen>_59){
var _64=document.createElement("a");
_64.innerHTML="Next >";
YAHOO.util.Event.addListener(_64,"click",this.next_pag,this,true);
this.pagDiv.appendChild(_64);
}
if(_58!=0){
var _65=document.createElement("a");
_65.innerHTML="< Prev";
if(this.orglen>_59){
_65.style.right="40px";
_65.style.position="absolute";
}else{
_65.style.right="";
_65.style.position="";
}
YAHOO.util.Event.addListener(_65,"click",this.prev_pag,this,true);
this.pagDiv.appendChild(_65);
}
if(this.orglen>_59||_58!=0){
$.w.r.appendChild(this.pagDiv);
this.pagDiv=null;
}
}
},prev_pag:function(){
this.remove();
var _66=this.startorg-this.countby;
var _67=_66+this.countby;
if(_67>=this.orglen){
_67=this.orglen;
}
this.create(_66,_67);
location.href="#";
this.startnum=_67;
this.startorg=_66;
},next_pag:function(){
this.remove();
var _68=this.startnum;
var _69=this.countby+_68;
if(_69>=this.orglen){
_69=this.orglen;
}
this.create(_68,_69);
location.href="#";
this.startnum=_69;
this.startorg=_68;
}}};
}();
var _6a=/listbadge.js$/;
var _6b=function(){
$.f.init(_6a);
};
if(_1){
_6b();
}else{
if(typeof window.addEventListener!=="undefined"){
if(window.opera){
_6b();
}else{
window.addEventListener("load",_6b,false);
}
}else{
if(typeof window.attachEvent!=="undefined"){
window.attachEvent("onload",_6b);
}
}
}
})(); | JavaScript |
/*!
* jQuery JavaScript Library v1.6.4
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Mon Sep 12 18:54:48 2011 -0400
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Check for digits
rdigit = /\d/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.6.4",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.done( fn );
return this;
},
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNaN: function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw msg;
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return (new Function( "return " + data ))();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array ) {
if ( !array ) {
return -1;
}
if ( indexOf ) {
return indexOf.call( array, elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
var // Promise methods
promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
// Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
// Create a simple deferred (one callbacks list)
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
// Full fledged deferred (two callbacks list)
Deferred: function( func ) {
var deferred = jQuery._Deferred(),
failDeferred = jQuery._Deferred(),
promise;
// Add errorDeferred methods, then and promise
jQuery.extend( deferred, {
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
always: function() {
return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
},
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
pipe: function( fnDone, fnFail ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
if ( promise ) {
return promise;
}
promise = obj = {};
}
var i = promiseMethods.length;
while( i-- ) {
obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
}
return obj;
}
});
// Make sure only one callback list will be used
deferred.done( failDeferred.cancel ).fail( deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = arguments,
i = 0,
length = args.length,
count = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
// Strange bug in FF4:
// Values changed onto the arguments object sometimes end up as undefined values
// outside the $.when method. Cloning the object into a fresh array solves the issue
deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
}
};
}
if ( length > 1 ) {
for( ; i < length; i++ ) {
if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var div = document.createElement( "div" ),
documentElement = document.documentElement,
all,
a,
select,
opt,
input,
marginDiv,
support,
fragment,
body,
testElementParent,
testElement,
testElementStyle,
tds,
events,
eventName,
i,
isSupported;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName( "tbody" ).length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName( "link" ).length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55$/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains it's value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
div.innerHTML = "";
// Figure out if the W3C box model works as expected
div.style.width = div.style.paddingLeft = "1px";
body = document.getElementsByTagName( "body" )[ 0 ];
// We use our own, invisible, body unless the body is already present
// in which case we use a div (#9239)
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
jQuery.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
}
div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE < 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( document.defaultView && document.defaultView.getComputedStyle ) {
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
// Remove the body element we added
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for( i in {
submit: 1,
change: 1,
focusin: 1
} ) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Null connected elements to avoid leaks in IE
testElement = fragment = select = opt = body = marginDiv = div = input = null;
return support;
})();
// Keep track of boxModel
jQuery.boxModel = jQuery.support.boxModel;
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || (pvt && id && (cache[ id ] && !cache[ id ][ internalKey ]))) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
} else {
id = jQuery.expando;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
} else {
cache[ id ] = jQuery.extend(cache[ id ], name);
}
}
thisCache = cache[ id ];
// Internal jQuery data is stored in a separate object inside the object's data
// cache in order to avoid key collisions between internal data and user-defined
// data
if ( pvt ) {
if ( !thisCache[ internalKey ] ) {
thisCache[ internalKey ] = {};
}
thisCache = thisCache[ internalKey ];
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
// not attempt to inspect the internal events object using jQuery.data, as this
// internal data object is undocumented and subject to change.
if ( name === "events" && !thisCache[name] ) {
return thisCache[ internalKey ] && thisCache[ internalKey ].events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
if ( thisCache ) {
// Support interoperable removal of hyphenated or camelcased keys
if ( !thisCache[ name ] ) {
name = jQuery.camelCase( name );
}
delete thisCache[ name ];
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !isEmptyDataObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( pvt ) {
delete cache[ id ][ internalKey ];
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
var internalCache = cache[ id ][ internalKey ];
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the entire user cache at once because it's faster than
// iterating through each key, but we need to continue to persist internal
// data if it existed
if ( internalCache ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
cache[ id ][ internalKey ] = internalCache;
// Otherwise, we need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
} else if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
} else {
elem[ jQuery.expando ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 ) {
var attr = this[0].attributes, name;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!jQuery.isNaN( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
// property to be considered empty objects; this property always exists in
// order to make sure JSON.stringify does not expose internal metadata
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery.data( elem, deferDataKey, undefined, true );
if ( defer &&
( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
!jQuery.data( elem, markDataKey, undefined, true ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.resolve();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = (type || "fx") + "mark";
jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
if ( count ) {
jQuery.data( elem, key, count, true );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
if ( elem ) {
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type, undefined, true );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data), true );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
defer;
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
count++;
tmp.done( resolve );
}
}
resolve();
return defer.promise();
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
nodeHook, boolHook;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = (value || "").split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ";
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return undefined;
}
var isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attrFix: {
// Always normalize to ensure hook usage
tabindex: "tabIndex"
},
attr: function( elem, name, value, pass ) {
var nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( !("getAttribute" in elem) ) {
return jQuery.prop( elem, name, value );
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Normalize the name if needed
if ( notxml ) {
name = jQuery.attrFix[ name ] || name;
hooks = jQuery.attrHooks[ name ];
if ( !hooks ) {
// Use boolHook for boolean attributes
if ( rboolean.test( name ) ) {
hooks = boolHook;
// Use nodeHook if available( IE6/7 )
} else if ( nodeHook ) {
hooks = nodeHook;
}
}
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return undefined;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, name ) {
var propName;
if ( elem.nodeType === 1 ) {
name = jQuery.attrFix[ name ] || name;
jQuery.attr( elem, name, "" );
elem.removeAttribute( name );
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
elem[ propName ] = false;
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return (elem[ name ] = value);
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Add the tabindex propHook to attrHooks for back-compat
jQuery.attrHooks.tabIndex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode;
return jQuery.prop( elem, name ) === true || ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !jQuery.support.getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
// Return undefined if nodeValue is empty string
return ret && ret.nodeValue !== "" ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return (ret.nodeValue = value + "");
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return (elem.style.cssText = "" + value);
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
}
}
});
});
var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspaces = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
};
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, pos ) {
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData.events;
if ( !elemData || !events ) {
return;
}
// types is actually an event object here
if ( types && types.type ) {
handler = types.handler;
types = types.type;
}
// Unbind all events for the element
if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) {
// Namespaced event handlers
namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) {
// remove the given handler for the given type
if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
}
// remove generic event handler if no more handlers exist
if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem, undefined, true );
}
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Event object or event type
var type = event.type || event,
namespaces = [],
exclusive;
if ( type.indexOf("!") >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.exclusive = exclusive;
event.namespace = namespaces.join(".");
event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
// triggerHandler() and global events don't bubble or run the default action
if ( onlyHandlers || !elem ) {
event.preventDefault();
event.stopPropagation();
}
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
jQuery.each( jQuery.cache, function() {
// internalKey variable is just used to make it easier to find
// and potentially change this stuff later; currently it just
// points to jQuery.expando
var internalKey = jQuery.expando,
internalCache = this[ internalKey ];
if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
jQuery.event.trigger( event, data, internalCache.handle.elem );
}
});
return;
}
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
event.target = elem;
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
var cur = elem,
// IE doesn't like method names with a colon (#3533, #8272)
ontype = type.indexOf(":") < 0 ? "on" + type : "";
// Fire event on the current element, then bubble up the DOM tree
do {
var handle = jQuery._data( cur, "handle" );
event.currentTarget = cur;
if ( handle ) {
handle.apply( cur, data );
}
// Trigger an inline bound script
if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
event.result = false;
event.preventDefault();
}
// Bubble up to document, then to window
cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
} while ( cur && !event.isPropagationStopped() );
// If nobody prevented the default action, do it now
if ( !event.isDefaultPrevented() ) {
var old,
special = jQuery.event.special[ type ] || {};
if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction)() check here because IE6/7 fails that test.
// IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
try {
if ( ontype && elem[ type ] ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
jQuery.event.triggered = type;
elem[ type ]();
}
} catch ( ieError ) {}
if ( old ) {
elem[ ontype ] = old;
}
jQuery.event.triggered = undefined;
}
}
return event.result;
},
handle: function( event ) {
event = jQuery.event.fix( event || window.event );
// Snapshot the handlers list since a called handler may add/remove events.
var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
run_all = !event.exclusive && !event.namespace,
args = Array.prototype.slice.call( arguments, 0 );
// Use the fix-ed Event rather than the (read-only) native event
args[0] = event;
event.currentTarget = this;
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ];
// Triggered event must 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event.
if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
// Fixes #1925 where srcElement might not be defined either
event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var eventDocument = event.target.ownerDocument || document,
doc = eventDocument.documentElement,
body = eventDocument.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
// Deprecated, use jQuery.guid instead
guid: 1E8,
// Deprecated, use jQuery.proxy instead
proxy: jQuery.proxy,
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var related = event.relatedTarget,
inside = false,
eventType = event.type;
event.type = event.data;
if ( related !== this ) {
if ( related ) {
inside = jQuery.contains( this, related );
}
if ( !inside ) {
jQuery.event.handle.apply( this, arguments );
event.type = eventType;
}
}
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( !jQuery.nodeName( this, "form" ) ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
// Avoid triggering error on non-existent type attribute in IE VML (#7071)
var elem = e.target,
type = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.type : "";
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.type : "";
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = jQuery.nodeName( elem, "input" ) ? elem.type : "",
val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( jQuery.nodeName( elem, "select" ) ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery._data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery._data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information
beforeactivate: function( e ) {
var elem = e.target;
jQuery._data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
// Handle when the input is .focus()'d
changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
// Don't pass args or remember liveFired; they apply to the donor event.
var event = jQuery.extend( {}, args[ 0 ] );
event.type = type;
event.originalEvent = {};
event.liveFired = undefined;
jQuery.event.handle.call( elem, event );
if ( event.isDefaultPrevented() ) {
args[ 0 ].preventDefault();
}
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0;
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( donor ) {
// Donor event is always a native one; fix it and switch its type.
// Let focusin/out handler cancel the donor focus/blur event.
var e = jQuery.event.fix( donor );
e.type = fix;
e.originalEvent = {};
jQuery.event.trigger( e, null, e.target );
if ( e.isDefaultPrevented() ) {
donor.preventDefault();
}
}
});
}
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
var handler;
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( arguments.length === 2 || data === false ) {
fn = data;
data = undefined;
}
if ( name === "one" ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
};
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
jQuery.fn.extend({
unbind: function( type, fn ) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
},
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( name === "die" && !types &&
origSelector && origSelector.charAt(0) === "." ) {
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( liveMap[ type ] ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
});
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery._data( this, "events" );
// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
elem = close.elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
// Make sure not to accidentally match a child element with the same selector
if ( related && jQuery.contains( elem, related ) ) {
related = elem;
}
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
var first = match[2],
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && ( typeof selector === "string" ?
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[ selector ] ) {
matches[ selector ] = POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[ selector ];
if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return (elem === qualifier) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || (l > 1 && i < lastIndex) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var internalKey = jQuery.expando,
oldData = jQuery.data( src ),
curData = jQuery.data( dest, oldData );
// Switch to use the internal data object, if it exists, for the next
// stage of data copying
if ( (oldData = oldData[ internalKey ]) ) {
var events = oldData.events;
curData = curData[ internalKey ] = jQuery.extend({}, oldData);
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc;
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( "getElementsByTagName" in elem ) {
return elem.getElementsByTagName( "*" );
} else if ( "querySelectorAll" in elem ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( "getElementsByTagName" in elem ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var clone = elem.cloneNode(true),
srcElements,
destElements,
i;
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName
// instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [], j;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ] && cache[ id ][ internalKey ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
rrelNum = /^([\-+])=([\-+.\de]+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
return val;
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat( value );
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
var ret;
jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
ret = curCSS( elem, "margin-right", "marginRight" );
} else {
ret = elem.style.marginRight;
}
});
return ret;
}
};
}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( !(defaultView = elem.ownerDocument.defaultView) ) {
return undefined;
}
if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left,
ret = elem.currentStyle && elem.currentStyle[ name ],
rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
which = name === "width" ? cssWidth : cssHeight;
if ( val > 0 ) {
if ( extra !== "border" ) {
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
}
});
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
jQuery.each( which, function() {
val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
}
});
}
return val + "px";
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for(; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.bind( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery._Deferred(),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
jQuery.error( e );
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for( key in s.converters ) {
if( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data(elem, "olddisplay") || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
if ( this[i].style ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
jQuery._data( this[i], "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p,
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
display = defaultDisplay( this.nodeName );
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
});
},
stop: function( clearQueue, gotoEnd ) {
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
var timers = jQuery.timers,
i = timers.length;
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
while ( i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue !== false ) {
jQuery.dequeue( this );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
},
// Get the current size
cur: function() {
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.start = from;
this.end = to;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
this.now = this.start;
this.pos = this.state = 0;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function( gotoEnd ) {
var t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options,
i, n;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( i in options.animatedProperties ) {
if ( options.animatedProperties[i] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery(elem).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( var p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[p] );
}
}
// Execute the complete function
options.complete.call( elem );
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ((this.end - this.start) * this.pos);
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) {
if ( !timers[i]() ) {
timers.splice(i--, 1);
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
jQuery.offset.initialize();
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";
// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";
innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
body.removeChild( container );
jQuery.offset.initialize = jQuery.noop;
},
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
jQuery.offset.initialize();
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem && elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem && elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ],
body = elem.document.body;
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
body && body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
| JavaScript |
/*
* faded 0.3.1 - jQuery plugin
* written by Nathan Searles
* http://nathansearles.com/faded/
*
* Copyright (c) 2009 Nathan Searles (http://nathansearles.com/)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* Built for jQuery library
* http://jquery.com
* Compatible with jQuery 1.3.2+
*
*/
if(typeof jQuery != "undefined") {
jQuery(function($) {
$.fn.extend({
faded: function(options) {
var settings = $.extend({}, $.fn.faded.defaults, options);
return this.each(
function() {
if($.fn.jquery < "1.3.1") {return;}
var $t = $(this);
var $c = $t.children(":nth-child(1)");
var o = $.metadata ? $.extend({}, settings, $t.metadata()) : settings;
var total = $c.children().size();
var next = 0, prev = 0, number = 0, currentitem = 0, restart = 0, restartinterval = 0;
var loaded,active,imgSrc,clicked,current;
if (o.random) {
$.fn.reorder = function(callback) {
function randOrd() { return(Math.round(Math.random())-0.5); }
return($(this).each(function() {
var $this = $(this);
var $children = $this.children();
var childCount = $children.length;
if (childCount > 1) {
$children.hide();
var indices = new Array();
for (i=0;i<childCount;i++) { indices[indices.length] = i; }
indices = indices.sort(randOrd);
$.each(indices,function(j,k) {
var $child = $children.eq(k);
var $clone = $child.clone(true);
$clone.show().appendTo($this);
if (callback !== undefined) {
callback($child, $clone);
}
$child.remove();
});
}
}));
};
$c.reorder();
}
function pause() {
clearInterval(autoplay);
clearTimeout(restart);
restart = setTimeout(function() {
autoplay = setInterval(function(){
animate("next");
},o.autoplay);
},o.autorestart);
}
$c.css({position:"relative"});
$c.children().css({
position:"absolute",
top: 0,
left: 0,
zIndex: 0,
display:"none"
});
if (o.autoheight) {
$c.animate({height: $c.children(":eq(0)").outerHeight()},o.autoheight);
}
if (o.pagination) {
if (o.autopagination) {
$t.append("<ul class="+o.pagination+"></ul>");
$c.children().each(function(){
$("."+o.pagination+"",$t).append("<li><a rel="+number+" href=\"#\" >"+(number+1)+"</a></li>");
number++;
});
}
$("."+o.pagination+" li a:eq(0)",$t).parent().addClass("current");
$("."+o.pagination+" li a",$t).click(function(){
current = $("."+o.pagination+" li.current a",$t).attr("rel");
clicked = $(this).attr("rel");
if (current != clicked) {animate("pagination",clicked,current);}
if(o.autoplay){pause();}
return false;
});
}
if (o.sequentialloading&&$c.children()[0].tagName=="IMG") {
$c.css({background:"url("+o.loadingimg+") no-repeat 50% 50%"});
imgSrc = $("img:eq(0)",$c).attr("src");
$("img:eq(0)",$c).attr("src", imgSrc).load(function() {
$(this).fadeIn(o.speed,function(){
loaded = true;
});
});
} else {
$c.find(":eq(0)").fadeIn(o.speed,function(){
loaded = true;
});
}
if (o.bigtarget) {
$c.css({"cursor":"pointer"});
$c.click(function(){
animate("next");
if(o.autoplay){
if (o.autorestart) {
pause();
} else {
clearInterval(autoplay);
}
}
return false;
});
}
if (o.autoplay) {
autoplay = setInterval(function(){
animate("next");
},o.autoplay);
pause();
}
$("."+o.nextbtn,$t).click(function(){
animate("next");
if(o.autoplay){
if (o.autorestart) {
pause();
} else {
clearInterval(autoplay);
}
}
return false;
});
$("."+o.prevbtn,$t).click(function(){
animate("prev");
if(o.autoplay){
if (o.autorestart) {
pause();
} else {
clearInterval(autoplay);
}
}
return false;
});
function animate(dir,clicked,current){
if (!active&&loaded) {
active=true;
switch(dir) {
case "next":
prev = next;
next = currentitem*1+1;
if (total === next) { next = 0; }
break;
case "prev":
prev = next;
next = currentitem*1-1;
if (next === -1) { next = total-1; }
break;
case "pagination":
next = clicked;
prev = current;
break;
}
if (o.pagination) {
$(".pagination li.current",$t).removeClass("current");
$(".pagination li a:eq("+next+")",$t).parent().addClass("current");
}
if (o.crossfade) {
$c.children(":eq("+next+")").css({zIndex:10}).fadeIn(o.speed,function(){
$c.children(":eq("+prev+")").css({display:"none",zIndex:0});
$(this).css({zIndex:0});
currentitem = next;
active = false;
});
} else {
$c.children(":eq("+prev+")").fadeOut(o.speed,function(){
if (o.autoheight) {
$c.animate({height: $c.children(":eq("+next+")").outerHeight()},o.autoheight,function(){
$c.children(":eq("+next+")").fadeIn(o.speed);
});
} else {
$c.children(":eq("+next+")").fadeIn(o.speed);
}
currentitem = next;
active = false;
});
}
}
}
}
);
}
});
$.fn.faded.defaults = {
speed: 300,
crossfade: false,
bigtarget: false,
sequentialloading: false,
autoheight: false,
pagination: "pagination",
autopagination: true,
nextbtn: "next",
prevbtn: "prev",
loadingimg: false,
autoplay: false,
autorestart: false,
random: false
};
});
} | JavaScript |
| JavaScript |
$(document).ready(function () {
/*$('.btn').mouseover(function () {
$(this).tooltip('show');
});
$('a').mouseover(function () {
$(this).tooltip('show');
});*/
}); | JavaScript |
function create_menu(basepath)
{
var base = (basepath == 'null') ? '' : basepath;
document.write(
'<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">' +
'<ul>' +
'<li><a href="'+base+'index.html">User Guide Home</a></li>' +
'<li><a href="'+base+'toc.html">Table of Contents Page</a></li>' +
'</ul>' +
'<h3>Basic Info</h3>' +
'<ul>' +
'<li><a href="'+base+'general/requirements.html">Server Requirements</a></li>' +
'<li><a href="'+base+'license.html">License Agreement</a></li>' +
'<li><a href="'+base+'changelog.html">Change Log</a></li>' +
'<li><a href="'+base+'general/credits.html">Credits</a></li>' +
'</ul>' +
'<h3>Installation</h3>' +
'<ul>' +
'<li><a href="'+base+'installation/downloads.html">Downloading CodeIgniter</a></li>' +
'<li><a href="'+base+'installation/index.html">Installation Instructions</a></li>' +
'<li><a href="'+base+'installation/upgrading.html">Upgrading from a Previous Version</a></li>' +
'<li><a href="'+base+'installation/troubleshooting.html">Troubleshooting</a></li>' +
'</ul>' +
'<h3>Introduction</h3>' +
'<ul>' +
'<li><a href="'+base+'overview/getting_started.html">Getting Started</a></li>' +
'<li><a href="'+base+'overview/at_a_glance.html">CodeIgniter at a Glance</a></li>' +
'<li><a href="'+base+'overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li>' +
'<li><a href="'+base+'overview/features.html">Supported Features</a></li>' +
'<li><a href="'+base+'overview/appflow.html">Application Flow Chart</a></li>' +
'<li><a href="'+base+'overview/mvc.html">Model-View-Controller</a></li>' +
'<li><a href="'+base+'overview/goals.html">Architectural Goals</a></li>' +
'</ul>' +
'<h3>Tutorial</h3>' +
'<ul>' +
'<li><a href="'+base+'tutorial/index.html">Introduction</a></li>' +
'<li><a href="'+base+'tutorial/static_pages.html">Static pages</a></li>' +
'<li><a href="'+base+'tutorial/news_section.html">News section</a></li>' +
'<li><a href="'+base+'tutorial/create_news_items.html">Create news items</a></li>' +
'<li><a href="'+base+'tutorial/conclusion.html">Conclusion</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>General Topics</h3>' +
'<ul>' +
'<li><a href="'+base+'general/urls.html">CodeIgniter URLs</a></li>' +
'<li><a href="'+base+'general/controllers.html">Controllers</a></li>' +
'<li><a href="'+base+'general/reserved_names.html">Reserved Names</a></li>' +
'<li><a href="'+base+'general/views.html">Views</a></li>' +
'<li><a href="'+base+'general/models.html">Models</a></li>' +
'<li><a href="'+base+'general/helpers.html">Helpers</a></li>' +
'<li><a href="'+base+'general/libraries.html">Using CodeIgniter Libraries</a></li>' +
'<li><a href="'+base+'general/creating_libraries.html">Creating Your Own Libraries</a></li>' +
'<li><a href="'+base+'general/drivers.html">Using CodeIgniter Drivers</a></li>' +
'<li><a href="'+base+'general/creating_drivers.html">Creating Your Own Drivers</a></li>' +
'<li><a href="'+base+'general/core_classes.html">Creating Core Classes</a></li>' +
'<li><a href="'+base+'general/hooks.html">Hooks - Extending the Core</a></li>' +
'<li><a href="'+base+'general/autoloader.html">Auto-loading Resources</a></li>' +
'<li><a href="'+base+'general/common_functions.html">Common Functions</a></li>' +
'<li><a href="'+base+'general/routing.html">URI Routing</a></li>' +
'<li><a href="'+base+'general/errors.html">Error Handling</a></li>' +
'<li><a href="'+base+'general/caching.html">Caching</a></li>' +
'<li><a href="'+base+'general/profiling.html">Profiling Your Application</a></li>' +
'<li><a href="'+base+'general/cli.html">Running via the CLI</a></li>' +
'<li><a href="'+base+'general/managing_apps.html">Managing Applications</a></li>' +
'<li><a href="'+base+'general/environments.html">Handling Multiple Environments</a></li>' +
'<li><a href="'+base+'general/alternative_php.html">Alternative PHP Syntax</a></li>' +
'<li><a href="'+base+'general/security.html">Security</a></li>' +
'<li><a href="'+base+'general/styleguide.html">PHP Style Guide</a></li>' +
'<li><a href="'+base+'doc_style/index.html">Writing Documentation</a></li>' +
'</ul>' +
'<h3>Additional Resources</h3>' +
'<ul>' +
'<li><a href="http://codeigniter.com/forums/">Community Forums</a></li>' +
'<li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Class Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/benchmark.html">Benchmarking Class</a></li>' +
'<li><a href="'+base+'libraries/calendar.html">Calendar Class</a></li>' +
'<li><a href="'+base+'libraries/cart.html">Cart Class</a></li>' +
'<li><a href="'+base+'libraries/config.html">Config Class</a></li>' +
'<li><a href="'+base+'libraries/email.html">Email Class</a></li>' +
'<li><a href="'+base+'libraries/encryption.html">Encryption Class</a></li>' +
'<li><a href="'+base+'libraries/file_uploading.html">File Uploading Class</a></li>' +
'<li><a href="'+base+'libraries/form_validation.html">Form Validation Class</a></li>' +
'<li><a href="'+base+'libraries/ftp.html">FTP Class</a></li>' +
'<li><a href="'+base+'libraries/table.html">HTML Table Class</a></li>' +
'<li><a href="'+base+'libraries/image_lib.html">Image Manipulation Class</a></li>' +
'<li><a href="'+base+'libraries/input.html">Input Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'<li><a href="'+base+'libraries/loader.html">Loader Class</a></li>' +
'<li><a href="'+base+'libraries/language.html">Language Class</a></li>' +
'<li><a href="'+base+'libraries/migration.html">Migration Class</a></li>' +
'<li><a href="'+base+'libraries/output.html">Output Class</a></li>' +
'<li><a href="'+base+'libraries/pagination.html">Pagination Class</a></li>' +
'<li><a href="'+base+'libraries/security.html">Security Class</a></li>' +
'<li><a href="'+base+'libraries/sessions.html">Session Class</a></li>' +
'<li><a href="'+base+'libraries/trackback.html">Trackback Class</a></li>' +
'<li><a href="'+base+'libraries/parser.html">Template Parser Class</a></li>' +
'<li><a href="'+base+'libraries/typography.html">Typography Class</a></li>' +
'<li><a href="'+base+'libraries/unit_testing.html">Unit Testing Class</a></li>' +
'<li><a href="'+base+'libraries/uri.html">URI Class</a></li>' +
'<li><a href="'+base+'libraries/user_agent.html">User Agent Class</a></li>' +
'<li><a href="'+base+'libraries/xmlrpc.html">XML-RPC Class</a></li>' +
'<li><a href="'+base+'libraries/zip.html">Zip Encoding Class</a></li>' +
'</ul>' +
'</td><td class="td_sep" valign="top">' +
'<h3>Driver Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'libraries/caching.html">Caching Class</a></li>' +
'<li><a href="'+base+'database/index.html">Database Class</a></li>' +
'<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' +
'</ul>' +
'<h3>Helper Reference</h3>' +
'<ul>' +
'<li><a href="'+base+'helpers/array_helper.html">Array Helper</a></li>' +
'<li><a href="'+base+'helpers/captcha_helper.html">CAPTCHA Helper</a></li>' +
'<li><a href="'+base+'helpers/cookie_helper.html">Cookie Helper</a></li>' +
'<li><a href="'+base+'helpers/date_helper.html">Date Helper</a></li>' +
'<li><a href="'+base+'helpers/directory_helper.html">Directory Helper</a></li>' +
'<li><a href="'+base+'helpers/download_helper.html">Download Helper</a></li>' +
'<li><a href="'+base+'helpers/email_helper.html">Email Helper</a></li>' +
'<li><a href="'+base+'helpers/file_helper.html">File Helper</a></li>' +
'<li><a href="'+base+'helpers/form_helper.html">Form Helper</a></li>' +
'<li><a href="'+base+'helpers/html_helper.html">HTML Helper</a></li>' +
'<li><a href="'+base+'helpers/inflector_helper.html">Inflector Helper</a></li>' +
'<li><a href="'+base+'helpers/language_helper.html">Language Helper</a></li>' +
'<li><a href="'+base+'helpers/number_helper.html">Number Helper</a></li>' +
'<li><a href="'+base+'helpers/path_helper.html">Path Helper</a></li>' +
'<li><a href="'+base+'helpers/security_helper.html">Security Helper</a></li>' +
'<li><a href="'+base+'helpers/smiley_helper.html">Smiley Helper</a></li>' +
'<li><a href="'+base+'helpers/string_helper.html">String Helper</a></li>' +
'<li><a href="'+base+'helpers/text_helper.html">Text Helper</a></li>' +
'<li><a href="'+base+'helpers/typography_helper.html">Typography Helper</a></li>' +
'<li><a href="'+base+'helpers/url_helper.html">URL Helper</a></li>' +
'<li><a href="'+base+'helpers/xml_helper.html">XML Helper</a></li>' +
'</ul>' +
'</td></tr></table>');
} | JavaScript |
/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
10/24/2005
v(1.0.2)
*/
//base
var fx = new Object();
fx.Base = function(){};
fx.Base.prototype = {
setOptions: function(options) {
this.options = {
duration: 500,
onComplete: ''
}
Object.extend(this.options, options || {});
},
go: function() {
this.duration = this.options.duration;
this.startTime = (new Date).getTime();
this.timer = setInterval (this.step.bind(this), 13);
},
step: function() {
var time = (new Date).getTime();
var Tpos = (time - this.startTime) / (this.duration);
if (time >= this.duration+this.startTime) {
this.now = this.to;
clearInterval (this.timer);
this.timer = null;
if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
}
else {
this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from;
//this time-position, sinoidal transition thing is from script.aculo.us
}
this.increase();
},
custom: function(from, to) {
if (this.timer != null) return;
this.from = from;
this.to = to;
this.go();
},
hide: function() {
this.now = 0;
this.increase();
},
clearTimer: function() {
clearInterval(this.timer);
this.timer = null;
}
}
//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
initialize: function(el, options) {
this.el = $(el);
this.el.style.overflow = "hidden";
this.el.iniWidth = this.el.offsetWidth;
this.el.iniHeight = this.el.offsetHeight;
this.setOptions(options);
}
});
fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {
increase: function() {
this.el.style.height = this.now + "px";
},
toggle: function() {
if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
else this.custom(0, this.el.scrollHeight);
}
});
| JavaScript |
window.onload = function() {
myHeight = new fx.Height('nav', {duration: 400});
myHeight.hide();
} | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Coming Soon Countdown ===== */
$(function () {
var austDay = new Date();
austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26);
$('#countdown').countdown({until: austDay});
$('#year').text(austDay.getFullYear());
}); | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Tooltips ===== */
$('.tooltip-test > button').tooltip();
/* ===== Popovers ===== */
$('.popover-test > button').popover();
/* ===== Smooth Scrolling ===== */
$(document).ready(function(){
$('a[href*=#typography],a[href*=#buttons], a[href*=#navs], a[href*=#pagination], a[href*=#tooltips], a[href*=#popovers], a[href*=#panels], a[href*=#accordion], a[href*=#carousel], a[href*=#info-boards], a[href*=#social-links], a[href*=#responsive-iframes]').bind("click", function(e){
var anchor = $(this);
$('html, body').stop().animate({
scrollTop: $(anchor.attr('href')).offset().top
}, 1000);
e.preventDefault();
});
return false;
});
| JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Tooltips ===== */
$('#bonus-tip').tooltip(); | JavaScript |
//** jQuery Scroll to Top Control script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** Available/ usage terms at http://www.dynamicdrive.com (March 30th, 09')
//** v1.1 (April 7th, 09'):
//** 1) Adds ability to scroll to an absolute position (from top of page) or specific element on the page instead.
//** 2) Fixes scroll animation not working in Opera.
var scrolltotop={
//startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control
//scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top).
setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]},
controlHTML: '<i class="fa fa-angle-up backtotop"></i>', //HTML for control, which is auto wrapped in DIV w/ ID="topcontrol"
controlattrs: {offsetx:5, offsety:5}, //offset of control relative to right/ bottom of window corner
anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links
state: {isvisible:false, shouldvisible:false},
scrollup:function(){
if (!this.cssfixedsupport) //if control is positioned using JavaScript
this.$control.css({opacity:0}) //hide control immediately after clicking it
var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto)
if (typeof dest=="string" && jQuery('#'+dest).length==1) //check element set by string exists
dest=jQuery('#'+dest).offset().top
else
dest=0
this.$body.animate({scrollTop: dest}, this.setting.scrollduration);
},
keepfixed:function(){
var $window=jQuery(window)
var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx
var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety
this.$control.css({left:controlx+'px', top:controly+'px'})
},
togglecontrol:function(){
var scrolltop=jQuery(window).scrollTop()
if (!this.cssfixedsupport)
this.keepfixed()
this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false
if (this.state.shouldvisible && !this.state.isvisible){
this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0])
this.state.isvisible=true
}
else if (this.state.shouldvisible==false && this.state.isvisible){
this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1])
this.state.isvisible=false
}
},
init:function(){
jQuery(document).ready(function($){
var mainobj=scrolltotop
var iebrws=document.all
mainobj.cssfixedsupport=!iebrws || iebrws && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode
mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body')
mainobj.$control=$('<div id="topcontrol">'+mainobj.controlHTML+'</div>')
.css({position:mainobj.cssfixedsupport? 'fixed' : 'absolute', bottom:mainobj.controlattrs.offsety, right:mainobj.controlattrs.offsetx, opacity:0, cursor:'pointer'})
.attr({title:''})
.click(function(){mainobj.scrollup(); return false})
.appendTo('body')
if (document.all && !window.XMLHttpRequest && mainobj.$control.text()!='') //loose check for IE6 and below, plus whether control contains any text
mainobj.$control.css({width:mainobj.$control.width()}) //IE6- seems to require an explicit width on a DIV containing text
mainobj.togglecontrol()
$('a[href="' + mainobj.anchorkeyword +'"]').click(function(){
mainobj.scrollup()
return false
})
$(window).bind('scroll resize', function(e){
mainobj.togglecontrol()
})
})
}
}
scrolltotop.init() | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
// Isotop Gallery
// ==============
//$(document).ready(function() {
var $container = $('#isotope-container');
$container.isotope({
itemSelector: '.isotope-item',
});
$('#filters a').click(function() {
var selector = $(this).attr('data-filter');
$container.isotope({filter: selector});
return false;
});
//});
| JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Sign Up popovers ===== */
$(function(){
$('#name').popover();
});
$(function(){
$('#username').popover();
});
$(function(){
$('#email').popover();
});
$(function(){
$('#password').popover();
});
$(function(){
$('#repeat-password').popover();
}); | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Tooltips ===== */
$('#tooltip').tooltip();
$(document).ready(function() {
$('#menu li a').click(function() {
var parent = $(this).parent();
if (!parent.hasClass('active')) {
parent.addClass('active').siblings().removeClass('active');
}
});
}); | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Navbar Search ===== */
$('#navbar-search > a').on('click', function() {
$('#navbar-search > a > i').toggleClass('fa-search fa-times');
$("#navbar-search-box").toggleClass('show hidden animated fadeInUp');
return false;
});
/*===== Pricing Bonus ===== */
$('#bonus .pricing-number > .fa-scissors').on('click', function() {
$(this).css('left', '100%'); /* Cutting */
setTimeout(function(){ /* Removing the scissors */
$('#bonus .pricing-number > .fa-scissors').addClass('hidden');
$('#bonus .pricing-body ul').addClass('animated fadeOutDown');
}, 2000);
return false;
});
/* ===== Lost password form ===== */
$('.pwd-lost > .pwd-lost-q > a').on('click', function() {
$(".pwd-lost > .pwd-lost-q").toggleClass("show hidden");
$(".pwd-lost > .pwd-lost-f").toggleClass("hidden show animated fadeIn");
return false;
});
/* ===== Thumbs rating ===== */
$('.rating .voteup').on('click', function () {
var up = $(this).closest('div').find('.up');
up.text(parseInt(up.text(),10) + 1);
return false;
});
$('.rating .votedown').on('click', function () {
var down = $(this).closest('div').find('.down');
down.text(parseInt(down.text(),10) + 1);
return false;
});
/* ===== Responsive Showcase ===== */
$('.responsive-showcase ul > li > i').on('click', function() {
var device = $(this).data('device');
$('.responsive-showcase ul > li > i').addClass("inactive");
$(this).removeClass("inactive");
$('.responsive-showcase img').removeClass("show");
$('.responsive-showcase img').addClass("hidden");
$('.responsive-showcase img' + device).toggleClass("hidden show");
$('.responsive-showcase img' + device).addClass("animated fadeIn");
return false;
});
/* ===== Services ===== */
$('.service-item').hover (function() {
$(this).children("i").toggleClass("fa-rotate-90");
return false;
});
| JavaScript |
$(function(){
$('#sidebar-nav').on('show.bs.tooltip', 'a', function(e) {
if($(e.currentTarget).find('span:visible').length) {
e.preventDefault();
return false;
}
});
});
var fancyFilter = function(filterListSelector, gallerySelector) {
//Filter Button Code
$(filterListSelector + ' a').click(function() {
$(filterListSelector + ' li').removeClass('active');
var $this = $(this);
var filterType = $this.data('filter');
if(!filterType) return true;
$this.closest('li').addClass('active');
$(gallerySelector).isotope({
filter: filterType,
});
return false;
});
};
| JavaScript |
/**
* @license wysihtml5 v0.3.0
* https://github.com/xing/wysihtml5
*
* Author: Christopher Blum (https://github.com/tiff)
*
* Copyright (C) 2012 XING AG
* Licensed under the MIT license (MIT)
*
*/
var wysihtml5 = {
version: "0.3.0",
// namespaces
commands: {},
dom: {},
quirks: {},
toolbar: {},
lang: {},
selection: {},
views: {},
INVISIBLE_SPACE: "\uFEFF",
EMPTY_FUNCTION: function() {},
ELEMENT_NODE: 1,
TEXT_NODE: 3,
BACKSPACE_KEY: 8,
ENTER_KEY: 13,
ESCAPE_KEY: 27,
SPACE_KEY: 32,
DELETE_KEY: 46
};/**
* @license Rangy, a cross-browser JavaScript range and selection library
* http://code.google.com/p/rangy/
*
* Copyright 2011, Tim Down
* Licensed under the MIT license.
* Version: 1.2.2
* Build date: 13 November 2011
*/
window['rangy'] = (function() {
var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined";
var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
"commonAncestorContainer", "START_TO_START", "START_TO_END", "END_TO_START", "END_TO_END"];
var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore",
"setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents",
"extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"];
var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"];
// Subset of TextRange's full set of methods that we're interested in
var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "getBookmark", "moveToBookmark",
"moveToElementText", "parentElement", "pasteHTML", "select", "setEndPoint", "getBoundingClientRect"];
/*----------------------------------------------------------------------------------------------------------------*/
// Trio of functions taken from Peter Michaux's article:
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(o, p) {
var t = typeof o[p];
return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown";
}
function isHostObject(o, p) {
return !!(typeof o[p] == OBJECT && o[p]);
}
function isHostProperty(o, p) {
return typeof o[p] != UNDEFINED;
}
// Creates a convenience function to save verbose repeated calls to tests functions
function createMultiplePropertyTest(testFunc) {
return function(o, props) {
var i = props.length;
while (i--) {
if (!testFunc(o, props[i])) {
return false;
}
}
return true;
};
}
// Next trio of functions are a convenience to save verbose repeated calls to previous two functions
var areHostMethods = createMultiplePropertyTest(isHostMethod);
var areHostObjects = createMultiplePropertyTest(isHostObject);
var areHostProperties = createMultiplePropertyTest(isHostProperty);
function isTextRange(range) {
return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);
}
var api = {
version: "1.2.2",
initialized: false,
supported: true,
util: {
isHostMethod: isHostMethod,
isHostObject: isHostObject,
isHostProperty: isHostProperty,
areHostMethods: areHostMethods,
areHostObjects: areHostObjects,
areHostProperties: areHostProperties,
isTextRange: isTextRange
},
features: {},
modules: {},
config: {
alertOnWarn: false,
preferTextRange: false
}
};
function fail(reason) {
window.alert("Rangy not supported in your browser. Reason: " + reason);
api.initialized = true;
api.supported = false;
}
api.fail = fail;
function warn(msg) {
var warningMessage = "Rangy warning: " + msg;
if (api.config.alertOnWarn) {
window.alert(warningMessage);
} else if (typeof window.console != UNDEFINED && typeof window.console.log != UNDEFINED) {
window.console.log(warningMessage);
}
}
api.warn = warn;
if ({}.hasOwnProperty) {
api.util.extend = function(o, props) {
for (var i in props) {
if (props.hasOwnProperty(i)) {
o[i] = props[i];
}
}
};
} else {
fail("hasOwnProperty not supported");
}
var initListeners = [];
var moduleInitializers = [];
// Initialization
function init() {
if (api.initialized) {
return;
}
var testRange;
var implementsDomRange = false, implementsTextRange = false;
// First, perform basic feature tests
if (isHostMethod(document, "createRange")) {
testRange = document.createRange();
if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {
implementsDomRange = true;
}
testRange.detach();
}
var body = isHostObject(document, "body") ? document.body : document.getElementsByTagName("body")[0];
if (body && isHostMethod(body, "createTextRange")) {
testRange = body.createTextRange();
if (isTextRange(testRange)) {
implementsTextRange = true;
}
}
if (!implementsDomRange && !implementsTextRange) {
fail("Neither Range nor TextRange are implemented");
}
api.initialized = true;
api.features = {
implementsDomRange: implementsDomRange,
implementsTextRange: implementsTextRange
};
// Initialize modules and call init listeners
var allListeners = moduleInitializers.concat(initListeners);
for (var i = 0, len = allListeners.length; i < len; ++i) {
try {
allListeners[i](api);
} catch (ex) {
if (isHostObject(window, "console") && isHostMethod(window.console, "log")) {
window.console.log("Init listener threw an exception. Continuing.", ex);
}
}
}
}
// Allow external scripts to initialize this library in case it's loaded after the document has loaded
api.init = init;
// Execute listener immediately if already initialized
api.addInitListener = function(listener) {
if (api.initialized) {
listener(api);
} else {
initListeners.push(listener);
}
};
var createMissingNativeApiListeners = [];
api.addCreateMissingNativeApiListener = function(listener) {
createMissingNativeApiListeners.push(listener);
};
function createMissingNativeApi(win) {
win = win || window;
init();
// Notify listeners
for (var i = 0, len = createMissingNativeApiListeners.length; i < len; ++i) {
createMissingNativeApiListeners[i](win);
}
}
api.createMissingNativeApi = createMissingNativeApi;
/**
* @constructor
*/
function Module(name) {
this.name = name;
this.initialized = false;
this.supported = false;
}
Module.prototype.fail = function(reason) {
this.initialized = true;
this.supported = false;
throw new Error("Module '" + this.name + "' failed to load: " + reason);
};
Module.prototype.warn = function(msg) {
api.warn("Module " + this.name + ": " + msg);
};
Module.prototype.createError = function(msg) {
return new Error("Error in Rangy " + this.name + " module: " + msg);
};
api.createModule = function(name, initFunc) {
var module = new Module(name);
api.modules[name] = module;
moduleInitializers.push(function(api) {
initFunc(api, module);
module.initialized = true;
module.supported = true;
});
};
api.requireModules = function(modules) {
for (var i = 0, len = modules.length, module, moduleName; i < len; ++i) {
moduleName = modules[i];
module = api.modules[moduleName];
if (!module || !(module instanceof Module)) {
throw new Error("Module '" + moduleName + "' not found");
}
if (!module.supported) {
throw new Error("Module '" + moduleName + "' not supported");
}
}
};
/*----------------------------------------------------------------------------------------------------------------*/
// Wait for document to load before running tests
var docReady = false;
var loadHandler = function(e) {
if (!docReady) {
docReady = true;
if (!api.initialized) {
init();
}
}
};
// Test whether we have window and document objects that we will need
if (typeof window == UNDEFINED) {
fail("No window found");
return;
}
if (typeof document == UNDEFINED) {
fail("No document found");
return;
}
if (isHostMethod(document, "addEventListener")) {
document.addEventListener("DOMContentLoaded", loadHandler, false);
}
// Add a fallback in case the DOMContentLoaded event isn't supported
if (isHostMethod(window, "addEventListener")) {
window.addEventListener("load", loadHandler, false);
} else if (isHostMethod(window, "attachEvent")) {
window.attachEvent("onload", loadHandler);
} else {
fail("Window does not have required addEventListener or attachEvent method");
}
return api;
})();
rangy.createModule("DomUtil", function(api, module) {
var UNDEF = "undefined";
var util = api.util;
// Perform feature tests
if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) {
module.fail("document missing a Node creation method");
}
if (!util.isHostMethod(document, "getElementsByTagName")) {
module.fail("document missing getElementsByTagName method");
}
var el = document.createElement("div");
if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) {
module.fail("Incomplete Element implementation");
}
// innerHTML is required for Range's createContextualFragment method
if (!util.isHostProperty(el, "innerHTML")) {
module.fail("Element is missing innerHTML property");
}
var textNode = document.createTextNode("test");
if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) ||
!util.areHostProperties(textNode, ["data"]))) {
module.fail("Incomplete Text Node implementation");
}
/*----------------------------------------------------------------------------------------------------------------*/
// Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been
// able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that
// contains just the document as a single element and the value searched for is the document.
var arrayContains = /*Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
}:*/
function(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
};
// Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI
function isHtmlNamespace(node) {
var ns;
return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml");
}
function parentElement(node) {
var parent = node.parentNode;
return (parent.nodeType == 1) ? parent : null;
}
function getNodeIndex(node) {
var i = 0;
while( (node = node.previousSibling) ) {
i++;
}
return i;
}
function getNodeLength(node) {
var childNodes;
return isCharacterDataNode(node) ? node.length : ((childNodes = node.childNodes) ? childNodes.length : 0);
}
function getCommonAncestor(node1, node2) {
var ancestors = [], n;
for (n = node1; n; n = n.parentNode) {
ancestors.push(n);
}
for (n = node2; n; n = n.parentNode) {
if (arrayContains(ancestors, n)) {
return n;
}
}
return null;
}
function isAncestorOf(ancestor, descendant, selfIsAncestor) {
var n = selfIsAncestor ? descendant : descendant.parentNode;
while (n) {
if (n === ancestor) {
return true;
} else {
n = n.parentNode;
}
}
return false;
}
function getClosestAncestorIn(node, ancestor, selfIsAncestor) {
var p, n = selfIsAncestor ? node : node.parentNode;
while (n) {
p = n.parentNode;
if (p === ancestor) {
return n;
}
n = p;
}
return null;
}
function isCharacterDataNode(node) {
var t = node.nodeType;
return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment
}
function insertAfter(node, precedingNode) {
var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
if (nextNode) {
parent.insertBefore(node, nextNode);
} else {
parent.appendChild(node);
}
return node;
}
// Note that we cannot use splitText() because it is bugridden in IE 9.
function splitDataNode(node, index) {
var newNode = node.cloneNode(false);
newNode.deleteData(0, index);
node.deleteData(index, node.length - index);
insertAfter(newNode, node);
return newNode;
}
function getDocument(node) {
if (node.nodeType == 9) {
return node;
} else if (typeof node.ownerDocument != UNDEF) {
return node.ownerDocument;
} else if (typeof node.document != UNDEF) {
return node.document;
} else if (node.parentNode) {
return getDocument(node.parentNode);
} else {
throw new Error("getDocument: no document found for node");
}
}
function getWindow(node) {
var doc = getDocument(node);
if (typeof doc.defaultView != UNDEF) {
return doc.defaultView;
} else if (typeof doc.parentWindow != UNDEF) {
return doc.parentWindow;
} else {
throw new Error("Cannot get a window object for node");
}
}
function getIframeDocument(iframeEl) {
if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument;
} else if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow.document;
} else {
throw new Error("getIframeWindow: No Document object found for iframe element");
}
}
function getIframeWindow(iframeEl) {
if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow;
} else if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument.defaultView;
} else {
throw new Error("getIframeWindow: No Window object found for iframe element");
}
}
function getBody(doc) {
return util.isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0];
}
function getRootContainer(node) {
var parent;
while ( (parent = node.parentNode) ) {
node = parent;
}
return node;
}
function comparePoints(nodeA, offsetA, nodeB, offsetB) {
// See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing
var nodeC, root, childA, childB, n;
if (nodeA == nodeB) {
// Case 1: nodes are the same
return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {
// Case 2: node C (container B or an ancestor) is a child node of A
return offsetA <= getNodeIndex(nodeC) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {
// Case 3: node C (container A or an ancestor) is a child node of B
return getNodeIndex(nodeC) < offsetB ? -1 : 1;
} else {
// Case 4: containers are siblings or descendants of siblings
root = getCommonAncestor(nodeA, nodeB);
childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);
childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);
if (childA === childB) {
// This shouldn't be possible
throw new Error("comparePoints got to case 4 and childA and childB are the same!");
} else {
n = root.firstChild;
while (n) {
if (n === childA) {
return -1;
} else if (n === childB) {
return 1;
}
n = n.nextSibling;
}
throw new Error("Should not be here!");
}
}
}
function fragmentFromNodeChildren(node) {
var fragment = getDocument(node).createDocumentFragment(), child;
while ( (child = node.firstChild) ) {
fragment.appendChild(child);
}
return fragment;
}
function inspectNode(node) {
if (!node) {
return "[No node]";
}
if (isCharacterDataNode(node)) {
return '"' + node.data + '"';
} else if (node.nodeType == 1) {
var idAttr = node.id ? ' id="' + node.id + '"' : "";
return "<" + node.nodeName + idAttr + ">[" + node.childNodes.length + "]";
} else {
return node.nodeName;
}
}
/**
* @constructor
*/
function NodeIterator(root) {
this.root = root;
this._next = root;
}
NodeIterator.prototype = {
_current: null,
hasNext: function() {
return !!this._next;
},
next: function() {
var n = this._current = this._next;
var child, next;
if (this._current) {
child = n.firstChild;
if (child) {
this._next = child;
} else {
next = null;
while ((n !== this.root) && !(next = n.nextSibling)) {
n = n.parentNode;
}
this._next = next;
}
}
return this._current;
},
detach: function() {
this._current = this._next = this.root = null;
}
};
function createIterator(root) {
return new NodeIterator(root);
}
/**
* @constructor
*/
function DomPosition(node, offset) {
this.node = node;
this.offset = offset;
}
DomPosition.prototype = {
equals: function(pos) {
return this.node === pos.node & this.offset == pos.offset;
},
inspect: function() {
return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]";
}
};
/**
* @constructor
*/
function DOMException(codeName) {
this.code = this[codeName];
this.codeName = codeName;
this.message = "DOMException: " + this.codeName;
}
DOMException.prototype = {
INDEX_SIZE_ERR: 1,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INVALID_STATE_ERR: 11
};
DOMException.prototype.toString = function() {
return this.message;
};
api.dom = {
arrayContains: arrayContains,
isHtmlNamespace: isHtmlNamespace,
parentElement: parentElement,
getNodeIndex: getNodeIndex,
getNodeLength: getNodeLength,
getCommonAncestor: getCommonAncestor,
isAncestorOf: isAncestorOf,
getClosestAncestorIn: getClosestAncestorIn,
isCharacterDataNode: isCharacterDataNode,
insertAfter: insertAfter,
splitDataNode: splitDataNode,
getDocument: getDocument,
getWindow: getWindow,
getIframeWindow: getIframeWindow,
getIframeDocument: getIframeDocument,
getBody: getBody,
getRootContainer: getRootContainer,
comparePoints: comparePoints,
inspectNode: inspectNode,
fragmentFromNodeChildren: fragmentFromNodeChildren,
createIterator: createIterator,
DomPosition: DomPosition
};
api.DOMException = DOMException;
});rangy.createModule("DomRange", function(api, module) {
api.requireModules( ["DomUtil"] );
var dom = api.dom;
var DomPosition = dom.DomPosition;
var DOMException = api.DOMException;
/*----------------------------------------------------------------------------------------------------------------*/
// Utility functions
function isNonTextPartiallySelected(node, range) {
return (node.nodeType != 3) &&
(dom.isAncestorOf(node, range.startContainer, true) || dom.isAncestorOf(node, range.endContainer, true));
}
function getRangeDocument(range) {
return dom.getDocument(range.startContainer);
}
function dispatchEvent(range, type, args) {
var listeners = range._listeners[type];
if (listeners) {
for (var i = 0, len = listeners.length; i < len; ++i) {
listeners[i].call(range, {target: range, args: args});
}
}
}
function getBoundaryBeforeNode(node) {
return new DomPosition(node.parentNode, dom.getNodeIndex(node));
}
function getBoundaryAfterNode(node) {
return new DomPosition(node.parentNode, dom.getNodeIndex(node) + 1);
}
function insertNodeAtPosition(node, n, o) {
var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;
if (dom.isCharacterDataNode(n)) {
if (o == n.length) {
dom.insertAfter(node, n);
} else {
n.parentNode.insertBefore(node, o == 0 ? n : dom.splitDataNode(n, o));
}
} else if (o >= n.childNodes.length) {
n.appendChild(node);
} else {
n.insertBefore(node, n.childNodes[o]);
}
return firstNodeInserted;
}
function cloneSubtree(iterator) {
var partiallySelected;
for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
partiallySelected = iterator.isPartiallySelectedSubtree();
node = node.cloneNode(!partiallySelected);
if (partiallySelected) {
subIterator = iterator.getSubtreeIterator();
node.appendChild(cloneSubtree(subIterator));
subIterator.detach(true);
}
if (node.nodeType == 10) { // DocumentType
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
frag.appendChild(node);
}
return frag;
}
function iterateSubtree(rangeIterator, func, iteratorState) {
var it, n;
iteratorState = iteratorState || { stop: false };
for (var node, subRangeIterator; node = rangeIterator.next(); ) {
//log.debug("iterateSubtree, partially selected: " + rangeIterator.isPartiallySelectedSubtree(), nodeToString(node));
if (rangeIterator.isPartiallySelectedSubtree()) {
// The node is partially selected by the Range, so we can use a new RangeIterator on the portion of the
// node selected by the Range.
if (func(node) === false) {
iteratorState.stop = true;
return;
} else {
subRangeIterator = rangeIterator.getSubtreeIterator();
iterateSubtree(subRangeIterator, func, iteratorState);
subRangeIterator.detach(true);
if (iteratorState.stop) {
return;
}
}
} else {
// The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its
// descendant
it = dom.createIterator(node);
while ( (n = it.next()) ) {
if (func(n) === false) {
iteratorState.stop = true;
return;
}
}
}
}
}
function deleteSubtree(iterator) {
var subIterator;
while (iterator.next()) {
if (iterator.isPartiallySelectedSubtree()) {
subIterator = iterator.getSubtreeIterator();
deleteSubtree(subIterator);
subIterator.detach(true);
} else {
iterator.remove();
}
}
}
function extractSubtree(iterator) {
for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
if (iterator.isPartiallySelectedSubtree()) {
node = node.cloneNode(false);
subIterator = iterator.getSubtreeIterator();
node.appendChild(extractSubtree(subIterator));
subIterator.detach(true);
} else {
iterator.remove();
}
if (node.nodeType == 10) { // DocumentType
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
frag.appendChild(node);
}
return frag;
}
function getNodesInRange(range, nodeTypes, filter) {
//log.info("getNodesInRange, " + nodeTypes.join(","));
var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;
var filterExists = !!filter;
if (filterNodeTypes) {
regex = new RegExp("^(" + nodeTypes.join("|") + ")$");
}
var nodes = [];
iterateSubtree(new RangeIterator(range, false), function(node) {
if ((!filterNodeTypes || regex.test(node.nodeType)) && (!filterExists || filter(node))) {
nodes.push(node);
}
});
return nodes;
}
function inspect(range) {
var name = (typeof range.getName == "undefined") ? "Range" : range.getName();
return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " +
dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]";
}
/*----------------------------------------------------------------------------------------------------------------*/
// RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)
/**
* @constructor
*/
function RangeIterator(range, clonePartiallySelectedTextNodes) {
this.range = range;
this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;
if (!range.collapsed) {
this.sc = range.startContainer;
this.so = range.startOffset;
this.ec = range.endContainer;
this.eo = range.endOffset;
var root = range.commonAncestorContainer;
if (this.sc === this.ec && dom.isCharacterDataNode(this.sc)) {
this.isSingleCharacterDataNode = true;
this._first = this._last = this._next = this.sc;
} else {
this._first = this._next = (this.sc === root && !dom.isCharacterDataNode(this.sc)) ?
this.sc.childNodes[this.so] : dom.getClosestAncestorIn(this.sc, root, true);
this._last = (this.ec === root && !dom.isCharacterDataNode(this.ec)) ?
this.ec.childNodes[this.eo - 1] : dom.getClosestAncestorIn(this.ec, root, true);
}
}
}
RangeIterator.prototype = {
_current: null,
_next: null,
_first: null,
_last: null,
isSingleCharacterDataNode: false,
reset: function() {
this._current = null;
this._next = this._first;
},
hasNext: function() {
return !!this._next;
},
next: function() {
// Move to next node
var current = this._current = this._next;
if (current) {
this._next = (current !== this._last) ? current.nextSibling : null;
// Check for partially selected text nodes
if (dom.isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {
if (current === this.ec) {
(current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);
}
if (this._current === this.sc) {
(current = current.cloneNode(true)).deleteData(0, this.so);
}
}
}
return current;
},
remove: function() {
var current = this._current, start, end;
if (dom.isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {
start = (current === this.sc) ? this.so : 0;
end = (current === this.ec) ? this.eo : current.length;
if (start != end) {
current.deleteData(start, end - start);
}
} else {
if (current.parentNode) {
current.parentNode.removeChild(current);
} else {
}
}
},
// Checks if the current node is partially selected
isPartiallySelectedSubtree: function() {
var current = this._current;
return isNonTextPartiallySelected(current, this.range);
},
getSubtreeIterator: function() {
var subRange;
if (this.isSingleCharacterDataNode) {
subRange = this.range.cloneRange();
subRange.collapse();
} else {
subRange = new Range(getRangeDocument(this.range));
var current = this._current;
var startContainer = current, startOffset = 0, endContainer = current, endOffset = dom.getNodeLength(current);
if (dom.isAncestorOf(current, this.sc, true)) {
startContainer = this.sc;
startOffset = this.so;
}
if (dom.isAncestorOf(current, this.ec, true)) {
endContainer = this.ec;
endOffset = this.eo;
}
updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);
}
return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);
},
detach: function(detachRange) {
if (detachRange) {
this.range.detach();
}
this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;
}
};
/*----------------------------------------------------------------------------------------------------------------*/
// Exceptions
/**
* @constructor
*/
function RangeException(codeName) {
this.code = this[codeName];
this.codeName = codeName;
this.message = "RangeException: " + this.codeName;
}
RangeException.prototype = {
BAD_BOUNDARYPOINTS_ERR: 1,
INVALID_NODE_TYPE_ERR: 2
};
RangeException.prototype.toString = function() {
return this.message;
};
/*----------------------------------------------------------------------------------------------------------------*/
/**
* Currently iterates through all nodes in the range on creation until I think of a decent way to do it
* TODO: Look into making this a proper iterator, not requiring preloading everything first
* @constructor
*/
function RangeNodeIterator(range, nodeTypes, filter) {
this.nodes = getNodesInRange(range, nodeTypes, filter);
this._next = this.nodes[0];
this._position = 0;
}
RangeNodeIterator.prototype = {
_current: null,
hasNext: function() {
return !!this._next;
},
next: function() {
this._current = this._next;
this._next = this.nodes[ ++this._position ];
return this._current;
},
detach: function() {
this._current = this._next = this.nodes = null;
}
};
var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];
var rootContainerNodeTypes = [2, 9, 11];
var readonlyNodeTypes = [5, 6, 10, 12];
var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];
var surroundNodeTypes = [1, 3, 4, 5, 7, 8];
function createAncestorFinder(nodeTypes) {
return function(node, selfIsAncestor) {
var t, n = selfIsAncestor ? node : node.parentNode;
while (n) {
t = n.nodeType;
if (dom.arrayContains(nodeTypes, t)) {
return n;
}
n = n.parentNode;
}
return null;
};
}
var getRootContainer = dom.getRootContainer;
var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );
var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);
var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );
function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {
if (getDocTypeNotationEntityAncestor(node, allowSelf)) {
throw new RangeException("INVALID_NODE_TYPE_ERR");
}
}
function assertNotDetached(range) {
if (!range.startContainer) {
throw new DOMException("INVALID_STATE_ERR");
}
}
function assertValidNodeType(node, invalidTypes) {
if (!dom.arrayContains(invalidTypes, node.nodeType)) {
throw new RangeException("INVALID_NODE_TYPE_ERR");
}
}
function assertValidOffset(node, offset) {
if (offset < 0 || offset > (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length)) {
throw new DOMException("INDEX_SIZE_ERR");
}
}
function assertSameDocumentOrFragment(node1, node2) {
if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
}
function assertNodeNotReadOnly(node) {
if (getReadonlyAncestor(node, true)) {
throw new DOMException("NO_MODIFICATION_ALLOWED_ERR");
}
}
function assertNode(node, codeName) {
if (!node) {
throw new DOMException(codeName);
}
}
function isOrphan(node) {
return !dom.arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true);
}
function isValidOffset(node, offset) {
return offset <= (dom.isCharacterDataNode(node) ? node.length : node.childNodes.length);
}
function assertRangeValid(range) {
assertNotDetached(range);
if (isOrphan(range.startContainer) || isOrphan(range.endContainer) ||
!isValidOffset(range.startContainer, range.startOffset) ||
!isValidOffset(range.endContainer, range.endOffset)) {
throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")");
}
}
/*----------------------------------------------------------------------------------------------------------------*/
// Test the browser's innerHTML support to decide how to implement createContextualFragment
var styleEl = document.createElement("style");
var htmlParsingConforms = false;
try {
styleEl.innerHTML = "<b>x</b>";
htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node
} catch (e) {
// IE 6 and 7 throw
}
api.features.htmlParsingConforms = htmlParsingConforms;
var createContextualFragment = htmlParsingConforms ?
// Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See
// discussion and base code for this implementation at issue 67.
// Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface
// Thanks to Aleks Williams.
function(fragmentStr) {
// "Let node the context object's start's node."
var node = this.startContainer;
var doc = dom.getDocument(node);
// "If the context object's start's node is null, raise an INVALID_STATE_ERR
// exception and abort these steps."
if (!node) {
throw new DOMException("INVALID_STATE_ERR");
}
// "Let element be as follows, depending on node's interface:"
// Document, Document Fragment: null
var el = null;
// "Element: node"
if (node.nodeType == 1) {
el = node;
// "Text, Comment: node's parentElement"
} else if (dom.isCharacterDataNode(node)) {
el = dom.parentElement(node);
}
// "If either element is null or element's ownerDocument is an HTML document
// and element's local name is "html" and element's namespace is the HTML
// namespace"
if (el === null || (
el.nodeName == "HTML"
&& dom.isHtmlNamespace(dom.getDocument(el).documentElement)
&& dom.isHtmlNamespace(el)
)) {
// "let element be a new Element with "body" as its local name and the HTML
// namespace as its namespace.""
el = doc.createElement("body");
} else {
el = el.cloneNode(false);
}
// "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm."
// "If the node's document is an XML document: Invoke the XML fragment parsing algorithm."
// "In either case, the algorithm must be invoked with fragment as the input
// and element as the context element."
el.innerHTML = fragmentStr;
// "If this raises an exception, then abort these steps. Otherwise, let new
// children be the nodes returned."
// "Let fragment be a new DocumentFragment."
// "Append all new children to fragment."
// "Return fragment."
return dom.fragmentFromNodeChildren(el);
} :
// In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that
// previous versions of Rangy used (with the exception of using a body element rather than a div)
function(fragmentStr) {
assertNotDetached(this);
var doc = getRangeDocument(this);
var el = doc.createElement("body");
el.innerHTML = fragmentStr;
return dom.fragmentFromNodeChildren(el);
};
/*----------------------------------------------------------------------------------------------------------------*/
var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
"commonAncestorContainer"];
var s2s = 0, s2e = 1, e2e = 2, e2s = 3;
var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;
function RangePrototype() {}
RangePrototype.prototype = {
attachListener: function(type, listener) {
this._listeners[type].push(listener);
},
compareBoundaryPoints: function(how, range) {
assertRangeValid(this);
assertSameDocumentOrFragment(this.startContainer, range.startContainer);
var nodeA, offsetA, nodeB, offsetB;
var prefixA = (how == e2s || how == s2s) ? "start" : "end";
var prefixB = (how == s2e || how == s2s) ? "start" : "end";
nodeA = this[prefixA + "Container"];
offsetA = this[prefixA + "Offset"];
nodeB = range[prefixB + "Container"];
offsetB = range[prefixB + "Offset"];
return dom.comparePoints(nodeA, offsetA, nodeB, offsetB);
},
insertNode: function(node) {
assertRangeValid(this);
assertValidNodeType(node, insertableNodeTypes);
assertNodeNotReadOnly(this.startContainer);
if (dom.isAncestorOf(node, this.startContainer, true)) {
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
// No check for whether the container of the start of the Range is of a type that does not allow
// children of the type of node: the browser's DOM implementation should do this for us when we attempt
// to add the node
var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);
this.setStartBefore(firstNodeInserted);
},
cloneContents: function() {
assertRangeValid(this);
var clone, frag;
if (this.collapsed) {
return getRangeDocument(this).createDocumentFragment();
} else {
if (this.startContainer === this.endContainer && dom.isCharacterDataNode(this.startContainer)) {
clone = this.startContainer.cloneNode(true);
clone.data = clone.data.slice(this.startOffset, this.endOffset);
frag = getRangeDocument(this).createDocumentFragment();
frag.appendChild(clone);
return frag;
} else {
var iterator = new RangeIterator(this, true);
clone = cloneSubtree(iterator);
iterator.detach();
}
return clone;
}
},
canSurroundContents: function() {
assertRangeValid(this);
assertNodeNotReadOnly(this.startContainer);
assertNodeNotReadOnly(this.endContainer);
// Check if the contents can be surrounded. Specifically, this means whether the range partially selects
// no non-text nodes.
var iterator = new RangeIterator(this, true);
var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
(iterator._last && isNonTextPartiallySelected(iterator._last, this)));
iterator.detach();
return !boundariesInvalid;
},
surroundContents: function(node) {
assertValidNodeType(node, surroundNodeTypes);
if (!this.canSurroundContents()) {
throw new RangeException("BAD_BOUNDARYPOINTS_ERR");
}
// Extract the contents
var content = this.extractContents();
// Clear the children of the node
if (node.hasChildNodes()) {
while (node.lastChild) {
node.removeChild(node.lastChild);
}
}
// Insert the new node and add the extracted contents
insertNodeAtPosition(node, this.startContainer, this.startOffset);
node.appendChild(content);
this.selectNode(node);
},
cloneRange: function() {
assertRangeValid(this);
var range = new Range(getRangeDocument(this));
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = this[prop];
}
return range;
},
toString: function() {
assertRangeValid(this);
var sc = this.startContainer;
if (sc === this.endContainer && dom.isCharacterDataNode(sc)) {
return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : "";
} else {
var textBits = [], iterator = new RangeIterator(this, true);
iterateSubtree(iterator, function(node) {
// Accept only text or CDATA nodes, not comments
if (node.nodeType == 3 || node.nodeType == 4) {
textBits.push(node.data);
}
});
iterator.detach();
return textBits.join("");
}
},
// The methods below are all non-standard. The following batch were introduced by Mozilla but have since
// been removed from Mozilla.
compareNode: function(node) {
assertRangeValid(this);
var parent = node.parentNode;
var nodeIndex = dom.getNodeIndex(node);
if (!parent) {
throw new DOMException("NOT_FOUND_ERR");
}
var startComparison = this.comparePoint(parent, nodeIndex),
endComparison = this.comparePoint(parent, nodeIndex + 1);
if (startComparison < 0) { // Node starts before
return (endComparison > 0) ? n_b_a : n_b;
} else {
return (endComparison > 0) ? n_a : n_i;
}
},
comparePoint: function(node, offset) {
assertRangeValid(this);
assertNode(node, "HIERARCHY_REQUEST_ERR");
assertSameDocumentOrFragment(node, this.startContainer);
if (dom.comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {
return -1;
} else if (dom.comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {
return 1;
}
return 0;
},
createContextualFragment: createContextualFragment,
toHtml: function() {
assertRangeValid(this);
var container = getRangeDocument(this).createElement("div");
container.appendChild(this.cloneContents());
return container.innerHTML;
},
// touchingIsIntersecting determines whether this method considers a node that borders a range intersects
// with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)
intersectsNode: function(node, touchingIsIntersecting) {
assertRangeValid(this);
assertNode(node, "NOT_FOUND_ERR");
if (dom.getDocument(node) !== getRangeDocument(this)) {
return false;
}
var parent = node.parentNode, offset = dom.getNodeIndex(node);
assertNode(parent, "NOT_FOUND_ERR");
var startComparison = dom.comparePoints(parent, offset, this.endContainer, this.endOffset),
endComparison = dom.comparePoints(parent, offset + 1, this.startContainer, this.startOffset);
return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
},
isPointInRange: function(node, offset) {
assertRangeValid(this);
assertNode(node, "HIERARCHY_REQUEST_ERR");
assertSameDocumentOrFragment(node, this.startContainer);
return (dom.comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&
(dom.comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);
},
// The methods below are non-standard and invented by me.
// Sharing a boundary start-to-end or end-to-start does not count as intersection.
intersectsRange: function(range, touchingIsIntersecting) {
assertRangeValid(this);
if (getRangeDocument(range) != getRangeDocument(this)) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.endContainer, range.endOffset),
endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.startContainer, range.startOffset);
return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
},
intersection: function(range) {
if (this.intersectsRange(range)) {
var startComparison = dom.comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),
endComparison = dom.comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);
var intersectionRange = this.cloneRange();
if (startComparison == -1) {
intersectionRange.setStart(range.startContainer, range.startOffset);
}
if (endComparison == 1) {
intersectionRange.setEnd(range.endContainer, range.endOffset);
}
return intersectionRange;
}
return null;
},
union: function(range) {
if (this.intersectsRange(range, true)) {
var unionRange = this.cloneRange();
if (dom.comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {
unionRange.setStart(range.startContainer, range.startOffset);
}
if (dom.comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {
unionRange.setEnd(range.endContainer, range.endOffset);
}
return unionRange;
} else {
throw new RangeException("Ranges do not intersect");
}
},
containsNode: function(node, allowPartial) {
if (allowPartial) {
return this.intersectsNode(node, false);
} else {
return this.compareNode(node) == n_i;
}
},
containsNodeContents: function(node) {
return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, dom.getNodeLength(node)) <= 0;
},
containsRange: function(range) {
return this.intersection(range).equals(range);
},
containsNodeText: function(node) {
var nodeRange = this.cloneRange();
nodeRange.selectNode(node);
var textNodes = nodeRange.getNodes([3]);
if (textNodes.length > 0) {
nodeRange.setStart(textNodes[0], 0);
var lastTextNode = textNodes.pop();
nodeRange.setEnd(lastTextNode, lastTextNode.length);
var contains = this.containsRange(nodeRange);
nodeRange.detach();
return contains;
} else {
return this.containsNodeContents(node);
}
},
createNodeIterator: function(nodeTypes, filter) {
assertRangeValid(this);
return new RangeNodeIterator(this, nodeTypes, filter);
},
getNodes: function(nodeTypes, filter) {
assertRangeValid(this);
return getNodesInRange(this, nodeTypes, filter);
},
getDocument: function() {
return getRangeDocument(this);
},
collapseBefore: function(node) {
assertNotDetached(this);
this.setEndBefore(node);
this.collapse(false);
},
collapseAfter: function(node) {
assertNotDetached(this);
this.setStartAfter(node);
this.collapse(true);
},
getName: function() {
return "DomRange";
},
equals: function(range) {
return Range.rangesEqual(this, range);
},
inspect: function() {
return inspect(this);
}
};
function copyComparisonConstantsToObject(obj) {
obj.START_TO_START = s2s;
obj.START_TO_END = s2e;
obj.END_TO_END = e2e;
obj.END_TO_START = e2s;
obj.NODE_BEFORE = n_b;
obj.NODE_AFTER = n_a;
obj.NODE_BEFORE_AND_AFTER = n_b_a;
obj.NODE_INSIDE = n_i;
}
function copyComparisonConstants(constructor) {
copyComparisonConstantsToObject(constructor);
copyComparisonConstantsToObject(constructor.prototype);
}
function createRangeContentRemover(remover, boundaryUpdater) {
return function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;
var iterator = new RangeIterator(this, true);
// Work out where to position the range after content removal
var node, boundary;
if (sc !== root) {
node = dom.getClosestAncestorIn(sc, root, true);
boundary = getBoundaryAfterNode(node);
sc = boundary.node;
so = boundary.offset;
}
// Check none of the range is read-only
iterateSubtree(iterator, assertNodeNotReadOnly);
iterator.reset();
// Remove the content
var returnValue = remover(iterator);
iterator.detach();
// Move to the new position
boundaryUpdater(this, sc, so, sc, so);
return returnValue;
};
}
function createPrototypeRange(constructor, boundaryUpdater, detacher) {
function createBeforeAfterNodeSetter(isBefore, isStart) {
return function(node) {
assertNotDetached(this);
assertValidNodeType(node, beforeAfterNodeTypes);
assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);
var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);
(isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);
};
}
function setRangeStart(range, node, offset) {
var ec = range.endContainer, eo = range.endOffset;
if (node !== range.startContainer || offset !== range.startOffset) {
// Check the root containers of the range and the new boundary, and also check whether the new boundary
// is after the current end. In either case, collapse the range to the new position
if (getRootContainer(node) != getRootContainer(ec) || dom.comparePoints(node, offset, ec, eo) == 1) {
ec = node;
eo = offset;
}
boundaryUpdater(range, node, offset, ec, eo);
}
}
function setRangeEnd(range, node, offset) {
var sc = range.startContainer, so = range.startOffset;
if (node !== range.endContainer || offset !== range.endOffset) {
// Check the root containers of the range and the new boundary, and also check whether the new boundary
// is after the current end. In either case, collapse the range to the new position
if (getRootContainer(node) != getRootContainer(sc) || dom.comparePoints(node, offset, sc, so) == -1) {
sc = node;
so = offset;
}
boundaryUpdater(range, sc, so, node, offset);
}
}
function setRangeStartAndEnd(range, node, offset) {
if (node !== range.startContainer || offset !== range.startOffset || node !== range.endContainer || offset !== range.endOffset) {
boundaryUpdater(range, node, offset, node, offset);
}
}
constructor.prototype = new RangePrototype();
api.util.extend(constructor.prototype, {
setStart: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeStart(this, node, offset);
},
setEnd: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeEnd(this, node, offset);
},
setStartBefore: createBeforeAfterNodeSetter(true, true),
setStartAfter: createBeforeAfterNodeSetter(false, true),
setEndBefore: createBeforeAfterNodeSetter(true, false),
setEndAfter: createBeforeAfterNodeSetter(false, false),
collapse: function(isStart) {
assertRangeValid(this);
if (isStart) {
boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);
} else {
boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);
}
},
selectNodeContents: function(node) {
// This doesn't seem well specified: the spec talks only about selecting the node's contents, which
// could be taken to mean only its children. However, browsers implement this the same as selectNode for
// text nodes, so I shall do likewise
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
boundaryUpdater(this, node, 0, node, dom.getNodeLength(node));
},
selectNode: function(node) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, false);
assertValidNodeType(node, beforeAfterNodeTypes);
var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);
boundaryUpdater(this, start.node, start.offset, end.node, end.offset);
},
extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),
deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),
canSurroundContents: function() {
assertRangeValid(this);
assertNodeNotReadOnly(this.startContainer);
assertNodeNotReadOnly(this.endContainer);
// Check if the contents can be surrounded. Specifically, this means whether the range partially selects
// no non-text nodes.
var iterator = new RangeIterator(this, true);
var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
(iterator._last && isNonTextPartiallySelected(iterator._last, this)));
iterator.detach();
return !boundariesInvalid;
},
detach: function() {
detacher(this);
},
splitBoundaries: function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
var startEndSame = (sc === ec);
if (dom.isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {
dom.splitDataNode(ec, eo);
}
if (dom.isCharacterDataNode(sc) && so > 0 && so < sc.length) {
sc = dom.splitDataNode(sc, so);
if (startEndSame) {
eo -= so;
ec = sc;
} else if (ec == sc.parentNode && eo >= dom.getNodeIndex(sc)) {
eo++;
}
so = 0;
}
boundaryUpdater(this, sc, so, ec, eo);
},
normalizeBoundaries: function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
var mergeForward = function(node) {
var sibling = node.nextSibling;
if (sibling && sibling.nodeType == node.nodeType) {
ec = node;
eo = node.length;
node.appendData(sibling.data);
sibling.parentNode.removeChild(sibling);
}
};
var mergeBackward = function(node) {
var sibling = node.previousSibling;
if (sibling && sibling.nodeType == node.nodeType) {
sc = node;
var nodeLength = node.length;
so = sibling.length;
node.insertData(0, sibling.data);
sibling.parentNode.removeChild(sibling);
if (sc == ec) {
eo += so;
ec = sc;
} else if (ec == node.parentNode) {
var nodeIndex = dom.getNodeIndex(node);
if (eo == nodeIndex) {
ec = node;
eo = nodeLength;
} else if (eo > nodeIndex) {
eo--;
}
}
}
};
var normalizeStart = true;
if (dom.isCharacterDataNode(ec)) {
if (ec.length == eo) {
mergeForward(ec);
}
} else {
if (eo > 0) {
var endNode = ec.childNodes[eo - 1];
if (endNode && dom.isCharacterDataNode(endNode)) {
mergeForward(endNode);
}
}
normalizeStart = !this.collapsed;
}
if (normalizeStart) {
if (dom.isCharacterDataNode(sc)) {
if (so == 0) {
mergeBackward(sc);
}
} else {
if (so < sc.childNodes.length) {
var startNode = sc.childNodes[so];
if (startNode && dom.isCharacterDataNode(startNode)) {
mergeBackward(startNode);
}
}
}
} else {
sc = ec;
so = eo;
}
boundaryUpdater(this, sc, so, ec, eo);
},
collapseToPoint: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeStartAndEnd(this, node, offset);
}
});
copyComparisonConstants(constructor);
}
/*----------------------------------------------------------------------------------------------------------------*/
// Updates commonAncestorContainer and collapsed after boundary change
function updateCollapsedAndCommonAncestor(range) {
range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
range.commonAncestorContainer = range.collapsed ?
range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);
}
function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {
var startMoved = (range.startContainer !== startContainer || range.startOffset !== startOffset);
var endMoved = (range.endContainer !== endContainer || range.endOffset !== endOffset);
range.startContainer = startContainer;
range.startOffset = startOffset;
range.endContainer = endContainer;
range.endOffset = endOffset;
updateCollapsedAndCommonAncestor(range);
dispatchEvent(range, "boundarychange", {startMoved: startMoved, endMoved: endMoved});
}
function detach(range) {
assertNotDetached(range);
range.startContainer = range.startOffset = range.endContainer = range.endOffset = null;
range.collapsed = range.commonAncestorContainer = null;
dispatchEvent(range, "detach", null);
range._listeners = null;
}
/**
* @constructor
*/
function Range(doc) {
this.startContainer = doc;
this.startOffset = 0;
this.endContainer = doc;
this.endOffset = 0;
this._listeners = {
boundarychange: [],
detach: []
};
updateCollapsedAndCommonAncestor(this);
}
createPrototypeRange(Range, updateBoundaries, detach);
api.rangePrototype = RangePrototype.prototype;
Range.rangeProperties = rangeProperties;
Range.RangeIterator = RangeIterator;
Range.copyComparisonConstants = copyComparisonConstants;
Range.createPrototypeRange = createPrototypeRange;
Range.inspect = inspect;
Range.getRangeDocument = getRangeDocument;
Range.rangesEqual = function(r1, r2) {
return r1.startContainer === r2.startContainer &&
r1.startOffset === r2.startOffset &&
r1.endContainer === r2.endContainer &&
r1.endOffset === r2.endOffset;
};
api.DomRange = Range;
api.RangeException = RangeException;
});rangy.createModule("WrappedRange", function(api, module) {
api.requireModules( ["DomUtil", "DomRange"] );
/**
* @constructor
*/
var WrappedRange;
var dom = api.dom;
var DomPosition = dom.DomPosition;
var DomRange = api.DomRange;
/*----------------------------------------------------------------------------------------------------------------*/
/*
This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()
method. For example, in the following (where pipes denote the selection boundaries):
<ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul>
var range = document.selection.createRange();
alert(range.parentElement().id); // Should alert "ul" but alerts "b"
This method returns the common ancestor node of the following:
- the parentElement() of the textRange
- the parentElement() of the textRange after calling collapse(true)
- the parentElement() of the textRange after calling collapse(false)
*/
function getTextRangeContainerElement(textRange) {
var parentEl = textRange.parentElement();
var range = textRange.duplicate();
range.collapse(true);
var startEl = range.parentElement();
range = textRange.duplicate();
range.collapse(false);
var endEl = range.parentElement();
var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);
return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);
}
function textRangeIsCollapsed(textRange) {
return textRange.compareEndPoints("StartToEnd", textRange) == 0;
}
// Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started out as
// an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) but has
// grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange bugs, handling
// for inputs and images, plus optimizations.
function getTextRangeBoundaryPosition(textRange, wholeRangeContainerElement, isStart, isCollapsed) {
var workingRange = textRange.duplicate();
workingRange.collapse(isStart);
var containerElement = workingRange.parentElement();
// Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so
// check for that
// TODO: Find out when. Workaround for wholeRangeContainerElement may break this
if (!dom.isAncestorOf(wholeRangeContainerElement, containerElement, true)) {
containerElement = wholeRangeContainerElement;
}
// Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and
// similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx
if (!containerElement.canHaveHTML) {
return new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));
}
var workingNode = dom.getDocument(containerElement).createElement("span");
var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd";
var previousNode, nextNode, boundaryPosition, boundaryNode;
// Move the working range through the container's children, starting at the end and working backwards, until the
// working range reaches or goes past the boundary we're interested in
do {
containerElement.insertBefore(workingNode, workingNode.previousSibling);
workingRange.moveToElementText(workingNode);
} while ( (comparison = workingRange.compareEndPoints(workingComparisonType, textRange)) > 0 &&
workingNode.previousSibling);
// We've now reached or gone past the boundary of the text range we're interested in
// so have identified the node we want
boundaryNode = workingNode.nextSibling;
if (comparison == -1 && boundaryNode && dom.isCharacterDataNode(boundaryNode)) {
// This is a character data node (text, comment, cdata). The working range is collapsed at the start of the
// node containing the text range's boundary, so we move the end of the working range to the boundary point
// and measure the length of its text to get the boundary's offset within the node.
workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange);
var offset;
if (/[\r\n]/.test(boundaryNode.data)) {
/*
For the particular case of a boundary within a text node containing line breaks (within a <pre> element,
for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts:
- Each line break is represented as \r in the text node's data/nodeValue properties
- Each line break is represented as \r\n in the TextRange's 'text' property
- The 'text' property of the TextRange does not contain trailing line breaks
To get round the problem presented by the final fact above, we can use the fact that TextRange's
moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily
the same as the number of characters it was instructed to move. The simplest approach is to use this to
store the characters moved when moving both the start and end of the range to the start of the document
body and subtracting the start offset from the end offset (the "move-negative-gazillion" method).
However, this is extremely slow when the document is large and the range is near the end of it. Clearly
doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same
problem.
Another approach that works is to use moveStart() to move the start boundary of the range up to the end
boundary one character at a time and incrementing a counter with the value returned by the moveStart()
call. However, the check for whether the start boundary has reached the end boundary is expensive, so
this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of
the range within the document).
The method below is a hybrid of the two methods above. It uses the fact that a string containing the
TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the
text of the TextRange, so the start of the range is moved that length initially and then a character at
a time to make up for any trailing line breaks not contained in the 'text' property. This has good
performance in most situations compared to the previous two methods.
*/
var tempRange = workingRange.duplicate();
var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length;
offset = tempRange.moveStart("character", rangeLength);
while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) {
offset++;
tempRange.moveStart("character", 1);
}
} else {
offset = workingRange.text.length;
}
boundaryPosition = new DomPosition(boundaryNode, offset);
} else {
// If the boundary immediately follows a character data node and this is the end boundary, we should favour
// a position within that, and likewise for a start boundary preceding a character data node
previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;
nextNode = (isCollapsed || isStart) && workingNode.nextSibling;
if (nextNode && dom.isCharacterDataNode(nextNode)) {
boundaryPosition = new DomPosition(nextNode, 0);
} else if (previousNode && dom.isCharacterDataNode(previousNode)) {
boundaryPosition = new DomPosition(previousNode, previousNode.length);
} else {
boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));
}
}
// Clean up
workingNode.parentNode.removeChild(workingNode);
return boundaryPosition;
}
// Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that node.
// This function started out as an optimized version of code found in Tim Cameron Ryan's IERange
// (http://code.google.com/p/ierange/)
function createBoundaryTextRange(boundaryPosition, isStart) {
var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;
var doc = dom.getDocument(boundaryPosition.node);
var workingNode, childNodes, workingRange = doc.body.createTextRange();
var nodeIsDataNode = dom.isCharacterDataNode(boundaryPosition.node);
if (nodeIsDataNode) {
boundaryNode = boundaryPosition.node;
boundaryParent = boundaryNode.parentNode;
} else {
childNodes = boundaryPosition.node.childNodes;
boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;
boundaryParent = boundaryPosition.node;
}
// Position the range immediately before the node containing the boundary
workingNode = doc.createElement("span");
// Making the working element non-empty element persuades IE to consider the TextRange boundary to be within the
// element rather than immediately before or after it, which is what we want
workingNode.innerHTML = "&#feff;";
// insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report
// for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12
if (boundaryNode) {
boundaryParent.insertBefore(workingNode, boundaryNode);
} else {
boundaryParent.appendChild(workingNode);
}
workingRange.moveToElementText(workingNode);
workingRange.collapse(!isStart);
// Clean up
boundaryParent.removeChild(workingNode);
// Move the working range to the text offset, if required
if (nodeIsDataNode) {
workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset);
}
return workingRange;
}
/*----------------------------------------------------------------------------------------------------------------*/
if (api.features.implementsDomRange && (!api.features.implementsTextRange || !api.config.preferTextRange)) {
// This is a wrapper around the browser's native DOM Range. It has two aims:
// - Provide workarounds for specific browser bugs
// - provide convenient extensions, which are inherited from Rangy's DomRange
(function() {
var rangeProto;
var rangeProperties = DomRange.rangeProperties;
var canSetRangeStartAfterEnd;
function updateRangeProperties(range) {
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = range.nativeRange[prop];
}
}
function updateNativeRange(range, startContainer, startOffset, endContainer,endOffset) {
var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);
var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);
// Always set both boundaries for the benefit of IE9 (see issue 35)
if (startMoved || endMoved) {
range.setEnd(endContainer, endOffset);
range.setStart(startContainer, startOffset);
}
}
function detach(range) {
range.nativeRange.detach();
range.detached = true;
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = null;
}
}
var createBeforeAfterNodeSetter;
WrappedRange = function(range) {
if (!range) {
throw new Error("Range must be specified");
}
this.nativeRange = range;
updateRangeProperties(this);
};
DomRange.createPrototypeRange(WrappedRange, updateNativeRange, detach);
rangeProto = WrappedRange.prototype;
rangeProto.selectNode = function(node) {
this.nativeRange.selectNode(node);
updateRangeProperties(this);
};
rangeProto.deleteContents = function() {
this.nativeRange.deleteContents();
updateRangeProperties(this);
};
rangeProto.extractContents = function() {
var frag = this.nativeRange.extractContents();
updateRangeProperties(this);
return frag;
};
rangeProto.cloneContents = function() {
return this.nativeRange.cloneContents();
};
// TODO: Until I can find a way to programmatically trigger the Firefox bug (apparently long-standing, still
// present in 3.6.8) that throws "Index or size is negative or greater than the allowed amount" for
// insertNode in some circumstances, all browsers will have to use the Rangy's own implementation of
// insertNode, which works but is almost certainly slower than the native implementation.
/*
rangeProto.insertNode = function(node) {
this.nativeRange.insertNode(node);
updateRangeProperties(this);
};
*/
rangeProto.surroundContents = function(node) {
this.nativeRange.surroundContents(node);
updateRangeProperties(this);
};
rangeProto.collapse = function(isStart) {
this.nativeRange.collapse(isStart);
updateRangeProperties(this);
};
rangeProto.cloneRange = function() {
return new WrappedRange(this.nativeRange.cloneRange());
};
rangeProto.refresh = function() {
updateRangeProperties(this);
};
rangeProto.toString = function() {
return this.nativeRange.toString();
};
// Create test range and node for feature detection
var testTextNode = document.createTextNode("test");
dom.getBody(document).appendChild(testTextNode);
var range = document.createRange();
/*--------------------------------------------------------------------------------------------------------*/
// Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and
// correct for it
range.setStart(testTextNode, 0);
range.setEnd(testTextNode, 0);
try {
range.setStart(testTextNode, 1);
canSetRangeStartAfterEnd = true;
rangeProto.setStart = function(node, offset) {
this.nativeRange.setStart(node, offset);
updateRangeProperties(this);
};
rangeProto.setEnd = function(node, offset) {
this.nativeRange.setEnd(node, offset);
updateRangeProperties(this);
};
createBeforeAfterNodeSetter = function(name) {
return function(node) {
this.nativeRange[name](node);
updateRangeProperties(this);
};
};
} catch(ex) {
canSetRangeStartAfterEnd = false;
rangeProto.setStart = function(node, offset) {
try {
this.nativeRange.setStart(node, offset);
} catch (ex) {
this.nativeRange.setEnd(node, offset);
this.nativeRange.setStart(node, offset);
}
updateRangeProperties(this);
};
rangeProto.setEnd = function(node, offset) {
try {
this.nativeRange.setEnd(node, offset);
} catch (ex) {
this.nativeRange.setStart(node, offset);
this.nativeRange.setEnd(node, offset);
}
updateRangeProperties(this);
};
createBeforeAfterNodeSetter = function(name, oppositeName) {
return function(node) {
try {
this.nativeRange[name](node);
} catch (ex) {
this.nativeRange[oppositeName](node);
this.nativeRange[name](node);
}
updateRangeProperties(this);
};
};
}
rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore");
rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter");
rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore");
rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter");
/*--------------------------------------------------------------------------------------------------------*/
// Test for and correct Firefox 2 behaviour with selectNodeContents on text nodes: it collapses the range to
// the 0th character of the text node
range.selectNodeContents(testTextNode);
if (range.startContainer == testTextNode && range.endContainer == testTextNode &&
range.startOffset == 0 && range.endOffset == testTextNode.length) {
rangeProto.selectNodeContents = function(node) {
this.nativeRange.selectNodeContents(node);
updateRangeProperties(this);
};
} else {
rangeProto.selectNodeContents = function(node) {
this.setStart(node, 0);
this.setEnd(node, DomRange.getEndOffset(node));
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Test for WebKit bug that has the beahviour of compareBoundaryPoints round the wrong way for constants
// START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738
range.selectNodeContents(testTextNode);
range.setEnd(testTextNode, 3);
var range2 = document.createRange();
range2.selectNodeContents(testTextNode);
range2.setEnd(testTextNode, 4);
range2.setStart(testTextNode, 2);
if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &
range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {
// This is the wrong way round, so correct for it
rangeProto.compareBoundaryPoints = function(type, range) {
range = range.nativeRange || range;
if (type == range.START_TO_END) {
type = range.END_TO_START;
} else if (type == range.END_TO_START) {
type = range.START_TO_END;
}
return this.nativeRange.compareBoundaryPoints(type, range);
};
} else {
rangeProto.compareBoundaryPoints = function(type, range) {
return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Test for existence of createContextualFragment and delegate to it if it exists
if (api.util.isHostMethod(range, "createContextualFragment")) {
rangeProto.createContextualFragment = function(fragmentStr) {
return this.nativeRange.createContextualFragment(fragmentStr);
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Clean up
dom.getBody(document).removeChild(testTextNode);
range.detach();
range2.detach();
})();
api.createNativeRange = function(doc) {
doc = doc || document;
return doc.createRange();
};
} else if (api.features.implementsTextRange) {
// This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a
// prototype
WrappedRange = function(textRange) {
this.textRange = textRange;
this.refresh();
};
WrappedRange.prototype = new DomRange(document);
WrappedRange.prototype.refresh = function() {
var start, end;
// TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.
var rangeContainerElement = getTextRangeContainerElement(this.textRange);
if (textRangeIsCollapsed(this.textRange)) {
end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true);
} else {
start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);
end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false);
}
this.setStart(start.node, start.offset);
this.setEnd(end.node, end.offset);
};
DomRange.copyComparisonConstants(WrappedRange);
// Add WrappedRange as the Range property of the global object to allow expression like Range.END_TO_END to work
var globalObj = (function() { return this; })();
if (typeof globalObj.Range == "undefined") {
globalObj.Range = WrappedRange;
}
api.createNativeRange = function(doc) {
doc = doc || document;
return doc.body.createTextRange();
};
}
if (api.features.implementsTextRange) {
WrappedRange.rangeToTextRange = function(range) {
if (range.collapsed) {
var tr = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
return tr;
//return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
} else {
var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);
var textRange = dom.getDocument(range.startContainer).body.createTextRange();
textRange.setEndPoint("StartToStart", startRange);
textRange.setEndPoint("EndToEnd", endRange);
return textRange;
}
};
}
WrappedRange.prototype.getName = function() {
return "WrappedRange";
};
api.WrappedRange = WrappedRange;
api.createRange = function(doc) {
doc = doc || document;
return new WrappedRange(api.createNativeRange(doc));
};
api.createRangyRange = function(doc) {
doc = doc || document;
return new DomRange(doc);
};
api.createIframeRange = function(iframeEl) {
return api.createRange(dom.getIframeDocument(iframeEl));
};
api.createIframeRangyRange = function(iframeEl) {
return api.createRangyRange(dom.getIframeDocument(iframeEl));
};
api.addCreateMissingNativeApiListener(function(win) {
var doc = win.document;
if (typeof doc.createRange == "undefined") {
doc.createRange = function() {
return api.createRange(this);
};
}
doc = win = null;
});
});rangy.createModule("WrappedSelection", function(api, module) {
// This will create a selection object wrapper that follows the Selection object found in the WHATWG draft DOM Range
// spec (http://html5.org/specs/dom-range.html)
api.requireModules( ["DomUtil", "DomRange", "WrappedRange"] );
api.config.checkSelectionRanges = true;
var BOOLEAN = "boolean",
windowPropertyName = "_rangySelection",
dom = api.dom,
util = api.util,
DomRange = api.DomRange,
WrappedRange = api.WrappedRange,
DOMException = api.DOMException,
DomPosition = dom.DomPosition,
getSelection,
selectionIsCollapsed,
CONTROL = "Control";
function getWinSelection(winParam) {
return (winParam || window).getSelection();
}
function getDocSelection(winParam) {
return (winParam || window).document.selection;
}
// Test for the Range/TextRange and Selection features required
// Test for ability to retrieve selection
var implementsWinGetSelection = api.util.isHostMethod(window, "getSelection"),
implementsDocSelection = api.util.isHostObject(document, "selection");
var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);
if (useDocumentSelection) {
getSelection = getDocSelection;
api.isSelectionValid = function(winParam) {
var doc = (winParam || window).document, nativeSel = doc.selection;
// Check whether the selection TextRange is actually contained within the correct document
return (nativeSel.type != "None" || dom.getDocument(nativeSel.createRange().parentElement()) == doc);
};
} else if (implementsWinGetSelection) {
getSelection = getWinSelection;
api.isSelectionValid = function() {
return true;
};
} else {
module.fail("Neither document.selection or window.getSelection() detected.");
}
api.getNativeSelection = getSelection;
var testSelection = getSelection();
var testRange = api.createNativeRange(document);
var body = dom.getBody(document);
// Obtaining a range from a selection
var selectionHasAnchorAndFocus = util.areHostObjects(testSelection, ["anchorNode", "focusNode"] &&
util.areHostProperties(testSelection, ["anchorOffset", "focusOffset"]));
api.features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;
// Test for existence of native selection extend() method
var selectionHasExtend = util.isHostMethod(testSelection, "extend");
api.features.selectionHasExtend = selectionHasExtend;
// Test if rangeCount exists
var selectionHasRangeCount = (typeof testSelection.rangeCount == "number");
api.features.selectionHasRangeCount = selectionHasRangeCount;
var selectionSupportsMultipleRanges = false;
var collapsedNonEditableSelectionsSupported = true;
if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) &&
typeof testSelection.rangeCount == "number" && api.features.implementsDomRange) {
(function() {
var iframe = document.createElement("iframe");
body.appendChild(iframe);
var iframeDoc = dom.getIframeDocument(iframe);
iframeDoc.open();
iframeDoc.write("<html><head></head><body>12</body></html>");
iframeDoc.close();
var sel = dom.getIframeWindow(iframe).getSelection();
var docEl = iframeDoc.documentElement;
var iframeBody = docEl.lastChild, textNode = iframeBody.firstChild;
// Test whether the native selection will allow a collapsed selection within a non-editable element
var r1 = iframeDoc.createRange();
r1.setStart(textNode, 1);
r1.collapse(true);
sel.addRange(r1);
collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
sel.removeAllRanges();
// Test whether the native selection is capable of supporting multiple ranges
var r2 = r1.cloneRange();
r1.setStart(textNode, 0);
r2.setEnd(textNode, 2);
sel.addRange(r1);
sel.addRange(r2);
selectionSupportsMultipleRanges = (sel.rangeCount == 2);
// Clean up
r1.detach();
r2.detach();
body.removeChild(iframe);
})();
}
api.features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;
api.features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;
// ControlRanges
var implementsControlRange = false, testControlRange;
if (body && util.isHostMethod(body, "createControlRange")) {
testControlRange = body.createControlRange();
if (util.areHostProperties(testControlRange, ["item", "add"])) {
implementsControlRange = true;
}
}
api.features.implementsControlRange = implementsControlRange;
// Selection collapsedness
if (selectionHasAnchorAndFocus) {
selectionIsCollapsed = function(sel) {
return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;
};
} else {
selectionIsCollapsed = function(sel) {
return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;
};
}
function updateAnchorAndFocusFromRange(sel, range, backwards) {
var anchorPrefix = backwards ? "end" : "start", focusPrefix = backwards ? "start" : "end";
sel.anchorNode = range[anchorPrefix + "Container"];
sel.anchorOffset = range[anchorPrefix + "Offset"];
sel.focusNode = range[focusPrefix + "Container"];
sel.focusOffset = range[focusPrefix + "Offset"];
}
function updateAnchorAndFocusFromNativeSelection(sel) {
var nativeSel = sel.nativeSelection;
sel.anchorNode = nativeSel.anchorNode;
sel.anchorOffset = nativeSel.anchorOffset;
sel.focusNode = nativeSel.focusNode;
sel.focusOffset = nativeSel.focusOffset;
}
function updateEmptySelection(sel) {
sel.anchorNode = sel.focusNode = null;
sel.anchorOffset = sel.focusOffset = 0;
sel.rangeCount = 0;
sel.isCollapsed = true;
sel._ranges.length = 0;
}
function getNativeRange(range) {
var nativeRange;
if (range instanceof DomRange) {
nativeRange = range._selectionNativeRange;
if (!nativeRange) {
nativeRange = api.createNativeRange(dom.getDocument(range.startContainer));
nativeRange.setEnd(range.endContainer, range.endOffset);
nativeRange.setStart(range.startContainer, range.startOffset);
range._selectionNativeRange = nativeRange;
range.attachListener("detach", function() {
this._selectionNativeRange = null;
});
}
} else if (range instanceof WrappedRange) {
nativeRange = range.nativeRange;
} else if (api.features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {
nativeRange = range;
}
return nativeRange;
}
function rangeContainsSingleElement(rangeNodes) {
if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {
return false;
}
for (var i = 1, len = rangeNodes.length; i < len; ++i) {
if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {
return false;
}
}
return true;
}
function getSingleElementFromRange(range) {
var nodes = range.getNodes();
if (!rangeContainsSingleElement(nodes)) {
throw new Error("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element");
}
return nodes[0];
}
function isTextRange(range) {
return !!range && typeof range.text != "undefined";
}
function updateFromTextRange(sel, range) {
// Create a Range from the selected TextRange
var wrappedRange = new WrappedRange(range);
sel._ranges = [wrappedRange];
updateAnchorAndFocusFromRange(sel, wrappedRange, false);
sel.rangeCount = 1;
sel.isCollapsed = wrappedRange.collapsed;
}
function updateControlSelection(sel) {
// Update the wrapped selection based on what's now in the native selection
sel._ranges.length = 0;
if (sel.docSelection.type == "None") {
updateEmptySelection(sel);
} else {
var controlRange = sel.docSelection.createRange();
if (isTextRange(controlRange)) {
// This case (where the selection type is "Control" and calling createRange() on the selection returns
// a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected
// ControlRange have been removed from the ControlRange and removed from the document.
updateFromTextRange(sel, controlRange);
} else {
sel.rangeCount = controlRange.length;
var range, doc = dom.getDocument(controlRange.item(0));
for (var i = 0; i < sel.rangeCount; ++i) {
range = api.createRange(doc);
range.selectNode(controlRange.item(i));
sel._ranges.push(range);
}
sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;
updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);
}
}
}
function addRangeToControlSelection(sel, range) {
var controlRange = sel.docSelection.createRange();
var rangeElement = getSingleElementFromRange(range);
// Create a new ControlRange containing all the elements in the selected ControlRange plus the element
// contained by the supplied range
var doc = dom.getDocument(controlRange.item(0));
var newControlRange = dom.getBody(doc).createControlRange();
for (var i = 0, len = controlRange.length; i < len; ++i) {
newControlRange.add(controlRange.item(i));
}
try {
newControlRange.add(rangeElement);
} catch (ex) {
throw new Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)");
}
newControlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(sel);
}
var getSelectionRangeAt;
if (util.isHostMethod(testSelection, "getRangeAt")) {
getSelectionRangeAt = function(sel, index) {
try {
return sel.getRangeAt(index);
} catch(ex) {
return null;
}
};
} else if (selectionHasAnchorAndFocus) {
getSelectionRangeAt = function(sel) {
var doc = dom.getDocument(sel.anchorNode);
var range = api.createRange(doc);
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the
// document)
if (range.collapsed !== this.isCollapsed) {
range.setStart(sel.focusNode, sel.focusOffset);
range.setEnd(sel.anchorNode, sel.anchorOffset);
}
return range;
};
}
/**
* @constructor
*/
function WrappedSelection(selection, docSelection, win) {
this.nativeSelection = selection;
this.docSelection = docSelection;
this._ranges = [];
this.win = win;
this.refresh();
}
api.getSelection = function(win) {
win = win || window;
var sel = win[windowPropertyName];
var nativeSel = getSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;
if (sel) {
sel.nativeSelection = nativeSel;
sel.docSelection = docSel;
sel.refresh(win);
} else {
sel = new WrappedSelection(nativeSel, docSel, win);
win[windowPropertyName] = sel;
}
return sel;
};
api.getIframeSelection = function(iframeEl) {
return api.getSelection(dom.getIframeWindow(iframeEl));
};
var selProto = WrappedSelection.prototype;
function createControlSelection(sel, ranges) {
// Ensure that the selection becomes of type "Control"
var doc = dom.getDocument(ranges[0].startContainer);
var controlRange = dom.getBody(doc).createControlRange();
for (var i = 0, el; i < rangeCount; ++i) {
el = getSingleElementFromRange(ranges[i]);
try {
controlRange.add(el);
} catch (ex) {
throw new Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)");
}
}
controlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(sel);
}
// Selecting a range
if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) {
selProto.removeAllRanges = function() {
this.nativeSelection.removeAllRanges();
updateEmptySelection(this);
};
var addRangeBackwards = function(sel, range) {
var doc = DomRange.getRangeDocument(range);
var endRange = api.createRange(doc);
endRange.collapseToPoint(range.endContainer, range.endOffset);
sel.nativeSelection.addRange(getNativeRange(endRange));
sel.nativeSelection.extend(range.startContainer, range.startOffset);
sel.refresh();
};
if (selectionHasRangeCount) {
selProto.addRange = function(range, backwards) {
if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
addRangeToControlSelection(this, range);
} else {
if (backwards && selectionHasExtend) {
addRangeBackwards(this, range);
} else {
var previousRangeCount;
if (selectionSupportsMultipleRanges) {
previousRangeCount = this.rangeCount;
} else {
this.removeAllRanges();
previousRangeCount = 0;
}
this.nativeSelection.addRange(getNativeRange(range));
// Check whether adding the range was successful
this.rangeCount = this.nativeSelection.rangeCount;
if (this.rangeCount == previousRangeCount + 1) {
// The range was added successfully
// Check whether the range that we added to the selection is reflected in the last range extracted from
// the selection
if (api.config.checkSelectionRanges) {
var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);
if (nativeRange && !DomRange.rangesEqual(nativeRange, range)) {
// Happens in WebKit with, for example, a selection placed at the start of a text node
range = new WrappedRange(nativeRange);
}
}
this._ranges[this.rangeCount - 1] = range;
updateAnchorAndFocusFromRange(this, range, selectionIsBackwards(this.nativeSelection));
this.isCollapsed = selectionIsCollapsed(this);
} else {
// The range was not added successfully. The simplest thing is to refresh
this.refresh();
}
}
}
};
} else {
selProto.addRange = function(range, backwards) {
if (backwards && selectionHasExtend) {
addRangeBackwards(this, range);
} else {
this.nativeSelection.addRange(getNativeRange(range));
this.refresh();
}
};
}
selProto.setRanges = function(ranges) {
if (implementsControlRange && ranges.length > 1) {
createControlSelection(this, ranges);
} else {
this.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
this.addRange(ranges[i]);
}
}
};
} else if (util.isHostMethod(testSelection, "empty") && util.isHostMethod(testRange, "select") &&
implementsControlRange && useDocumentSelection) {
selProto.removeAllRanges = function() {
// Added try/catch as fix for issue #21
try {
this.docSelection.empty();
// Check for empty() not working (issue #24)
if (this.docSelection.type != "None") {
// Work around failure to empty a control selection by instead selecting a TextRange and then
// calling empty()
var doc;
if (this.anchorNode) {
doc = dom.getDocument(this.anchorNode);
} else if (this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
if (controlRange.length) {
doc = dom.getDocument(controlRange.item(0)).body.createTextRange();
}
}
if (doc) {
var textRange = doc.body.createTextRange();
textRange.select();
this.docSelection.empty();
}
}
} catch(ex) {}
updateEmptySelection(this);
};
selProto.addRange = function(range) {
if (this.docSelection.type == CONTROL) {
addRangeToControlSelection(this, range);
} else {
WrappedRange.rangeToTextRange(range).select();
this._ranges[0] = range;
this.rangeCount = 1;
this.isCollapsed = this._ranges[0].collapsed;
updateAnchorAndFocusFromRange(this, range, false);
}
};
selProto.setRanges = function(ranges) {
this.removeAllRanges();
var rangeCount = ranges.length;
if (rangeCount > 1) {
createControlSelection(this, ranges);
} else if (rangeCount) {
this.addRange(ranges[0]);
}
};
} else {
module.fail("No means of selecting a Range or TextRange was found");
return false;
}
selProto.getRangeAt = function(index) {
if (index < 0 || index >= this.rangeCount) {
throw new DOMException("INDEX_SIZE_ERR");
} else {
return this._ranges[index];
}
};
var refreshSelection;
if (useDocumentSelection) {
refreshSelection = function(sel) {
var range;
if (api.isSelectionValid(sel.win)) {
range = sel.docSelection.createRange();
} else {
range = dom.getBody(sel.win.document).createTextRange();
range.collapse(true);
}
if (sel.docSelection.type == CONTROL) {
updateControlSelection(sel);
} else if (isTextRange(range)) {
updateFromTextRange(sel, range);
} else {
updateEmptySelection(sel);
}
};
} else if (util.isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == "number") {
refreshSelection = function(sel) {
if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {
updateControlSelection(sel);
} else {
sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));
}
updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackwards(sel.nativeSelection));
sel.isCollapsed = selectionIsCollapsed(sel);
} else {
updateEmptySelection(sel);
}
}
};
} else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && api.features.implementsDomRange) {
refreshSelection = function(sel) {
var range, nativeSel = sel.nativeSelection;
if (nativeSel.anchorNode) {
range = getSelectionRangeAt(nativeSel, 0);
sel._ranges = [range];
sel.rangeCount = 1;
updateAnchorAndFocusFromNativeSelection(sel);
sel.isCollapsed = selectionIsCollapsed(sel);
} else {
updateEmptySelection(sel);
}
};
} else {
module.fail("No means of obtaining a Range or TextRange from the user's selection was found");
return false;
}
selProto.refresh = function(checkForChanges) {
var oldRanges = checkForChanges ? this._ranges.slice(0) : null;
refreshSelection(this);
if (checkForChanges) {
var i = oldRanges.length;
if (i != this._ranges.length) {
return false;
}
while (i--) {
if (!DomRange.rangesEqual(oldRanges[i], this._ranges[i])) {
return false;
}
}
return true;
}
};
// Removal of a single range
var removeRangeManually = function(sel, range) {
var ranges = sel.getAllRanges(), removed = false;
sel.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
if (removed || range !== ranges[i]) {
sel.addRange(ranges[i]);
} else {
// According to the draft WHATWG Range spec, the same range may be added to the selection multiple
// times. removeRange should only remove the first instance, so the following ensures only the first
// instance is removed
removed = true;
}
}
if (!sel.rangeCount) {
updateEmptySelection(sel);
}
};
if (implementsControlRange) {
selProto.removeRange = function(range) {
if (this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
var rangeElement = getSingleElementFromRange(range);
// Create a new ControlRange containing all the elements in the selected ControlRange minus the
// element contained by the supplied range
var doc = dom.getDocument(controlRange.item(0));
var newControlRange = dom.getBody(doc).createControlRange();
var el, removed = false;
for (var i = 0, len = controlRange.length; i < len; ++i) {
el = controlRange.item(i);
if (el !== rangeElement || removed) {
newControlRange.add(controlRange.item(i));
} else {
removed = true;
}
}
newControlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(this);
} else {
removeRangeManually(this, range);
}
};
} else {
selProto.removeRange = function(range) {
removeRangeManually(this, range);
};
}
// Detecting if a selection is backwards
var selectionIsBackwards;
if (!useDocumentSelection && selectionHasAnchorAndFocus && api.features.implementsDomRange) {
selectionIsBackwards = function(sel) {
var backwards = false;
if (sel.anchorNode) {
backwards = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);
}
return backwards;
};
selProto.isBackwards = function() {
return selectionIsBackwards(this);
};
} else {
selectionIsBackwards = selProto.isBackwards = function() {
return false;
};
}
// Selection text
// This is conformant to the new WHATWG DOM Range draft spec but differs from WebKit and Mozilla's implementation
selProto.toString = function() {
var rangeTexts = [];
for (var i = 0, len = this.rangeCount; i < len; ++i) {
rangeTexts[i] = "" + this._ranges[i];
}
return rangeTexts.join("");
};
function assertNodeInSameDocument(sel, node) {
if (sel.anchorNode && (dom.getDocument(sel.anchorNode) !== dom.getDocument(node))) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
}
// No current browsers conform fully to the HTML 5 draft spec for this method, so Rangy's own method is always used
selProto.collapse = function(node, offset) {
assertNodeInSameDocument(this, node);
var range = api.createRange(dom.getDocument(node));
range.collapseToPoint(node, offset);
this.removeAllRanges();
this.addRange(range);
this.isCollapsed = true;
};
selProto.collapseToStart = function() {
if (this.rangeCount) {
var range = this._ranges[0];
this.collapse(range.startContainer, range.startOffset);
} else {
throw new DOMException("INVALID_STATE_ERR");
}
};
selProto.collapseToEnd = function() {
if (this.rangeCount) {
var range = this._ranges[this.rangeCount - 1];
this.collapse(range.endContainer, range.endOffset);
} else {
throw new DOMException("INVALID_STATE_ERR");
}
};
// The HTML 5 spec is very specific on how selectAllChildren should be implemented so the native implementation is
// never used by Rangy.
selProto.selectAllChildren = function(node) {
assertNodeInSameDocument(this, node);
var range = api.createRange(dom.getDocument(node));
range.selectNodeContents(node);
this.removeAllRanges();
this.addRange(range);
};
selProto.deleteFromDocument = function() {
// Sepcial behaviour required for Control selections
if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
var element;
while (controlRange.length) {
element = controlRange.item(0);
controlRange.remove(element);
element.parentNode.removeChild(element);
}
this.refresh();
} else if (this.rangeCount) {
var ranges = this.getAllRanges();
this.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
ranges[i].deleteContents();
}
// The HTML5 spec says nothing about what the selection should contain after calling deleteContents on each
// range. Firefox moves the selection to where the final selected range was, so we emulate that
this.addRange(ranges[len - 1]);
}
};
// The following are non-standard extensions
selProto.getAllRanges = function() {
return this._ranges.slice(0);
};
selProto.setSingleRange = function(range) {
this.setRanges( [range] );
};
selProto.containsNode = function(node, allowPartial) {
for (var i = 0, len = this._ranges.length; i < len; ++i) {
if (this._ranges[i].containsNode(node, allowPartial)) {
return true;
}
}
return false;
};
selProto.toHtml = function() {
var html = "";
if (this.rangeCount) {
var container = DomRange.getRangeDocument(this._ranges[0]).createElement("div");
for (var i = 0, len = this._ranges.length; i < len; ++i) {
container.appendChild(this._ranges[i].cloneContents());
}
html = container.innerHTML;
}
return html;
};
function inspect(sel) {
var rangeInspects = [];
var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);
var focus = new DomPosition(sel.focusNode, sel.focusOffset);
var name = (typeof sel.getName == "function") ? sel.getName() : "Selection";
if (typeof sel.rangeCount != "undefined") {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));
}
}
return "[" + name + "(Ranges: " + rangeInspects.join(", ") +
")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]";
}
selProto.getName = function() {
return "WrappedSelection";
};
selProto.inspect = function() {
return inspect(this);
};
selProto.detach = function() {
this.win[windowPropertyName] = null;
this.win = this.anchorNode = this.focusNode = null;
};
WrappedSelection.inspect = inspect;
api.Selection = WrappedSelection;
api.selectionPrototype = selProto;
api.addCreateMissingNativeApiListener(function(win) {
if (typeof win.getSelection == "undefined") {
win.getSelection = function() {
return api.getSelection(this);
};
}
win = null;
});
});
/*
Base.js, version 1.1a
Copyright 2006-2010, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
var Base = function() {
// dummy
};
Base.extend = function(_instance, _static) { // subclass
var extend = Base.prototype.extend;
// build the prototype
Base._prototyping = true;
var proto = new this;
extend.call(proto, _instance);
proto.base = function() {
// call this method from any other method to invoke that method's ancestor
};
delete Base._prototyping;
// create the wrapper for the constructor function
//var constructor = proto.constructor.valueOf(); //-dean
var constructor = proto.constructor;
var klass = proto.constructor = function() {
if (!Base._prototyping) {
if (this._constructing || this.constructor == klass) { // instantiation
this._constructing = true;
constructor.apply(this, arguments);
delete this._constructing;
} else if (arguments[0] != null) { // casting
return (arguments[0].extend || extend).call(arguments[0], proto);
}
}
};
// build the class interface
klass.ancestor = this;
klass.extend = this.extend;
klass.forEach = this.forEach;
klass.implement = this.implement;
klass.prototype = proto;
klass.toString = this.toString;
klass.valueOf = function(type) {
//return (type == "object") ? klass : constructor; //-dean
return (type == "object") ? klass : constructor.valueOf();
};
extend.call(klass, _static);
// class initialisation
if (typeof klass.init == "function") klass.init();
return klass;
};
Base.prototype = {
extend: function(source, value) {
if (arguments.length > 1) { // extending with a name/value pair
var ancestor = this[source];
if (ancestor && (typeof value == "function") && // overriding a method?
// the valueOf() comparison is to avoid circular references
(!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) &&
/\bbase\b/.test(value)) {
// get the underlying method
var method = value.valueOf();
// override
value = function() {
var previous = this.base || Base.prototype.base;
this.base = ancestor;
var returnValue = method.apply(this, arguments);
this.base = previous;
return returnValue;
};
// point to the underlying method
value.valueOf = function(type) {
return (type == "object") ? value : method;
};
value.toString = Base.toString;
}
this[source] = value;
} else if (source) { // extending with an object literal
var extend = Base.prototype.extend;
// if this object has a customised extend method then use it
if (!Base._prototyping && typeof this != "function") {
extend = this.extend || extend;
}
var proto = {toSource: null};
// do the "toString" and other methods manually
var hidden = ["constructor", "toString", "valueOf"];
// if we are prototyping then include the constructor
var i = Base._prototyping ? 0 : 1;
while (key = hidden[i++]) {
if (source[key] != proto[key]) {
extend.call(this, key, source[key]);
}
}
// copy each of the source object's properties to this object
for (var key in source) {
if (!proto[key]) extend.call(this, key, source[key]);
}
}
return this;
}
};
// initialise
Base = Base.extend({
constructor: function() {
this.extend(arguments[0]);
}
}, {
ancestor: Object,
version: "1.1",
forEach: function(object, block, context) {
for (var key in object) {
if (this.prototype[key] === undefined) {
block.call(context, object[key], key, object);
}
}
},
implement: function() {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "function") {
// if it's a function, call it
arguments[i](this.prototype);
} else {
// add the interface using the extend method
this.prototype.extend(arguments[i]);
}
}
return this;
},
toString: function() {
return String(this.valueOf());
}
});/**
* Detect browser support for specific features
*/
wysihtml5.browser = (function() {
var userAgent = navigator.userAgent,
testElement = document.createElement("div"),
// Browser sniffing is unfortunately needed since some behaviors are impossible to feature detect
isIE = userAgent.indexOf("MSIE") !== -1 && userAgent.indexOf("Opera") === -1,
isGecko = userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1,
isWebKit = userAgent.indexOf("AppleWebKit/") !== -1,
isChrome = userAgent.indexOf("Chrome/") !== -1,
isOpera = userAgent.indexOf("Opera/") !== -1;
function iosVersion(userAgent) {
return ((/ipad|iphone|ipod/.test(userAgent) && userAgent.match(/ os (\d+).+? like mac os x/)) || [, 0])[1];
}
return {
// Static variable needed, publicly accessible, to be able override it in unit tests
USER_AGENT: userAgent,
/**
* Exclude browsers that are not capable of displaying and handling
* contentEditable as desired:
* - iPhone, iPad (tested iOS 4.2.2) and Android (tested 2.2) refuse to make contentEditables focusable
* - IE < 8 create invalid markup and crash randomly from time to time
*
* @return {Boolean}
*/
supported: function() {
var userAgent = this.USER_AGENT.toLowerCase(),
// Essential for making html elements editable
hasContentEditableSupport = "contentEditable" in testElement,
// Following methods are needed in order to interact with the contentEditable area
hasEditingApiSupport = document.execCommand && document.queryCommandSupported && document.queryCommandState,
// document selector apis are only supported by IE 8+, Safari 4+, Chrome and Firefox 3.5+
hasQuerySelectorSupport = document.querySelector && document.querySelectorAll,
// contentEditable is unusable in mobile browsers (tested iOS 4.2.2, Android 2.2, Opera Mobile, WebOS 3.05)
isIncompatibleMobileBrowser = (this.isIos() && iosVersion(userAgent) < 5) || userAgent.indexOf("opera mobi") !== -1 || userAgent.indexOf("hpwos/") !== -1;
return hasContentEditableSupport
&& hasEditingApiSupport
&& hasQuerySelectorSupport
&& !isIncompatibleMobileBrowser;
},
isTouchDevice: function() {
return this.supportsEvent("touchmove");
},
isIos: function() {
var userAgent = this.USER_AGENT.toLowerCase();
return userAgent.indexOf("webkit") !== -1 && userAgent.indexOf("mobile") !== -1;
},
/**
* Whether the browser supports sandboxed iframes
* Currently only IE 6+ offers such feature <iframe security="restricted">
*
* http://msdn.microsoft.com/en-us/library/ms534622(v=vs.85).aspx
* http://blogs.msdn.com/b/ie/archive/2008/01/18/using-frames-more-securely.aspx
*
* HTML5 sandboxed iframes are still buggy and their DOM is not reachable from the outside (except when using postMessage)
*/
supportsSandboxedIframes: function() {
return isIE;
},
/**
* IE6+7 throw a mixed content warning when the src of an iframe
* is empty/unset or about:blank
* window.querySelector is implemented as of IE8
*/
throwsMixedContentWarningWhenIframeSrcIsEmpty: function() {
return !("querySelector" in document);
},
/**
* Whether the caret is correctly displayed in contentEditable elements
* Firefox sometimes shows a huge caret in the beginning after focusing
*/
displaysCaretInEmptyContentEditableCorrectly: function() {
return !isGecko;
},
/**
* Opera and IE are the only browsers who offer the css value
* in the original unit, thx to the currentStyle object
* All other browsers provide the computed style in px via window.getComputedStyle
*/
hasCurrentStyleProperty: function() {
return "currentStyle" in testElement;
},
/**
* Whether the browser inserts a <br> when pressing enter in a contentEditable element
*/
insertsLineBreaksOnReturn: function() {
return isGecko;
},
supportsPlaceholderAttributeOn: function(element) {
return "placeholder" in element;
},
supportsEvent: function(eventName) {
return "on" + eventName in testElement || (function() {
testElement.setAttribute("on" + eventName, "return;");
return typeof(testElement["on" + eventName]) === "function";
})();
},
/**
* Opera doesn't correctly fire focus/blur events when clicking in- and outside of iframe
*/
supportsEventsInIframeCorrectly: function() {
return !isOpera;
},
/**
* Chrome & Safari only fire the ondrop/ondragend/... events when the ondragover event is cancelled
* with event.preventDefault
* Firefox 3.6 fires those events anyway, but the mozilla doc says that the dragover/dragenter event needs
* to be cancelled
*/
firesOnDropOnlyWhenOnDragOverIsCancelled: function() {
return isWebKit || isGecko;
},
/**
* Whether the browser supports the event.dataTransfer property in a proper way
*/
supportsDataTransfer: function() {
try {
// Firefox doesn't support dataTransfer in a safe way, it doesn't strip script code in the html payload (like Chrome does)
return isWebKit && (window.Clipboard || window.DataTransfer).prototype.getData;
} catch(e) {
return false;
}
},
/**
* Everything below IE9 doesn't know how to treat HTML5 tags
*
* @param {Object} context The document object on which to check HTML5 support
*
* @example
* wysihtml5.browser.supportsHTML5Tags(document);
*/
supportsHTML5Tags: function(context) {
var element = context.createElement("div"),
html5 = "<article>foo</article>";
element.innerHTML = html5;
return element.innerHTML.toLowerCase() === html5;
},
/**
* Checks whether a document supports a certain queryCommand
* In particular, Opera needs a reference to a document that has a contentEditable in it's dom tree
* in oder to report correct results
*
* @param {Object} doc Document object on which to check for a query command
* @param {String} command The query command to check for
* @return {Boolean}
*
* @example
* wysihtml5.browser.supportsCommand(document, "bold");
*/
supportsCommand: (function() {
// Following commands are supported but contain bugs in some browsers
var buggyCommands = {
// formatBlock fails with some tags (eg. <blockquote>)
"formatBlock": isIE,
// When inserting unordered or ordered lists in Firefox, Chrome or Safari, the current selection or line gets
// converted into a list (<ul><li>...</li></ul>, <ol><li>...</li></ol>)
// IE and Opera act a bit different here as they convert the entire content of the current block element into a list
"insertUnorderedList": isIE || isOpera || isWebKit,
"insertOrderedList": isIE || isOpera || isWebKit
};
// Firefox throws errors for queryCommandSupported, so we have to build up our own object of supported commands
var supported = {
"insertHTML": isGecko
};
return function(doc, command) {
var isBuggy = buggyCommands[command];
if (!isBuggy) {
// Firefox throws errors when invoking queryCommandSupported or queryCommandEnabled
try {
return doc.queryCommandSupported(command);
} catch(e1) {}
try {
return doc.queryCommandEnabled(command);
} catch(e2) {
return !!supported[command];
}
}
return false;
};
})(),
/**
* IE: URLs starting with:
* www., http://, https://, ftp://, gopher://, mailto:, new:, snews:, telnet:, wasis:, file://,
* nntp://, newsrc:, ldap://, ldaps://, outlook:, mic:// and url:
* will automatically be auto-linked when either the user inserts them via copy&paste or presses the
* space bar when the caret is directly after such an url.
* This behavior cannot easily be avoided in IE < 9 since the logic is hardcoded in the mshtml.dll
* (related blog post on msdn
* http://blogs.msdn.com/b/ieinternals/archive/2009/09/17/prevent-automatic-hyperlinking-in-contenteditable-html.aspx).
*/
doesAutoLinkingInContentEditable: function() {
return isIE;
},
/**
* As stated above, IE auto links urls typed into contentEditable elements
* Since IE9 it's possible to prevent this behavior
*/
canDisableAutoLinking: function() {
return this.supportsCommand(document, "AutoUrlDetect");
},
/**
* IE leaves an empty paragraph in the contentEditable element after clearing it
* Chrome/Safari sometimes an empty <div>
*/
clearsContentEditableCorrectly: function() {
return isGecko || isOpera || isWebKit;
},
/**
* IE gives wrong results for getAttribute
*/
supportsGetAttributeCorrectly: function() {
var td = document.createElement("td");
return td.getAttribute("rowspan") != "1";
},
/**
* When clicking on images in IE, Opera and Firefox, they are selected, which makes it easy to interact with them.
* Chrome and Safari both don't support this
*/
canSelectImagesInContentEditable: function() {
return isGecko || isIE || isOpera;
},
/**
* When the caret is in an empty list (<ul><li>|</li></ul>) which is the first child in an contentEditable container
* pressing backspace doesn't remove the entire list as done in other browsers
*/
clearsListsInContentEditableCorrectly: function() {
return isGecko || isIE || isWebKit;
},
/**
* All browsers except Safari and Chrome automatically scroll the range/caret position into view
*/
autoScrollsToCaret: function() {
return !isWebKit;
},
/**
* Check whether the browser automatically closes tags that don't need to be opened
*/
autoClosesUnclosedTags: function() {
var clonedTestElement = testElement.cloneNode(false),
returnValue,
innerHTML;
clonedTestElement.innerHTML = "<p><div></div>";
innerHTML = clonedTestElement.innerHTML.toLowerCase();
returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>";
// Cache result by overwriting current function
this.autoClosesUnclosedTags = function() { return returnValue; };
return returnValue;
},
/**
* Whether the browser supports the native document.getElementsByClassName which returns live NodeLists
*/
supportsNativeGetElementsByClassName: function() {
return String(document.getElementsByClassName).indexOf("[native code]") !== -1;
},
/**
* As of now (19.04.2011) only supported by Firefox 4 and Chrome
* See https://developer.mozilla.org/en/DOM/Selection/modify
*/
supportsSelectionModify: function() {
return "getSelection" in window && "modify" in window.getSelection();
},
/**
* Whether the browser supports the classList object for fast className manipulation
* See https://developer.mozilla.org/en/DOM/element.classList
*/
supportsClassList: function() {
return "classList" in testElement;
},
/**
* Opera needs a white space after a <br> in order to position the caret correctly
*/
needsSpaceAfterLineBreak: function() {
return isOpera;
},
/**
* Whether the browser supports the speech api on the given element
* See http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/
*
* @example
* var input = document.createElement("input");
* if (wysihtml5.browser.supportsSpeechApiOn(input)) {
* // ...
* }
*/
supportsSpeechApiOn: function(input) {
var chromeVersion = userAgent.match(/Chrome\/(\d+)/) || [, 0];
return chromeVersion[1] >= 11 && ("onwebkitspeechchange" in input || "speech" in input);
},
/**
* IE9 crashes when setting a getter via Object.defineProperty on XMLHttpRequest or XDomainRequest
* See https://connect.microsoft.com/ie/feedback/details/650112
* or try the POC http://tifftiff.de/ie9_crash/
*/
crashesWhenDefineProperty: function(property) {
return isIE && (property === "XMLHttpRequest" || property === "XDomainRequest");
},
/**
* IE is the only browser who fires the "focus" event not immediately when .focus() is called on an element
*/
doesAsyncFocus: function() {
return isIE;
},
/**
* In IE it's impssible for the user and for the selection library to set the caret after an <img> when it's the lastChild in the document
*/
hasProblemsSettingCaretAfterImg: function() {
return isIE;
},
hasUndoInContextMenu: function() {
return isGecko || isChrome || isOpera;
}
};
})();wysihtml5.lang.array = function(arr) {
return {
/**
* Check whether a given object exists in an array
*
* @example
* wysihtml5.lang.array([1, 2]).contains(1);
* // => true
*/
contains: function(needle) {
if (arr.indexOf) {
return arr.indexOf(needle) !== -1;
} else {
for (var i=0, length=arr.length; i<length; i++) {
if (arr[i] === needle) { return true; }
}
return false;
}
},
/**
* Substract one array from another
*
* @example
* wysihtml5.lang.array([1, 2, 3, 4]).without([3, 4]);
* // => [1, 2]
*/
without: function(arrayToSubstract) {
arrayToSubstract = wysihtml5.lang.array(arrayToSubstract);
var newArr = [],
i = 0,
length = arr.length;
for (; i<length; i++) {
if (!arrayToSubstract.contains(arr[i])) {
newArr.push(arr[i]);
}
}
return newArr;
},
/**
* Return a clean native array
*
* Following will convert a Live NodeList to a proper Array
* @example
* var childNodes = wysihtml5.lang.array(document.body.childNodes).get();
*/
get: function() {
var i = 0,
length = arr.length,
newArray = [];
for (; i<length; i++) {
newArray.push(arr[i]);
}
return newArray;
}
};
};wysihtml5.lang.Dispatcher = Base.extend(
/** @scope wysihtml5.lang.Dialog.prototype */ {
observe: function(eventName, handler) {
this.events = this.events || {};
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(handler);
return this;
},
on: function() {
return this.observe.apply(this, wysihtml5.lang.array(arguments).get());
},
fire: function(eventName, payload) {
this.events = this.events || {};
var handlers = this.events[eventName] || [],
i = 0;
for (; i<handlers.length; i++) {
handlers[i].call(this, payload);
}
return this;
},
stopObserving: function(eventName, handler) {
this.events = this.events || {};
var i = 0,
handlers,
newHandlers;
if (eventName) {
handlers = this.events[eventName] || [],
newHandlers = [];
for (; i<handlers.length; i++) {
if (handlers[i] !== handler && handler) {
newHandlers.push(handlers[i]);
}
}
this.events[eventName] = newHandlers;
} else {
// Clean up all events
this.events = {};
}
return this;
}
});wysihtml5.lang.object = function(obj) {
return {
/**
* @example
* wysihtml5.lang.object({ foo: 1, bar: 1 }).merge({ bar: 2, baz: 3 }).get();
* // => { foo: 1, bar: 2, baz: 3 }
*/
merge: function(otherObj) {
for (var i in otherObj) {
obj[i] = otherObj[i];
}
return this;
},
get: function() {
return obj;
},
/**
* @example
* wysihtml5.lang.object({ foo: 1 }).clone();
* // => { foo: 1 }
*/
clone: function() {
var newObj = {},
i;
for (i in obj) {
newObj[i] = obj[i];
}
return newObj;
},
/**
* @example
* wysihtml5.lang.object([]).isArray();
* // => true
*/
isArray: function() {
return Object.prototype.toString.call(obj) === "[object Array]";
}
};
};(function() {
var WHITE_SPACE_START = /^\s+/,
WHITE_SPACE_END = /\s+$/;
wysihtml5.lang.string = function(str) {
str = String(str);
return {
/**
* @example
* wysihtml5.lang.string(" foo ").trim();
* // => "foo"
*/
trim: function() {
return str.replace(WHITE_SPACE_START, "").replace(WHITE_SPACE_END, "");
},
/**
* @example
* wysihtml5.lang.string("Hello #{name}").interpolate({ name: "Christopher" });
* // => "Hello Christopher"
*/
interpolate: function(vars) {
for (var i in vars) {
str = this.replace("#{" + i + "}").by(vars[i]);
}
return str;
},
/**
* @example
* wysihtml5.lang.string("Hello Tom").replace("Tom").with("Hans");
* // => "Hello Hans"
*/
replace: function(search) {
return {
by: function(replace) {
return str.split(search).join(replace);
}
}
}
};
};
})();/**
* Find urls in descendant text nodes of an element and auto-links them
* Inspired by http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/
*
* @param {Element} element Container element in which to search for urls
*
* @example
* <div id="text-container">Please click here: www.google.com</div>
* <script>wysihtml5.dom.autoLink(document.getElementById("text-container"));</script>
*/
(function(wysihtml5) {
var /**
* Don't auto-link urls that are contained in the following elements:
*/
IGNORE_URLS_IN = wysihtml5.lang.array(["CODE", "PRE", "A", "SCRIPT", "HEAD", "TITLE", "STYLE"]),
/**
* revision 1:
* /(\S+\.{1}[^\s\,\.\!]+)/g
*
* revision 2:
* /(\b(((https?|ftp):\/\/)|(www\.))[-A-Z0-9+&@#\/%?=~_|!:,.;\[\]]*[-A-Z0-9+&@#\/%=~_|])/gim
*
* put this in the beginning if you don't wan't to match within a word
* (^|[\>\(\{\[\s\>])
*/
URL_REG_EXP = /((https?:\/\/|www\.)[^\s<]{3,})/gi,
TRAILING_CHAR_REG_EXP = /([^\w\/\-](,?))$/i,
MAX_DISPLAY_LENGTH = 100,
BRACKETS = { ")": "(", "]": "[", "}": "{" };
function autoLink(element) {
if (_hasParentThatShouldBeIgnored(element)) {
return element;
}
if (element === element.ownerDocument.documentElement) {
element = element.ownerDocument.body;
}
return _parseNode(element);
}
/**
* This is basically a rebuild of
* the rails auto_link_urls text helper
*/
function _convertUrlsToLinks(str) {
return str.replace(URL_REG_EXP, function(match, url) {
var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "",
opening = BRACKETS[punctuation];
url = url.replace(TRAILING_CHAR_REG_EXP, "");
if (url.split(opening).length > url.split(punctuation).length) {
url = url + punctuation;
punctuation = "";
}
var realUrl = url,
displayUrl = url;
if (url.length > MAX_DISPLAY_LENGTH) {
displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "...";
}
// Add http prefix if necessary
if (realUrl.substr(0, 4) === "www.") {
realUrl = "http://" + realUrl;
}
return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation;
});
}
/**
* Creates or (if already cached) returns a temp element
* for the given document object
*/
function _getTempElement(context) {
var tempElement = context._wysihtml5_tempElement;
if (!tempElement) {
tempElement = context._wysihtml5_tempElement = context.createElement("div");
}
return tempElement;
}
/**
* Replaces the original text nodes with the newly auto-linked dom tree
*/
function _wrapMatchesInNode(textNode) {
var parentNode = textNode.parentNode,
tempElement = _getTempElement(parentNode.ownerDocument);
// We need to insert an empty/temporary <span /> to fix IE quirks
// Elsewise IE would strip white space in the beginning
tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(textNode.data);
tempElement.removeChild(tempElement.firstChild);
while (tempElement.firstChild) {
// inserts tempElement.firstChild before textNode
parentNode.insertBefore(tempElement.firstChild, textNode);
}
parentNode.removeChild(textNode);
}
function _hasParentThatShouldBeIgnored(node) {
var nodeName;
while (node.parentNode) {
node = node.parentNode;
nodeName = node.nodeName;
if (IGNORE_URLS_IN.contains(nodeName)) {
return true;
} else if (nodeName === "body") {
return false;
}
}
return false;
}
function _parseNode(element) {
if (IGNORE_URLS_IN.contains(element.nodeName)) {
return;
}
if (element.nodeType === wysihtml5.TEXT_NODE && element.data.match(URL_REG_EXP)) {
_wrapMatchesInNode(element);
return;
}
var childNodes = wysihtml5.lang.array(element.childNodes).get(),
childNodesLength = childNodes.length,
i = 0;
for (; i<childNodesLength; i++) {
_parseNode(childNodes[i]);
}
return element;
}
wysihtml5.dom.autoLink = autoLink;
// Reveal url reg exp to the outside
wysihtml5.dom.autoLink.URL_REG_EXP = URL_REG_EXP;
})(wysihtml5);(function(wysihtml5) {
var supportsClassList = wysihtml5.browser.supportsClassList(),
api = wysihtml5.dom;
api.addClass = function(element, className) {
if (supportsClassList) {
return element.classList.add(className);
}
if (api.hasClass(element, className)) {
return;
}
element.className += " " + className;
};
api.removeClass = function(element, className) {
if (supportsClassList) {
return element.classList.remove(className);
}
element.className = element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " ");
};
api.hasClass = function(element, className) {
if (supportsClassList) {
return element.classList.contains(className);
}
var elementClassName = element.className;
return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
};
})(wysihtml5);
wysihtml5.dom.contains = (function() {
var documentElement = document.documentElement;
if (documentElement.contains) {
return function(container, element) {
if (element.nodeType !== wysihtml5.ELEMENT_NODE) {
element = element.parentNode;
}
return container !== element && container.contains(element);
};
} else if (documentElement.compareDocumentPosition) {
return function(container, element) {
// https://developer.mozilla.org/en/DOM/Node.compareDocumentPosition
return !!(container.compareDocumentPosition(element) & 16);
};
}
})();/**
* Converts an HTML fragment/element into a unordered/ordered list
*
* @param {Element} element The element which should be turned into a list
* @param {String} listType The list type in which to convert the tree (either "ul" or "ol")
* @return {Element} The created list
*
* @example
* <!-- Assume the following dom: -->
* <span id="pseudo-list">
* eminem<br>
* dr. dre
* <div>50 Cent</div>
* </span>
*
* <script>
* wysihtml5.dom.convertToList(document.getElementById("pseudo-list"), "ul");
* </script>
*
* <!-- Will result in: -->
* <ul>
* <li>eminem</li>
* <li>dr. dre</li>
* <li>50 Cent</li>
* </ul>
*/
wysihtml5.dom.convertToList = (function() {
function _createListItem(doc, list) {
var listItem = doc.createElement("li");
list.appendChild(listItem);
return listItem;
}
function _createList(doc, type) {
return doc.createElement(type);
}
function convertToList(element, listType) {
if (element.nodeName === "UL" || element.nodeName === "OL" || element.nodeName === "MENU") {
// Already a list
return element;
}
var doc = element.ownerDocument,
list = _createList(doc, listType),
lineBreaks = element.querySelectorAll("br"),
lineBreaksLength = lineBreaks.length,
childNodes,
childNodesLength,
childNode,
lineBreak,
parentNode,
isBlockElement,
isLineBreak,
currentListItem,
i;
// First find <br> at the end of inline elements and move them behind them
for (i=0; i<lineBreaksLength; i++) {
lineBreak = lineBreaks[i];
while ((parentNode = lineBreak.parentNode) && parentNode !== element && parentNode.lastChild === lineBreak) {
if (wysihtml5.dom.getStyle("display").from(parentNode) === "block") {
parentNode.removeChild(lineBreak);
break;
}
wysihtml5.dom.insert(lineBreak).after(lineBreak.parentNode);
}
}
childNodes = wysihtml5.lang.array(element.childNodes).get();
childNodesLength = childNodes.length;
for (i=0; i<childNodesLength; i++) {
currentListItem = currentListItem || _createListItem(doc, list);
childNode = childNodes[i];
isBlockElement = wysihtml5.dom.getStyle("display").from(childNode) === "block";
isLineBreak = childNode.nodeName === "BR";
if (isBlockElement) {
// Append blockElement to current <li> if empty, otherwise create a new one
currentListItem = currentListItem.firstChild ? _createListItem(doc, list) : currentListItem;
currentListItem.appendChild(childNode);
currentListItem = null;
continue;
}
if (isLineBreak) {
// Only create a new list item in the next iteration when the current one has already content
currentListItem = currentListItem.firstChild ? null : currentListItem;
continue;
}
currentListItem.appendChild(childNode);
}
element.parentNode.replaceChild(list, element);
return list;
}
return convertToList;
})();/**
* Copy a set of attributes from one element to another
*
* @param {Array} attributesToCopy List of attributes which should be copied
* @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to
* copy the attributes from., this again returns an object which provides a method named "to" which can be invoked
* with the element where to copy the attributes to (see example)
*
* @example
* var textarea = document.querySelector("textarea"),
* div = document.querySelector("div[contenteditable=true]"),
* anotherDiv = document.querySelector("div.preview");
* wysihtml5.dom.copyAttributes(["spellcheck", "value", "placeholder"]).from(textarea).to(div).andTo(anotherDiv);
*
*/
wysihtml5.dom.copyAttributes = function(attributesToCopy) {
return {
from: function(elementToCopyFrom) {
return {
to: function(elementToCopyTo) {
var attribute,
i = 0,
length = attributesToCopy.length;
for (; i<length; i++) {
attribute = attributesToCopy[i];
if (typeof(elementToCopyFrom[attribute]) !== "undefined" && elementToCopyFrom[attribute] !== "") {
elementToCopyTo[attribute] = elementToCopyFrom[attribute];
}
}
return { andTo: arguments.callee };
}
};
}
};
};/**
* Copy a set of styles from one element to another
* Please note that this only works properly across browsers when the element from which to copy the styles
* is in the dom
*
* Interesting article on how to copy styles
*
* @param {Array} stylesToCopy List of styles which should be copied
* @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to
* copy the styles from., this again returns an object which provides a method named "to" which can be invoked
* with the element where to copy the styles to (see example)
*
* @example
* var textarea = document.querySelector("textarea"),
* div = document.querySelector("div[contenteditable=true]"),
* anotherDiv = document.querySelector("div.preview");
* wysihtml5.dom.copyStyles(["overflow-y", "width", "height"]).from(textarea).to(div).andTo(anotherDiv);
*
*/
(function(dom) {
/**
* Mozilla, WebKit and Opera recalculate the computed width when box-sizing: boder-box; is set
* So if an element has "width: 200px; -moz-box-sizing: border-box; border: 1px;" then
* its computed css width will be 198px
*/
var BOX_SIZING_PROPERTIES = ["-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing"];
var shouldIgnoreBoxSizingBorderBox = function(element) {
if (hasBoxSizingBorderBox(element)) {
return parseInt(dom.getStyle("width").from(element), 10) < element.offsetWidth;
}
return false;
};
var hasBoxSizingBorderBox = function(element) {
var i = 0,
length = BOX_SIZING_PROPERTIES.length;
for (; i<length; i++) {
if (dom.getStyle(BOX_SIZING_PROPERTIES[i]).from(element) === "border-box") {
return BOX_SIZING_PROPERTIES[i];
}
}
};
dom.copyStyles = function(stylesToCopy) {
return {
from: function(element) {
if (shouldIgnoreBoxSizingBorderBox(element)) {
stylesToCopy = wysihtml5.lang.array(stylesToCopy).without(BOX_SIZING_PROPERTIES);
}
var cssText = "",
length = stylesToCopy.length,
i = 0,
property;
for (; i<length; i++) {
property = stylesToCopy[i];
cssText += property + ":" + dom.getStyle(property).from(element) + ";";
}
return {
to: function(element) {
dom.setStyles(cssText).on(element);
return { andTo: arguments.callee };
}
};
}
};
};
})(wysihtml5.dom);/**
* Event Delegation
*
* @example
* wysihtml5.dom.delegate(document.body, "a", "click", function() {
* // foo
* });
*/
(function(wysihtml5) {
wysihtml5.dom.delegate = function(container, selector, eventName, handler) {
return wysihtml5.dom.observe(container, eventName, function(event) {
var target = event.target,
match = wysihtml5.lang.array(container.querySelectorAll(selector));
while (target && target !== container) {
if (match.contains(target)) {
handler.call(target, event);
break;
}
target = target.parentNode;
}
});
};
})(wysihtml5);/**
* Returns the given html wrapped in a div element
*
* Fixing IE's inability to treat unknown elements (HTML5 section, article, ...) correctly
* when inserted via innerHTML
*
* @param {String} html The html which should be wrapped in a dom element
* @param {Obejct} [context] Document object of the context the html belongs to
*
* @example
* wysihtml5.dom.getAsDom("<article>foo</article>");
*/
wysihtml5.dom.getAsDom = (function() {
var _innerHTMLShiv = function(html, context) {
var tempElement = context.createElement("div");
tempElement.style.display = "none";
context.body.appendChild(tempElement);
// IE throws an exception when trying to insert <frameset></frameset> via innerHTML
try { tempElement.innerHTML = html; } catch(e) {}
context.body.removeChild(tempElement);
return tempElement;
};
/**
* Make sure IE supports HTML5 tags, which is accomplished by simply creating one instance of each element
*/
var _ensureHTML5Compatibility = function(context) {
if (context._wysihtml5_supportsHTML5Tags) {
return;
}
for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) {
context.createElement(HTML5_ELEMENTS[i]);
}
context._wysihtml5_supportsHTML5Tags = true;
};
/**
* List of html5 tags
* taken from http://simon.html5.org/html5-elements
*/
var HTML5_ELEMENTS = [
"abbr", "article", "aside", "audio", "bdi", "canvas", "command", "datalist", "details", "figcaption",
"figure", "footer", "header", "hgroup", "keygen", "mark", "meter", "nav", "output", "progress",
"rp", "rt", "ruby", "svg", "section", "source", "summary", "time", "track", "video", "wbr"
];
return function(html, context) {
context = context || document;
var tempElement;
if (typeof(html) === "object" && html.nodeType) {
tempElement = context.createElement("div");
tempElement.appendChild(html);
} else if (wysihtml5.browser.supportsHTML5Tags(context)) {
tempElement = context.createElement("div");
tempElement.innerHTML = html;
} else {
_ensureHTML5Compatibility(context);
tempElement = _innerHTMLShiv(html, context);
}
return tempElement;
};
})();/**
* Walks the dom tree from the given node up until it finds a match
* Designed for optimal performance.
*
* @param {Element} node The from which to check the parent nodes
* @param {Object} matchingSet Object to match against (possible properties: nodeName, className, classRegExp)
* @param {Number} [levels] How many parents should the function check up from the current node (defaults to 50)
* @return {null|Element} Returns the first element that matched the desiredNodeName(s)
* @example
* var listElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: ["MENU", "UL", "OL"] });
* // ... or ...
* var unorderedListElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: "UL" });
* // ... or ...
* var coloredElement = wysihtml5.dom.getParentElement(myTextNode, { nodeName: "SPAN", className: "wysiwyg-color-red", classRegExp: /wysiwyg-color-[a-z]/g });
*/
wysihtml5.dom.getParentElement = (function() {
function _isSameNodeName(nodeName, desiredNodeNames) {
if (!desiredNodeNames || !desiredNodeNames.length) {
return true;
}
if (typeof(desiredNodeNames) === "string") {
return nodeName === desiredNodeNames;
} else {
return wysihtml5.lang.array(desiredNodeNames).contains(nodeName);
}
}
function _isElement(node) {
return node.nodeType === wysihtml5.ELEMENT_NODE;
}
function _hasClassName(element, className, classRegExp) {
var classNames = (element.className || "").match(classRegExp) || [];
if (!className) {
return !!classNames.length;
}
return classNames[classNames.length - 1] === className;
}
function _getParentElementWithNodeName(node, nodeName, levels) {
while (levels-- && node && node.nodeName !== "BODY") {
if (_isSameNodeName(node.nodeName, nodeName)) {
return node;
}
node = node.parentNode;
}
return null;
}
function _getParentElementWithNodeNameAndClassName(node, nodeName, className, classRegExp, levels) {
while (levels-- && node && node.nodeName !== "BODY") {
if (_isElement(node) &&
_isSameNodeName(node.nodeName, nodeName) &&
_hasClassName(node, className, classRegExp)) {
return node;
}
node = node.parentNode;
}
return null;
}
return function(node, matchingSet, levels) {
levels = levels || 50; // Go max 50 nodes upwards from current node
if (matchingSet.className || matchingSet.classRegExp) {
return _getParentElementWithNodeNameAndClassName(
node, matchingSet.nodeName, matchingSet.className, matchingSet.classRegExp, levels
);
} else {
return _getParentElementWithNodeName(
node, matchingSet.nodeName, levels
);
}
};
})();
/**
* Get element's style for a specific css property
*
* @param {Element} element The element on which to retrieve the style
* @param {String} property The CSS property to retrieve ("float", "display", "text-align", ...)
*
* @example
* wysihtml5.dom.getStyle("display").from(document.body);
* // => "block"
*/
wysihtml5.dom.getStyle = (function() {
var stylePropertyMapping = {
"float": ("styleFloat" in document.createElement("div").style) ? "styleFloat" : "cssFloat"
},
REG_EXP_CAMELIZE = /\-[a-z]/g;
function camelize(str) {
return str.replace(REG_EXP_CAMELIZE, function(match) {
return match.charAt(1).toUpperCase();
});
}
return function(property) {
return {
from: function(element) {
if (element.nodeType !== wysihtml5.ELEMENT_NODE) {
return;
}
var doc = element.ownerDocument,
camelizedProperty = stylePropertyMapping[property] || camelize(property),
style = element.style,
currentStyle = element.currentStyle,
styleValue = style[camelizedProperty];
if (styleValue) {
return styleValue;
}
// currentStyle is no standard and only supported by Opera and IE but it has one important advantage over the standard-compliant
// window.getComputedStyle, since it returns css property values in their original unit:
// If you set an elements width to "50%", window.getComputedStyle will give you it's current width in px while currentStyle
// gives you the original "50%".
// Opera supports both, currentStyle and window.getComputedStyle, that's why checking for currentStyle should have higher prio
if (currentStyle) {
try {
return currentStyle[camelizedProperty];
} catch(e) {
//ie will occasionally fail for unknown reasons. swallowing exception
}
}
var win = doc.defaultView || doc.parentWindow,
needsOverflowReset = (property === "height" || property === "width") && element.nodeName === "TEXTAREA",
originalOverflow,
returnValue;
if (win.getComputedStyle) {
// Chrome and Safari both calculate a wrong width and height for textareas when they have scroll bars
// therfore we remove and restore the scrollbar and calculate the value in between
if (needsOverflowReset) {
originalOverflow = style.overflow;
style.overflow = "hidden";
}
returnValue = win.getComputedStyle(element, null).getPropertyValue(property);
if (needsOverflowReset) {
style.overflow = originalOverflow || "";
}
return returnValue;
}
}
};
};
})();/**
* High performant way to check whether an element with a specific tag name is in the given document
* Optimized for being heavily executed
* Unleashes the power of live node lists
*
* @param {Object} doc The document object of the context where to check
* @param {String} tagName Upper cased tag name
* @example
* wysihtml5.dom.hasElementWithTagName(document, "IMG");
*/
wysihtml5.dom.hasElementWithTagName = (function() {
var LIVE_CACHE = {},
DOCUMENT_IDENTIFIER = 1;
function _getDocumentIdentifier(doc) {
return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++);
}
return function(doc, tagName) {
var key = _getDocumentIdentifier(doc) + ":" + tagName,
cacheEntry = LIVE_CACHE[key];
if (!cacheEntry) {
cacheEntry = LIVE_CACHE[key] = doc.getElementsByTagName(tagName);
}
return cacheEntry.length > 0;
};
})();/**
* High performant way to check whether an element with a specific class name is in the given document
* Optimized for being heavily executed
* Unleashes the power of live node lists
*
* @param {Object} doc The document object of the context where to check
* @param {String} tagName Upper cased tag name
* @example
* wysihtml5.dom.hasElementWithClassName(document, "foobar");
*/
(function(wysihtml5) {
var LIVE_CACHE = {},
DOCUMENT_IDENTIFIER = 1;
function _getDocumentIdentifier(doc) {
return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++);
}
wysihtml5.dom.hasElementWithClassName = function(doc, className) {
// getElementsByClassName is not supported by IE<9
// but is sometimes mocked via library code (which then doesn't return live node lists)
if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) {
return !!doc.querySelector("." + className);
}
var key = _getDocumentIdentifier(doc) + ":" + className,
cacheEntry = LIVE_CACHE[key];
if (!cacheEntry) {
cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className);
}
return cacheEntry.length > 0;
};
})(wysihtml5);
wysihtml5.dom.insert = function(elementToInsert) {
return {
after: function(element) {
element.parentNode.insertBefore(elementToInsert, element.nextSibling);
},
before: function(element) {
element.parentNode.insertBefore(elementToInsert, element);
},
into: function(element) {
element.appendChild(elementToInsert);
}
};
};wysihtml5.dom.insertCSS = function(rules) {
rules = rules.join("\n");
return {
into: function(doc) {
var head = doc.head || doc.getElementsByTagName("head")[0],
styleElement = doc.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = rules;
} else {
styleElement.appendChild(doc.createTextNode(rules));
}
if (head) {
head.appendChild(styleElement);
}
}
};
};/**
* Method to set dom events
*
* @example
* wysihtml5.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... });
*/
wysihtml5.dom.observe = function(element, eventNames, handler) {
eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames;
var handlerWrapper,
eventName,
i = 0,
length = eventNames.length;
for (; i<length; i++) {
eventName = eventNames[i];
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
} else {
handlerWrapper = function(event) {
if (!("target" in event)) {
event.target = event.srcElement;
}
event.preventDefault = event.preventDefault || function() {
this.returnValue = false;
};
event.stopPropagation = event.stopPropagation || function() {
this.cancelBubble = true;
};
handler.call(element, event);
};
element.attachEvent("on" + eventName, handlerWrapper);
}
}
return {
stop: function() {
var eventName,
i = 0,
length = eventNames.length;
for (; i<length; i++) {
eventName = eventNames[i];
if (element.removeEventListener) {
element.removeEventListener(eventName, handler, false);
} else {
element.detachEvent("on" + eventName, handlerWrapper);
}
}
}
};
};
/**
* HTML Sanitizer
* Rewrites the HTML based on given rules
*
* @param {Element|String} elementOrHtml HTML String to be sanitized OR element whose content should be sanitized
* @param {Object} [rules] List of rules for rewriting the HTML, if there's no rule for an element it will
* be converted to a "span". Each rule is a key/value pair where key is the tag to convert, and value the
* desired substitution.
* @param {Object} context Document object in which to parse the html, needed to sandbox the parsing
*
* @return {Element|String} Depends on the elementOrHtml parameter. When html then the sanitized html as string elsewise the element.
*
* @example
* var userHTML = '<div id="foo" onclick="alert(1);"><p><font color="red">foo</font><script>alert(1);</script></p></div>';
* wysihtml5.dom.parse(userHTML, {
* tags {
* p: "div", // Rename p tags to div tags
* font: "span" // Rename font tags to span tags
* div: true, // Keep them, also possible (same result when passing: "div" or true)
* script: undefined // Remove script elements
* }
* });
* // => <div><div><span>foo bar</span></div></div>
*
* var userHTML = '<table><tbody><tr><td>I'm a table!</td></tr></tbody></table>';
* wysihtml5.dom.parse(userHTML);
* // => '<span><span><span><span>I'm a table!</span></span></span></span>'
*
* var userHTML = '<div>foobar<br>foobar</div>';
* wysihtml5.dom.parse(userHTML, {
* tags: {
* div: undefined,
* br: true
* }
* });
* // => ''
*
* var userHTML = '<div class="red">foo</div><div class="pink">bar</div>';
* wysihtml5.dom.parse(userHTML, {
* classes: {
* red: 1,
* green: 1
* },
* tags: {
* div: {
* rename_tag: "p"
* }
* }
* });
* // => '<p class="red">foo</p><p>bar</p>'
*/
wysihtml5.dom.parse = (function() {
/**
* It's not possible to use a XMLParser/DOMParser as HTML5 is not always well-formed XML
* new DOMParser().parseFromString('<img src="foo.gif">') will cause a parseError since the
* node isn't closed
*
* Therefore we've to use the browser's ordinary HTML parser invoked by setting innerHTML.
*/
var NODE_TYPE_MAPPING = {
"1": _handleElement,
"3": _handleText
},
// Rename unknown tags to this
DEFAULT_NODE_NAME = "span",
WHITE_SPACE_REG_EXP = /\s+/,
defaultRules = { tags: {}, classes: {} },
currentRules = {};
/**
* Iterates over all childs of the element, recreates them, appends them into a document fragment
* which later replaces the entire body content
*/
function parse(elementOrHtml, rules, context, cleanUp) {
wysihtml5.lang.object(currentRules).merge(defaultRules).merge(rules).get();
context = context || elementOrHtml.ownerDocument || document;
var fragment = context.createDocumentFragment(),
isString = typeof(elementOrHtml) === "string",
element,
newNode,
firstChild;
if (isString) {
element = wysihtml5.dom.getAsDom(elementOrHtml, context);
} else {
element = elementOrHtml;
}
while (element.firstChild) {
firstChild = element.firstChild;
element.removeChild(firstChild);
newNode = _convert(firstChild, cleanUp);
if (newNode) {
fragment.appendChild(newNode);
}
}
// Clear element contents
element.innerHTML = "";
// Insert new DOM tree
element.appendChild(fragment);
return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element;
}
function _convert(oldNode, cleanUp) {
var oldNodeType = oldNode.nodeType,
oldChilds = oldNode.childNodes,
oldChildsLength = oldChilds.length,
newNode,
method = NODE_TYPE_MAPPING[oldNodeType],
i = 0;
newNode = method && method(oldNode);
if (!newNode) {
return null;
}
for (i=0; i<oldChildsLength; i++) {
newChild = _convert(oldChilds[i], cleanUp);
if (newChild) {
newNode.appendChild(newChild);
}
}
// Cleanup senseless <span> elements
if (cleanUp &&
newNode.childNodes.length <= 1 &&
newNode.nodeName.toLowerCase() === DEFAULT_NODE_NAME &&
!newNode.attributes.length) {
return newNode.firstChild;
}
return newNode;
}
function _handleElement(oldNode) {
var rule,
newNode,
endTag,
tagRules = currentRules.tags,
nodeName = oldNode.nodeName.toLowerCase(),
scopeName = oldNode.scopeName;
/**
* We already parsed that element
* ignore it! (yes, this sometimes happens in IE8 when the html is invalid)
*/
if (oldNode._wysihtml5) {
return null;
}
oldNode._wysihtml5 = 1;
if (oldNode.className === "wysihtml5-temp") {
return null;
}
/**
* IE is the only browser who doesn't include the namespace in the
* nodeName, that's why we have to prepend it by ourselves
* scopeName is a proprietary IE feature
* read more here http://msdn.microsoft.com/en-us/library/ms534388(v=vs.85).aspx
*/
if (scopeName && scopeName != "HTML") {
nodeName = scopeName + ":" + nodeName;
}
/**
* Repair node
* IE is a bit bitchy when it comes to invalid nested markup which includes unclosed tags
* A <p> doesn't need to be closed according HTML4-5 spec, we simply replace it with a <div> to preserve its content and layout
*/
if ("outerHTML" in oldNode) {
if (!wysihtml5.browser.autoClosesUnclosedTags() &&
oldNode.nodeName === "P" &&
oldNode.outerHTML.slice(-4).toLowerCase() !== "</p>") {
nodeName = "div";
}
}
if (nodeName in tagRules) {
rule = tagRules[nodeName];
if (!rule || rule.remove) {
return null;
}
rule = typeof(rule) === "string" ? { rename_tag: rule } : rule;
} else if (oldNode.firstChild) {
rule = { rename_tag: DEFAULT_NODE_NAME };
} else {
// Remove empty unknown elements
return null;
}
newNode = oldNode.ownerDocument.createElement(rule.rename_tag || nodeName);
_handleAttributes(oldNode, newNode, rule);
oldNode = null;
return newNode;
}
function _handleAttributes(oldNode, newNode, rule) {
var attributes = {}, // fresh new set of attributes to set on newNode
setClass = rule.set_class, // classes to set
addClass = rule.add_class, // add classes based on existing attributes
setAttributes = rule.set_attributes, // attributes to set on the current node
checkAttributes = rule.check_attributes, // check/convert values of attributes
allowedClasses = currentRules.classes,
i = 0,
classes = [],
newClasses = [],
newUniqueClasses = [],
oldClasses = [],
classesLength,
newClassesLength,
currentClass,
newClass,
attributeName,
newAttributeValue,
method;
if (setAttributes) {
attributes = wysihtml5.lang.object(setAttributes).clone();
}
if (checkAttributes) {
for (attributeName in checkAttributes) {
method = attributeCheckMethods[checkAttributes[attributeName]];
if (!method) {
continue;
}
newAttributeValue = method(_getAttribute(oldNode, attributeName));
if (typeof(newAttributeValue) === "string") {
attributes[attributeName] = newAttributeValue;
}
}
}
if (setClass) {
classes.push(setClass);
}
if (addClass) {
for (attributeName in addClass) {
method = addClassMethods[addClass[attributeName]];
if (!method) {
continue;
}
newClass = method(_getAttribute(oldNode, attributeName));
if (typeof(newClass) === "string") {
classes.push(newClass);
}
}
}
// make sure that wysihtml5 temp class doesn't get stripped out
allowedClasses["_wysihtml5-temp-placeholder"] = 1;
// add old classes last
oldClasses = oldNode.getAttribute("class");
if (oldClasses) {
classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP));
}
classesLength = classes.length;
for (; i<classesLength; i++) {
currentClass = classes[i];
if (allowedClasses[currentClass]) {
newClasses.push(currentClass);
}
}
// remove duplicate entries and preserve class specificity
newClassesLength = newClasses.length;
while (newClassesLength--) {
currentClass = newClasses[newClassesLength];
if (!wysihtml5.lang.array(newUniqueClasses).contains(currentClass)) {
newUniqueClasses.unshift(currentClass);
}
}
if (newUniqueClasses.length) {
attributes["class"] = newUniqueClasses.join(" ");
}
// set attributes on newNode
for (attributeName in attributes) {
// Setting attributes can cause a js error in IE under certain circumstances
// eg. on a <img> under https when it's new attribute value is non-https
// TODO: Investigate this further and check for smarter handling
try {
newNode.setAttribute(attributeName, attributes[attributeName]);
} catch(e) {}
}
// IE8 sometimes loses the width/height attributes when those are set before the "src"
// so we make sure to set them again
if (attributes.src) {
if (typeof(attributes.width) !== "undefined") {
newNode.setAttribute("width", attributes.width);
}
if (typeof(attributes.height) !== "undefined") {
newNode.setAttribute("height", attributes.height);
}
}
}
/**
* IE gives wrong results for hasAttribute/getAttribute, for example:
* var td = document.createElement("td");
* td.getAttribute("rowspan"); // => "1" in IE
*
* Therefore we have to check the element's outerHTML for the attribute
*/
var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly();
function _getAttribute(node, attributeName) {
attributeName = attributeName.toLowerCase();
var nodeName = node.nodeName;
if (nodeName == "IMG" && attributeName == "src" && _isLoadedImage(node) === true) {
// Get 'src' attribute value via object property since this will always contain the
// full absolute url (http://...)
// this fixes a very annoying bug in firefox (ver 3.6 & 4) and IE 8 where images copied from the same host
// will have relative paths, which the sanitizer strips out (see attributeCheckMethods.url)
return node.src;
} else if (HAS_GET_ATTRIBUTE_BUG && "outerHTML" in node) {
// Don't trust getAttribute/hasAttribute in IE 6-8, instead check the element's outerHTML
var outerHTML = node.outerHTML.toLowerCase(),
// TODO: This might not work for attributes without value: <input disabled>
hasAttribute = outerHTML.indexOf(" " + attributeName + "=") != -1;
return hasAttribute ? node.getAttribute(attributeName) : null;
} else{
return node.getAttribute(attributeName);
}
}
/**
* Check whether the given node is a proper loaded image
* FIXME: Returns undefined when unknown (Chrome, Safari)
*/
function _isLoadedImage(node) {
try {
return node.complete && !node.mozMatchesSelector(":-moz-broken");
} catch(e) {
if (node.complete && node.readyState === "complete") {
return true;
}
}
}
function _handleText(oldNode) {
return oldNode.ownerDocument.createTextNode(oldNode.data);
}
// ------------ attribute checks ------------ \\
var attributeCheckMethods = {
url: (function() {
var REG_EXP = /^https?:\/\//i;
return function(attributeValue) {
if (!attributeValue || !attributeValue.match(REG_EXP)) {
return null;
}
return attributeValue.replace(REG_EXP, function(match) {
return match.toLowerCase();
});
};
})(),
alt: (function() {
var REG_EXP = /[^ a-z0-9_\-]/gi;
return function(attributeValue) {
if (!attributeValue) {
return "";
}
return attributeValue.replace(REG_EXP, "");
};
})(),
numbers: (function() {
var REG_EXP = /\D/g;
return function(attributeValue) {
attributeValue = (attributeValue || "").replace(REG_EXP, "");
return attributeValue || null;
};
})()
};
// ------------ class converter (converts an html attribute to a class name) ------------ \\
var addClassMethods = {
align_img: (function() {
var mapping = {
left: "wysiwyg-float-left",
right: "wysiwyg-float-right"
};
return function(attributeValue) {
return mapping[String(attributeValue).toLowerCase()];
};
})(),
align_text: (function() {
var mapping = {
left: "wysiwyg-text-align-left",
right: "wysiwyg-text-align-right",
center: "wysiwyg-text-align-center",
justify: "wysiwyg-text-align-justify"
};
return function(attributeValue) {
return mapping[String(attributeValue).toLowerCase()];
};
})(),
clear_br: (function() {
var mapping = {
left: "wysiwyg-clear-left",
right: "wysiwyg-clear-right",
both: "wysiwyg-clear-both",
all: "wysiwyg-clear-both"
};
return function(attributeValue) {
return mapping[String(attributeValue).toLowerCase()];
};
})(),
size_font: (function() {
var mapping = {
"1": "wysiwyg-font-size-xx-small",
"2": "wysiwyg-font-size-small",
"3": "wysiwyg-font-size-medium",
"4": "wysiwyg-font-size-large",
"5": "wysiwyg-font-size-x-large",
"6": "wysiwyg-font-size-xx-large",
"7": "wysiwyg-font-size-xx-large",
"-": "wysiwyg-font-size-smaller",
"+": "wysiwyg-font-size-larger"
};
return function(attributeValue) {
return mapping[String(attributeValue).charAt(0)];
};
})()
};
return parse;
})();/**
* Checks for empty text node childs and removes them
*
* @param {Element} node The element in which to cleanup
* @example
* wysihtml5.dom.removeEmptyTextNodes(element);
*/
wysihtml5.dom.removeEmptyTextNodes = function(node) {
var childNode,
childNodes = wysihtml5.lang.array(node.childNodes).get(),
childNodesLength = childNodes.length,
i = 0;
for (; i<childNodesLength; i++) {
childNode = childNodes[i];
if (childNode.nodeType === wysihtml5.TEXT_NODE && childNode.data === "") {
childNode.parentNode.removeChild(childNode);
}
}
};
/**
* Renames an element (eg. a <div> to a <p>) and keeps its childs
*
* @param {Element} element The list element which should be renamed
* @param {Element} newNodeName The desired tag name
*
* @example
* <!-- Assume the following dom: -->
* <ul id="list">
* <li>eminem</li>
* <li>dr. dre</li>
* <li>50 Cent</li>
* </ul>
*
* <script>
* wysihtml5.dom.renameElement(document.getElementById("list"), "ol");
* </script>
*
* <!-- Will result in: -->
* <ol>
* <li>eminem</li>
* <li>dr. dre</li>
* <li>50 Cent</li>
* </ol>
*/
wysihtml5.dom.renameElement = function(element, newNodeName) {
var newElement = element.ownerDocument.createElement(newNodeName),
firstChild;
while (firstChild = element.firstChild) {
newElement.appendChild(firstChild);
}
wysihtml5.dom.copyAttributes(["align", "className"]).from(element).to(newElement);
element.parentNode.replaceChild(newElement, element);
return newElement;
};/**
* Takes an element, removes it and replaces it with it's childs
*
* @param {Object} node The node which to replace with it's child nodes
* @example
* <div id="foo">
* <span>hello</span>
* </div>
* <script>
* // Remove #foo and replace with it's children
* wysihtml5.dom.replaceWithChildNodes(document.getElementById("foo"));
* </script>
*/
wysihtml5.dom.replaceWithChildNodes = function(node) {
if (!node.parentNode) {
return;
}
if (!node.firstChild) {
node.parentNode.removeChild(node);
return;
}
var fragment = node.ownerDocument.createDocumentFragment();
while (node.firstChild) {
fragment.appendChild(node.firstChild);
}
node.parentNode.replaceChild(fragment, node);
node = fragment = null;
};
/**
* Unwraps an unordered/ordered list
*
* @param {Element} element The list element which should be unwrapped
*
* @example
* <!-- Assume the following dom: -->
* <ul id="list">
* <li>eminem</li>
* <li>dr. dre</li>
* <li>50 Cent</li>
* </ul>
*
* <script>
* wysihtml5.dom.resolveList(document.getElementById("list"));
* </script>
*
* <!-- Will result in: -->
* eminem<br>
* dr. dre<br>
* 50 Cent<br>
*/
(function(dom) {
function _isBlockElement(node) {
return dom.getStyle("display").from(node) === "block";
}
function _isLineBreak(node) {
return node.nodeName === "BR";
}
function _appendLineBreak(element) {
var lineBreak = element.ownerDocument.createElement("br");
element.appendChild(lineBreak);
}
function resolveList(list) {
if (list.nodeName !== "MENU" && list.nodeName !== "UL" && list.nodeName !== "OL") {
return;
}
var doc = list.ownerDocument,
fragment = doc.createDocumentFragment(),
previousSibling = list.previousElementSibling || list.previousSibling,
firstChild,
lastChild,
isLastChild,
shouldAppendLineBreak,
listItem;
if (previousSibling && !_isBlockElement(previousSibling)) {
_appendLineBreak(fragment);
}
while (listItem = list.firstChild) {
lastChild = listItem.lastChild;
while (firstChild = listItem.firstChild) {
isLastChild = firstChild === lastChild;
// This needs to be done before appending it to the fragment, as it otherwise will loose style information
shouldAppendLineBreak = isLastChild && !_isBlockElement(firstChild) && !_isLineBreak(firstChild);
fragment.appendChild(firstChild);
if (shouldAppendLineBreak) {
_appendLineBreak(fragment);
}
}
listItem.parentNode.removeChild(listItem);
}
list.parentNode.replaceChild(fragment, list);
}
dom.resolveList = resolveList;
})(wysihtml5.dom);/**
* Sandbox for executing javascript, parsing css styles and doing dom operations in a secure way
*
* Browser Compatibility:
* - Secure in MSIE 6+, but only when the user hasn't made changes to his security level "restricted"
* - Partially secure in other browsers (Firefox, Opera, Safari, Chrome, ...)
*
* Please note that this class can't benefit from the HTML5 sandbox attribute for the following reasons:
* - sandboxing doesn't work correctly with inlined content (src="javascript:'<html>...</html>'")
* - sandboxing of physical documents causes that the dom isn't accessible anymore from the outside (iframe.contentWindow, ...)
* - setting the "allow-same-origin" flag would fix that, but then still javascript and dom events refuse to fire
* - therefore the "allow-scripts" flag is needed, which then would deactivate any security, as the js executed inside the iframe
* can do anything as if the sandbox attribute wasn't set
*
* @param {Function} [readyCallback] Method that gets invoked when the sandbox is ready
* @param {Object} [config] Optional parameters
*
* @example
* new wysihtml5.dom.Sandbox(function(sandbox) {
* sandbox.getWindow().document.body.innerHTML = '<img src=foo.gif onerror="alert(document.cookie)">';
* });
*/
(function(wysihtml5) {
var /**
* Default configuration
*/
doc = document,
/**
* Properties to unset/protect on the window object
*/
windowProperties = [
"parent", "top", "opener", "frameElement", "frames",
"localStorage", "globalStorage", "sessionStorage", "indexedDB"
],
/**
* Properties on the window object which are set to an empty function
*/
windowProperties2 = [
"open", "close", "openDialog", "showModalDialog",
"alert", "confirm", "prompt",
"openDatabase", "postMessage",
"XMLHttpRequest", "XDomainRequest"
],
/**
* Properties to unset/protect on the document object
*/
documentProperties = [
"referrer",
"write", "open", "close"
];
wysihtml5.dom.Sandbox = Base.extend(
/** @scope wysihtml5.dom.Sandbox.prototype */ {
constructor: function(readyCallback, config) {
this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION;
this.config = wysihtml5.lang.object({}).merge(config).get();
this.iframe = this._createIframe();
},
insertInto: function(element) {
if (typeof(element) === "string") {
element = doc.getElementById(element);
}
element.appendChild(this.iframe);
},
getIframe: function() {
return this.iframe;
},
getWindow: function() {
this._readyError();
},
getDocument: function() {
this._readyError();
},
destroy: function() {
var iframe = this.getIframe();
iframe.parentNode.removeChild(iframe);
},
_readyError: function() {
throw new Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet");
},
/**
* Creates the sandbox iframe
*
* Some important notes:
* - We can't use HTML5 sandbox for now:
* setting it causes that the iframe's dom can't be accessed from the outside
* Therefore we need to set the "allow-same-origin" flag which enables accessing the iframe's dom
* But then there's another problem, DOM events (focus, blur, change, keypress, ...) aren't fired.
* In order to make this happen we need to set the "allow-scripts" flag.
* A combination of allow-scripts and allow-same-origin is almost the same as setting no sandbox attribute at all.
* - Chrome & Safari, doesn't seem to support sandboxing correctly when the iframe's html is inlined (no physical document)
* - IE needs to have the security="restricted" attribute set before the iframe is
* inserted into the dom tree
* - Believe it or not but in IE "security" in document.createElement("iframe") is false, even
* though it supports it
* - When an iframe has security="restricted", in IE eval() & execScript() don't work anymore
* - IE doesn't fire the onload event when the content is inlined in the src attribute, therefore we rely
* on the onreadystatechange event
*/
_createIframe: function() {
var that = this,
iframe = doc.createElement("iframe");
iframe.className = "wysihtml5-sandbox";
wysihtml5.dom.setAttributes({
"security": "restricted",
"allowtransparency": "true",
"frameborder": 0,
"width": 0,
"height": 0,
"marginwidth": 0,
"marginheight": 0
}).on(iframe);
// Setting the src like this prevents ssl warnings in IE6
if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) {
iframe.src = "javascript:'<html></html>'";
}
iframe.onload = function() {
iframe.onreadystatechange = iframe.onload = null;
that._onLoadIframe(iframe);
};
iframe.onreadystatechange = function() {
if (/loaded|complete/.test(iframe.readyState)) {
iframe.onreadystatechange = iframe.onload = null;
that._onLoadIframe(iframe);
}
};
return iframe;
},
/**
* Callback for when the iframe has finished loading
*/
_onLoadIframe: function(iframe) {
// don't resume when the iframe got unloaded (eg. by removing it from the dom)
if (!wysihtml5.dom.contains(doc.documentElement, iframe)) {
return;
}
var that = this,
iframeWindow = iframe.contentWindow,
iframeDocument = iframe.contentWindow.document,
charset = doc.characterSet || doc.charset || "utf-8",
sandboxHtml = this._getHtml({
charset: charset,
stylesheets: this.config.stylesheets
});
// Create the basic dom tree including proper DOCTYPE and charset
iframeDocument.open("text/html", "replace");
iframeDocument.write(sandboxHtml);
iframeDocument.close();
this.getWindow = function() { return iframe.contentWindow; };
this.getDocument = function() { return iframe.contentWindow.document; };
// Catch js errors and pass them to the parent's onerror event
// addEventListener("error") doesn't work properly in some browsers
// TODO: apparently this doesn't work in IE9!
iframeWindow.onerror = function(errorMessage, fileName, lineNumber) {
throw new Error("wysihtml5.Sandbox: " + errorMessage, fileName, lineNumber);
};
if (!wysihtml5.browser.supportsSandboxedIframes()) {
// Unset a bunch of sensitive variables
// Please note: This isn't hack safe!
// It more or less just takes care of basic attacks and prevents accidental theft of sensitive information
// IE is secure though, which is the most important thing, since IE is the only browser, who
// takes over scripts & styles into contentEditable elements when copied from external websites
// or applications (Microsoft Word, ...)
var i, length;
for (i=0, length=windowProperties.length; i<length; i++) {
this._unset(iframeWindow, windowProperties[i]);
}
for (i=0, length=windowProperties2.length; i<length; i++) {
this._unset(iframeWindow, windowProperties2[i], wysihtml5.EMPTY_FUNCTION);
}
for (i=0, length=documentProperties.length; i<length; i++) {
this._unset(iframeDocument, documentProperties[i]);
}
// This doesn't work in Safari 5
// See http://stackoverflow.com/questions/992461/is-it-possible-to-override-document-cookie-in-webkit
this._unset(iframeDocument, "cookie", "", true);
}
this.loaded = true;
// Trigger the callback
setTimeout(function() { that.callback(that); }, 0);
},
_getHtml: function(templateVars) {
var stylesheets = templateVars.stylesheets,
html = "",
i = 0,
length;
stylesheets = typeof(stylesheets) === "string" ? [stylesheets] : stylesheets;
if (stylesheets) {
length = stylesheets.length;
for (; i<length; i++) {
html += '<link rel="stylesheet" href="' + stylesheets[i] + '">';
}
}
templateVars.stylesheets = html;
return wysihtml5.lang.string(
'<!DOCTYPE html><html><head>'
+ '<meta charset="#{charset}">#{stylesheets}</head>'
+ '<body></body></html>'
).interpolate(templateVars);
},
/**
* Method to unset/override existing variables
* @example
* // Make cookie unreadable and unwritable
* this._unset(document, "cookie", "", true);
*/
_unset: function(object, property, value, setter) {
try { object[property] = value; } catch(e) {}
try { object.__defineGetter__(property, function() { return value; }); } catch(e) {}
if (setter) {
try { object.__defineSetter__(property, function() {}); } catch(e) {}
}
if (!wysihtml5.browser.crashesWhenDefineProperty(property)) {
try {
var config = {
get: function() { return value; }
};
if (setter) {
config.set = function() {};
}
Object.defineProperty(object, property, config);
} catch(e) {}
}
}
});
})(wysihtml5);
(function() {
var mapping = {
"className": "class"
};
wysihtml5.dom.setAttributes = function(attributes) {
return {
on: function(element) {
for (var i in attributes) {
element.setAttribute(mapping[i] || i, attributes[i]);
}
}
}
};
})();wysihtml5.dom.setStyles = function(styles) {
return {
on: function(element) {
var style = element.style;
if (typeof(styles) === "string") {
style.cssText += ";" + styles;
return;
}
for (var i in styles) {
if (i === "float") {
style.cssFloat = styles[i];
style.styleFloat = styles[i];
} else {
style[i] = styles[i];
}
}
}
};
};/**
* Simulate HTML5 placeholder attribute
*
* Needed since
* - div[contentEditable] elements don't support it
* - older browsers (such as IE8 and Firefox 3.6) don't support it at all
*
* @param {Object} parent Instance of main wysihtml5.Editor class
* @param {Element} view Instance of wysihtml5.views.* class
* @param {String} placeholderText
*
* @example
* wysihtml.dom.simulatePlaceholder(this, composer, "Foobar");
*/
(function(dom) {
dom.simulatePlaceholder = function(editor, view, placeholderText) {
var CLASS_NAME = "placeholder",
unset = function() {
if (view.hasPlaceholderSet()) {
view.clear();
}
dom.removeClass(view.element, CLASS_NAME);
},
set = function() {
if (view.isEmpty()) {
view.setValue(placeholderText);
dom.addClass(view.element, CLASS_NAME);
}
};
editor
.observe("set_placeholder", set)
.observe("unset_placeholder", unset)
.observe("focus:composer", unset)
.observe("paste:composer", unset)
.observe("blur:composer", set);
set();
};
})(wysihtml5.dom);
(function(dom) {
var documentElement = document.documentElement;
if ("textContent" in documentElement) {
dom.setTextContent = function(element, text) {
element.textContent = text;
};
dom.getTextContent = function(element) {
return element.textContent;
};
} else if ("innerText" in documentElement) {
dom.setTextContent = function(element, text) {
element.innerText = text;
};
dom.getTextContent = function(element) {
return element.innerText;
};
} else {
dom.setTextContent = function(element, text) {
element.nodeValue = text;
};
dom.getTextContent = function(element) {
return element.nodeValue;
};
}
})(wysihtml5.dom);
/**
* Fix most common html formatting misbehaviors of browsers implementation when inserting
* content via copy & paste contentEditable
*
* @author Christopher Blum
*/
wysihtml5.quirks.cleanPastedHTML = (function() {
// TODO: We probably need more rules here
var defaultRules = {
// When pasting underlined links <a> into a contentEditable, IE thinks, it has to insert <u> to keep the styling
"a u": wysihtml5.dom.replaceWithChildNodes
};
function cleanPastedHTML(elementOrHtml, rules, context) {
rules = rules || defaultRules;
context = context || elementOrHtml.ownerDocument || document;
var element,
isString = typeof(elementOrHtml) === "string",
method,
matches,
matchesLength,
i,
j = 0;
if (isString) {
element = wysihtml5.dom.getAsDom(elementOrHtml, context);
} else {
element = elementOrHtml;
}
for (i in rules) {
matches = element.querySelectorAll(i);
method = rules[i];
matchesLength = matches.length;
for (; j<matchesLength; j++) {
method(matches[j]);
}
}
matches = elementOrHtml = rules = null;
return isString ? element.innerHTML : element;
}
return cleanPastedHTML;
})();/**
* IE and Opera leave an empty paragraph in the contentEditable element after clearing it
*
* @param {Object} contentEditableElement The contentEditable element to observe for clearing events
* @exaple
* wysihtml5.quirks.ensureProperClearing(myContentEditableElement);
*/
(function(wysihtml5) {
var dom = wysihtml5.dom;
wysihtml5.quirks.ensureProperClearing = (function() {
var clearIfNecessary = function(event) {
var element = this;
setTimeout(function() {
var innerHTML = element.innerHTML.toLowerCase();
if (innerHTML == "<p> </p>" ||
innerHTML == "<p> </p><p> </p>") {
element.innerHTML = "";
}
}, 0);
};
return function(composer) {
dom.observe(composer.element, ["cut", "keydown"], clearIfNecessary);
};
})();
/**
* In Opera when the caret is in the first and only item of a list (<ul><li>|</li></ul>) and the list is the first child of the contentEditable element, it's impossible to delete the list by hitting backspace
*
* @param {Object} contentEditableElement The contentEditable element to observe for clearing events
* @exaple
* wysihtml5.quirks.ensureProperClearing(myContentEditableElement);
*/
wysihtml5.quirks.ensureProperClearingOfLists = (function() {
var ELEMENTS_THAT_CONTAIN_LI = ["OL", "UL", "MENU"];
var clearIfNecessary = function(element, contentEditableElement) {
if (!contentEditableElement.firstChild || !wysihtml5.lang.array(ELEMENTS_THAT_CONTAIN_LI).contains(contentEditableElement.firstChild.nodeName)) {
return;
}
var list = dom.getParentElement(element, { nodeName: ELEMENTS_THAT_CONTAIN_LI });
if (!list) {
return;
}
var listIsFirstChildOfContentEditable = list == contentEditableElement.firstChild;
if (!listIsFirstChildOfContentEditable) {
return;
}
var hasOnlyOneListItem = list.childNodes.length <= 1;
if (!hasOnlyOneListItem) {
return;
}
var onlyListItemIsEmpty = list.firstChild ? list.firstChild.innerHTML === "" : true;
if (!onlyListItemIsEmpty) {
return;
}
list.parentNode.removeChild(list);
};
return function(composer) {
dom.observe(composer.element, "keydown", function(event) {
if (event.keyCode !== wysihtml5.BACKSPACE_KEY) {
return;
}
var element = composer.selection.getSelectedNode();
clearIfNecessary(element, composer.element);
});
};
})();
})(wysihtml5);
// See https://bugzilla.mozilla.org/show_bug.cgi?id=664398
//
// In Firefox this:
// var d = document.createElement("div");
// d.innerHTML ='<a href="~"></a>';
// d.innerHTML;
// will result in:
// <a href="%7E"></a>
// which is wrong
(function(wysihtml5) {
var TILDE_ESCAPED = "%7E";
wysihtml5.quirks.getCorrectInnerHTML = function(element) {
var innerHTML = element.innerHTML;
if (innerHTML.indexOf(TILDE_ESCAPED) === -1) {
return innerHTML;
}
var elementsWithTilde = element.querySelectorAll("[href*='~'], [src*='~']"),
url,
urlToSearch,
length,
i;
for (i=0, length=elementsWithTilde.length; i<length; i++) {
url = elementsWithTilde[i].href || elementsWithTilde[i].src;
urlToSearch = wysihtml5.lang.string(url).replace("~").by(TILDE_ESCAPED);
innerHTML = wysihtml5.lang.string(innerHTML).replace(urlToSearch).by(url);
}
return innerHTML;
};
})(wysihtml5);/**
* Some browsers don't insert line breaks when hitting return in a contentEditable element
* - Opera & IE insert new <p> on return
* - Chrome & Safari insert new <div> on return
* - Firefox inserts <br> on return (yippie!)
*
* @param {Element} element
*
* @example
* wysihtml5.quirks.insertLineBreakOnReturn(element);
*/
(function(wysihtml5) {
var dom = wysihtml5.dom,
USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS = ["LI", "P", "H1", "H2", "H3", "H4", "H5", "H6"],
LIST_TAGS = ["UL", "OL", "MENU"];
wysihtml5.quirks.insertLineBreakOnReturn = function(composer) {
function unwrap(selectedNode) {
var parentElement = dom.getParentElement(selectedNode, { nodeName: ["P", "DIV"] }, 2);
if (!parentElement) {
return;
}
var invisibleSpace = document.createTextNode(wysihtml5.INVISIBLE_SPACE);
dom.insert(invisibleSpace).before(parentElement);
dom.replaceWithChildNodes(parentElement);
composer.selection.selectNode(invisibleSpace);
}
function keyDown(event) {
var keyCode = event.keyCode;
if (event.shiftKey || (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY)) {
return;
}
var element = event.target,
selectedNode = composer.selection.getSelectedNode(),
blockElement = dom.getParentElement(selectedNode, { nodeName: USE_NATIVE_LINE_BREAK_WHEN_CARET_INSIDE_TAGS }, 4);
if (blockElement) {
// Some browsers create <p> elements after leaving a list
// check after keydown of backspace and return whether a <p> got inserted and unwrap it
if (blockElement.nodeName === "LI" && (keyCode === wysihtml5.ENTER_KEY || keyCode === wysihtml5.BACKSPACE_KEY)) {
setTimeout(function() {
var selectedNode = composer.selection.getSelectedNode(),
list,
div;
if (!selectedNode) {
return;
}
list = dom.getParentElement(selectedNode, {
nodeName: LIST_TAGS
}, 2);
if (list) {
return;
}
unwrap(selectedNode);
}, 0);
} else if (blockElement.nodeName.match(/H[1-6]/) && keyCode === wysihtml5.ENTER_KEY) {
setTimeout(function() {
unwrap(composer.selection.getSelectedNode());
}, 0);
}
return;
}
if (keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) {
composer.commands.exec("insertLineBreak");
event.preventDefault();
}
}
// keypress doesn't fire when you hit backspace
dom.observe(composer.element.ownerDocument, "keydown", keyDown);
};
})(wysihtml5);/**
* Force rerendering of a given element
* Needed to fix display misbehaviors of IE
*
* @param {Element} element The element object which needs to be rerendered
* @example
* wysihtml5.quirks.redraw(document.body);
*/
(function(wysihtml5) {
var CLASS_NAME = "wysihtml5-quirks-redraw";
wysihtml5.quirks.redraw = function(element) {
wysihtml5.dom.addClass(element, CLASS_NAME);
wysihtml5.dom.removeClass(element, CLASS_NAME);
// Following hack is needed for firefox to make sure that image resize handles are properly removed
try {
var doc = element.ownerDocument;
doc.execCommand("italic", false, null);
doc.execCommand("italic", false, null);
} catch(e) {}
};
})(wysihtml5);/**
* Selection API
*
* @example
* var selection = new wysihtml5.Selection(editor);
*/
(function(wysihtml5) {
var dom = wysihtml5.dom;
function _getCumulativeOffsetTop(element) {
var top = 0;
if (element.parentNode) {
do {
top += element.offsetTop || 0;
element = element.offsetParent;
} while (element);
}
return top;
}
wysihtml5.Selection = Base.extend(
/** @scope wysihtml5.Selection.prototype */ {
constructor: function(editor) {
// Make sure that our external range library is initialized
window.rangy.init();
this.editor = editor;
this.composer = editor.composer;
this.doc = this.composer.doc;
},
/**
* Get the current selection as a bookmark to be able to later restore it
*
* @return {Object} An object that represents the current selection
*/
getBookmark: function() {
var range = this.getRange();
return range && range.cloneRange();
},
/**
* Restore a selection retrieved via wysihtml5.Selection.prototype.getBookmark
*
* @param {Object} bookmark An object that represents the current selection
*/
setBookmark: function(bookmark) {
if (!bookmark) {
return;
}
this.setSelection(bookmark);
},
/**
* Set the caret in front of the given node
*
* @param {Object} node The element or text node where to position the caret in front of
* @example
* selection.setBefore(myElement);
*/
setBefore: function(node) {
var range = rangy.createRange(this.doc);
range.setStartBefore(node);
range.setEndBefore(node);
return this.setSelection(range);
},
/**
* Set the caret after the given node
*
* @param {Object} node The element or text node where to position the caret in front of
* @example
* selection.setBefore(myElement);
*/
setAfter: function(node) {
var range = rangy.createRange(this.doc);
range.setStartAfter(node);
range.setEndAfter(node);
return this.setSelection(range);
},
/**
* Ability to select/mark nodes
*
* @param {Element} node The node/element to select
* @example
* selection.selectNode(document.getElementById("my-image"));
*/
selectNode: function(node) {
var range = rangy.createRange(this.doc),
isElement = node.nodeType === wysihtml5.ELEMENT_NODE,
canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : (node.nodeName !== "IMG"),
content = isElement ? node.innerHTML : node.data,
isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE),
displayStyle = dom.getStyle("display").from(node),
isBlockElement = (displayStyle === "block" || displayStyle === "list-item");
if (isEmpty && isElement && canHaveHTML) {
// Make sure that caret is visible in node by inserting a zero width no breaking space
try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {}
}
if (canHaveHTML) {
range.selectNodeContents(node);
} else {
range.selectNode(node);
}
if (canHaveHTML && isEmpty && isElement) {
range.collapse(isBlockElement);
} else if (canHaveHTML && isEmpty) {
range.setStartAfter(node);
range.setEndAfter(node);
}
this.setSelection(range);
},
/**
* Get the node which contains the selection
*
* @param {Boolean} [controlRange] (only IE) Whether it should return the selected ControlRange element when the selection type is a "ControlRange"
* @return {Object} The node that contains the caret
* @example
* var nodeThatContainsCaret = selection.getSelectedNode();
*/
getSelectedNode: function(controlRange) {
var selection,
range;
if (controlRange && this.doc.selection && this.doc.selection.type === "Control") {
range = this.doc.selection.createRange();
if (range && range.length) {
return range.item(0);
}
}
selection = this.getSelection(this.doc);
if (selection.focusNode === selection.anchorNode) {
return selection.focusNode;
} else {
range = this.getRange(this.doc);
return range ? range.commonAncestorContainer : this.doc.body;
}
},
executeAndRestore: function(method, restoreScrollPosition) {
var body = this.doc.body,
oldScrollTop = restoreScrollPosition && body.scrollTop,
oldScrollLeft = restoreScrollPosition && body.scrollLeft,
className = "_wysihtml5-temp-placeholder",
placeholderHTML = '<span class="' + className + '">' + wysihtml5.INVISIBLE_SPACE + '</span>',
range = this.getRange(this.doc),
newRange;
// Nothing selected, execute and say goodbye
if (!range) {
method(body, body);
return;
}
var node = range.createContextualFragment(placeholderHTML);
range.insertNode(node);
// Make sure that a potential error doesn't cause our placeholder element to be left as a placeholder
try {
method(range.startContainer, range.endContainer);
} catch(e3) {
setTimeout(function() { throw e3; }, 0);
}
caretPlaceholder = this.doc.querySelector("." + className);
if (caretPlaceholder) {
newRange = rangy.createRange(this.doc);
newRange.selectNode(caretPlaceholder);
newRange.deleteContents();
this.setSelection(newRange);
} else {
// fallback for when all hell breaks loose
body.focus();
}
if (restoreScrollPosition) {
body.scrollTop = oldScrollTop;
body.scrollLeft = oldScrollLeft;
}
// Remove it again, just to make sure that the placeholder is definitely out of the dom tree
try {
caretPlaceholder.parentNode.removeChild(caretPlaceholder);
} catch(e4) {}
},
/**
* Different approach of preserving the selection (doesn't modify the dom)
* Takes all text nodes in the selection and saves the selection position in the first and last one
*/
executeAndRestoreSimple: function(method) {
var range = this.getRange(),
body = this.doc.body,
newRange,
firstNode,
lastNode,
textNodes,
rangeBackup;
// Nothing selected, execute and say goodbye
if (!range) {
method(body, body);
return;
}
textNodes = range.getNodes([3]);
firstNode = textNodes[0] || range.startContainer;
lastNode = textNodes[textNodes.length - 1] || range.endContainer;
rangeBackup = {
collapsed: range.collapsed,
startContainer: firstNode,
startOffset: firstNode === range.startContainer ? range.startOffset : 0,
endContainer: lastNode,
endOffset: lastNode === range.endContainer ? range.endOffset : lastNode.length
};
try {
method(range.startContainer, range.endContainer);
} catch(e) {
setTimeout(function() { throw e; }, 0);
}
newRange = rangy.createRange(this.doc);
try { newRange.setStart(rangeBackup.startContainer, rangeBackup.startOffset); } catch(e1) {}
try { newRange.setEnd(rangeBackup.endContainer, rangeBackup.endOffset); } catch(e2) {}
try { this.setSelection(newRange); } catch(e3) {}
},
/**
* Insert html at the caret position and move the cursor after the inserted html
*
* @param {String} html HTML string to insert
* @example
* selection.insertHTML("<p>foobar</p>");
*/
insertHTML: function(html) {
var range = rangy.createRange(this.doc),
node = range.createContextualFragment(html),
lastChild = node.lastChild;
this.insertNode(node);
if (lastChild) {
this.setAfter(lastChild);
}
},
/**
* Insert a node at the caret position and move the cursor behind it
*
* @param {Object} node HTML string to insert
* @example
* selection.insertNode(document.createTextNode("foobar"));
*/
insertNode: function(node) {
var range = this.getRange();
if (range) {
range.insertNode(node);
}
},
/**
* Wraps current selection with the given node
*
* @param {Object} node The node to surround the selected elements with
*/
surround: function(node) {
var range = this.getRange();
if (!range) {
return;
}
try {
// This only works when the range boundaries are not overlapping other elements
range.surroundContents(node);
this.selectNode(node);
} catch(e) {
// fallback
node.appendChild(range.extractContents());
range.insertNode(node);
}
},
/**
* Scroll the current caret position into the view
* FIXME: This is a bit hacky, there might be a smarter way of doing this
*
* @example
* selection.scrollIntoView();
*/
scrollIntoView: function() {
var doc = this.doc,
hasScrollBars = doc.documentElement.scrollHeight > doc.documentElement.offsetHeight,
tempElement = doc._wysihtml5ScrollIntoViewElement = doc._wysihtml5ScrollIntoViewElement || (function() {
var element = doc.createElement("span");
// The element needs content in order to be able to calculate it's position properly
element.innerHTML = wysihtml5.INVISIBLE_SPACE;
return element;
})(),
offsetTop;
if (hasScrollBars) {
this.insertNode(tempElement);
offsetTop = _getCumulativeOffsetTop(tempElement);
tempElement.parentNode.removeChild(tempElement);
if (offsetTop > doc.body.scrollTop) {
doc.body.scrollTop = offsetTop;
}
}
},
/**
* Select line where the caret is in
*/
selectLine: function() {
if (wysihtml5.browser.supportsSelectionModify()) {
this._selectLine_W3C();
} else if (this.doc.selection) {
this._selectLine_MSIE();
}
},
/**
* See https://developer.mozilla.org/en/DOM/Selection/modify
*/
_selectLine_W3C: function() {
var win = this.doc.defaultView,
selection = win.getSelection();
selection.modify("extend", "left", "lineboundary");
selection.modify("extend", "right", "lineboundary");
},
_selectLine_MSIE: function() {
var range = this.doc.selection.createRange(),
rangeTop = range.boundingTop,
rangeHeight = range.boundingHeight,
scrollWidth = this.doc.body.scrollWidth,
rangeBottom,
rangeEnd,
measureNode,
i,
j;
if (!range.moveToPoint) {
return;
}
if (rangeTop === 0) {
// Don't know why, but when the selection ends at the end of a line
// range.boundingTop is 0
measureNode = this.doc.createElement("span");
this.insertNode(measureNode);
rangeTop = measureNode.offsetTop;
measureNode.parentNode.removeChild(measureNode);
}
rangeTop += 1;
for (i=-10; i<scrollWidth; i+=2) {
try {
range.moveToPoint(i, rangeTop);
break;
} catch(e1) {}
}
// Investigate the following in order to handle multi line selections
// rangeBottom = rangeTop + (rangeHeight ? (rangeHeight - 1) : 0);
rangeBottom = rangeTop;
rangeEnd = this.doc.selection.createRange();
for (j=scrollWidth; j>=0; j--) {
try {
rangeEnd.moveToPoint(j, rangeBottom);
break;
} catch(e2) {}
}
range.setEndPoint("EndToEnd", rangeEnd);
range.select();
},
getText: function() {
var selection = this.getSelection();
return selection ? selection.toString() : "";
},
getNodes: function(nodeType, filter) {
var range = this.getRange();
if (range) {
return range.getNodes([nodeType], filter);
} else {
return [];
}
},
getRange: function() {
var selection = this.getSelection();
return selection && selection.rangeCount && selection.getRangeAt(0);
},
getSelection: function() {
return rangy.getSelection(this.doc.defaultView || this.doc.parentWindow);
},
setSelection: function(range) {
var win = this.doc.defaultView || this.doc.parentWindow,
selection = rangy.getSelection(win);
return selection.setSingleRange(range);
}
});
})(wysihtml5);
/**
* Inspired by the rangy CSS Applier module written by Tim Down and licensed under the MIT license.
* http://code.google.com/p/rangy/
*
* changed in order to be able ...
* - to use custom tags
* - to detect and replace similar css classes via reg exp
*/
(function(wysihtml5, rangy) {
var defaultTagName = "span";
var REG_EXP_WHITE_SPACE = /\s+/g;
function hasClass(el, cssClass, regExp) {
if (!el.className) {
return false;
}
var matchingClassNames = el.className.match(regExp) || [];
return matchingClassNames[matchingClassNames.length - 1] === cssClass;
}
function addClass(el, cssClass, regExp) {
if (el.className) {
removeClass(el, regExp);
el.className += " " + cssClass;
} else {
el.className = cssClass;
}
}
function removeClass(el, regExp) {
if (el.className) {
el.className = el.className.replace(regExp, "");
}
}
function hasSameClasses(el1, el2) {
return el1.className.replace(REG_EXP_WHITE_SPACE, " ") == el2.className.replace(REG_EXP_WHITE_SPACE, " ");
}
function replaceWithOwnChildren(el) {
var parent = el.parentNode;
while (el.firstChild) {
parent.insertBefore(el.firstChild, el);
}
parent.removeChild(el);
}
function elementsHaveSameNonClassAttributes(el1, el2) {
if (el1.attributes.length != el2.attributes.length) {
return false;
}
for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) {
attr1 = el1.attributes[i];
name = attr1.name;
if (name != "class") {
attr2 = el2.attributes.getNamedItem(name);
if (attr1.specified != attr2.specified) {
return false;
}
if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) {
return false;
}
}
}
return true;
}
function isSplitPoint(node, offset) {
if (rangy.dom.isCharacterDataNode(node)) {
if (offset == 0) {
return !!node.previousSibling;
} else if (offset == node.length) {
return !!node.nextSibling;
} else {
return true;
}
}
return offset > 0 && offset < node.childNodes.length;
}
function splitNodeAt(node, descendantNode, descendantOffset) {
var newNode;
if (rangy.dom.isCharacterDataNode(descendantNode)) {
if (descendantOffset == 0) {
descendantOffset = rangy.dom.getNodeIndex(descendantNode);
descendantNode = descendantNode.parentNode;
} else if (descendantOffset == descendantNode.length) {
descendantOffset = rangy.dom.getNodeIndex(descendantNode) + 1;
descendantNode = descendantNode.parentNode;
} else {
newNode = rangy.dom.splitDataNode(descendantNode, descendantOffset);
}
}
if (!newNode) {
newNode = descendantNode.cloneNode(false);
if (newNode.id) {
newNode.removeAttribute("id");
}
var child;
while ((child = descendantNode.childNodes[descendantOffset])) {
newNode.appendChild(child);
}
rangy.dom.insertAfter(newNode, descendantNode);
}
return (descendantNode == node) ? newNode : splitNodeAt(node, newNode.parentNode, rangy.dom.getNodeIndex(newNode));
}
function Merge(firstNode) {
this.isElementMerge = (firstNode.nodeType == wysihtml5.ELEMENT_NODE);
this.firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode;
this.textNodes = [this.firstTextNode];
}
Merge.prototype = {
doMerge: function() {
var textBits = [], textNode, parent, text;
for (var i = 0, len = this.textNodes.length; i < len; ++i) {
textNode = this.textNodes[i];
parent = textNode.parentNode;
textBits[i] = textNode.data;
if (i) {
parent.removeChild(textNode);
if (!parent.hasChildNodes()) {
parent.parentNode.removeChild(parent);
}
}
}
this.firstTextNode.data = text = textBits.join("");
return text;
},
getLength: function() {
var i = this.textNodes.length, len = 0;
while (i--) {
len += this.textNodes[i].length;
}
return len;
},
toString: function() {
var textBits = [];
for (var i = 0, len = this.textNodes.length; i < len; ++i) {
textBits[i] = "'" + this.textNodes[i].data + "'";
}
return "[Merge(" + textBits.join(",") + ")]";
}
};
function HTMLApplier(tagNames, cssClass, similarClassRegExp, normalize) {
this.tagNames = tagNames || [defaultTagName];
this.cssClass = cssClass || "";
this.similarClassRegExp = similarClassRegExp;
this.normalize = normalize;
this.applyToAnyTagName = false;
}
HTMLApplier.prototype = {
getAncestorWithClass: function(node) {
var cssClassMatch;
while (node) {
cssClassMatch = this.cssClass ? hasClass(node, this.cssClass, this.similarClassRegExp) : true;
if (node.nodeType == wysihtml5.ELEMENT_NODE && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssClassMatch) {
return node;
}
node = node.parentNode;
}
return false;
},
// Normalizes nodes after applying a CSS class to a Range.
postApply: function(textNodes, range) {
var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1];
var merges = [], currentMerge;
var rangeStartNode = firstNode, rangeEndNode = lastNode;
var rangeStartOffset = 0, rangeEndOffset = lastNode.length;
var textNode, precedingTextNode;
for (var i = 0, len = textNodes.length; i < len; ++i) {
textNode = textNodes[i];
precedingTextNode = this.getAdjacentMergeableTextNode(textNode.parentNode, false);
if (precedingTextNode) {
if (!currentMerge) {
currentMerge = new Merge(precedingTextNode);
merges.push(currentMerge);
}
currentMerge.textNodes.push(textNode);
if (textNode === firstNode) {
rangeStartNode = currentMerge.firstTextNode;
rangeStartOffset = rangeStartNode.length;
}
if (textNode === lastNode) {
rangeEndNode = currentMerge.firstTextNode;
rangeEndOffset = currentMerge.getLength();
}
} else {
currentMerge = null;
}
}
// Test whether the first node after the range needs merging
var nextTextNode = this.getAdjacentMergeableTextNode(lastNode.parentNode, true);
if (nextTextNode) {
if (!currentMerge) {
currentMerge = new Merge(lastNode);
merges.push(currentMerge);
}
currentMerge.textNodes.push(nextTextNode);
}
// Do the merges
if (merges.length) {
for (i = 0, len = merges.length; i < len; ++i) {
merges[i].doMerge();
}
// Set the range boundaries
range.setStart(rangeStartNode, rangeStartOffset);
range.setEnd(rangeEndNode, rangeEndOffset);
}
},
getAdjacentMergeableTextNode: function(node, forward) {
var isTextNode = (node.nodeType == wysihtml5.TEXT_NODE);
var el = isTextNode ? node.parentNode : node;
var adjacentNode;
var propName = forward ? "nextSibling" : "previousSibling";
if (isTextNode) {
// Can merge if the node's previous/next sibling is a text node
adjacentNode = node[propName];
if (adjacentNode && adjacentNode.nodeType == wysihtml5.TEXT_NODE) {
return adjacentNode;
}
} else {
// Compare element with its sibling
adjacentNode = el[propName];
if (adjacentNode && this.areElementsMergeable(node, adjacentNode)) {
return adjacentNode[forward ? "firstChild" : "lastChild"];
}
}
return null;
},
areElementsMergeable: function(el1, el2) {
return rangy.dom.arrayContains(this.tagNames, (el1.tagName || "").toLowerCase())
&& rangy.dom.arrayContains(this.tagNames, (el2.tagName || "").toLowerCase())
&& hasSameClasses(el1, el2)
&& elementsHaveSameNonClassAttributes(el1, el2);
},
createContainer: function(doc) {
var el = doc.createElement(this.tagNames[0]);
if (this.cssClass) {
el.className = this.cssClass;
}
return el;
},
applyToTextNode: function(textNode) {
var parent = textNode.parentNode;
if (parent.childNodes.length == 1 && rangy.dom.arrayContains(this.tagNames, parent.tagName.toLowerCase())) {
if (this.cssClass) {
addClass(parent, this.cssClass, this.similarClassRegExp);
}
} else {
var el = this.createContainer(rangy.dom.getDocument(textNode));
textNode.parentNode.insertBefore(el, textNode);
el.appendChild(textNode);
}
},
isRemovable: function(el) {
return rangy.dom.arrayContains(this.tagNames, el.tagName.toLowerCase()) && wysihtml5.lang.string(el.className).trim() == this.cssClass;
},
undoToTextNode: function(textNode, range, ancestorWithClass) {
if (!range.containsNode(ancestorWithClass)) {
// Split out the portion of the ancestor from which we can remove the CSS class
var ancestorRange = range.cloneRange();
ancestorRange.selectNode(ancestorWithClass);
if (ancestorRange.isPointInRange(range.endContainer, range.endOffset) && isSplitPoint(range.endContainer, range.endOffset)) {
splitNodeAt(ancestorWithClass, range.endContainer, range.endOffset);
range.setEndAfter(ancestorWithClass);
}
if (ancestorRange.isPointInRange(range.startContainer, range.startOffset) && isSplitPoint(range.startContainer, range.startOffset)) {
ancestorWithClass = splitNodeAt(ancestorWithClass, range.startContainer, range.startOffset);
}
}
if (this.similarClassRegExp) {
removeClass(ancestorWithClass, this.similarClassRegExp);
}
if (this.isRemovable(ancestorWithClass)) {
replaceWithOwnChildren(ancestorWithClass);
}
},
applyToRange: function(range) {
var textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
if (!textNodes.length) {
try {
var node = this.createContainer(range.endContainer.ownerDocument);
range.surroundContents(node);
this.selectNode(range, node);
return;
} catch(e) {}
}
range.splitBoundaries();
textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
if (textNodes.length) {
var textNode;
for (var i = 0, len = textNodes.length; i < len; ++i) {
textNode = textNodes[i];
if (!this.getAncestorWithClass(textNode)) {
this.applyToTextNode(textNode);
}
}
range.setStart(textNodes[0], 0);
textNode = textNodes[textNodes.length - 1];
range.setEnd(textNode, textNode.length);
if (this.normalize) {
this.postApply(textNodes, range);
}
}
},
undoToRange: function(range) {
var textNodes = range.getNodes([wysihtml5.TEXT_NODE]), textNode, ancestorWithClass;
if (textNodes.length) {
range.splitBoundaries();
textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
} else {
var doc = range.endContainer.ownerDocument,
node = doc.createTextNode(wysihtml5.INVISIBLE_SPACE);
range.insertNode(node);
range.selectNode(node);
textNodes = [node];
}
for (var i = 0, len = textNodes.length; i < len; ++i) {
textNode = textNodes[i];
ancestorWithClass = this.getAncestorWithClass(textNode);
if (ancestorWithClass) {
this.undoToTextNode(textNode, range, ancestorWithClass);
}
}
if (len == 1) {
this.selectNode(range, textNodes[0]);
} else {
range.setStart(textNodes[0], 0);
textNode = textNodes[textNodes.length - 1];
range.setEnd(textNode, textNode.length);
if (this.normalize) {
this.postApply(textNodes, range);
}
}
},
selectNode: function(range, node) {
var isElement = node.nodeType === wysihtml5.ELEMENT_NODE,
canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : true,
content = isElement ? node.innerHTML : node.data,
isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE);
if (isEmpty && isElement && canHaveHTML) {
// Make sure that caret is visible in node by inserting a zero width no breaking space
try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {}
}
range.selectNodeContents(node);
if (isEmpty && isElement) {
range.collapse(false);
} else if (isEmpty) {
range.setStartAfter(node);
range.setEndAfter(node);
}
},
getTextSelectedByRange: function(textNode, range) {
var textRange = range.cloneRange();
textRange.selectNodeContents(textNode);
var intersectionRange = textRange.intersection(range);
var text = intersectionRange ? intersectionRange.toString() : "";
textRange.detach();
return text;
},
isAppliedToRange: function(range) {
var ancestors = [],
ancestor,
textNodes = range.getNodes([wysihtml5.TEXT_NODE]);
if (!textNodes.length) {
ancestor = this.getAncestorWithClass(range.startContainer);
return ancestor ? [ancestor] : false;
}
for (var i = 0, len = textNodes.length, selectedText; i < len; ++i) {
selectedText = this.getTextSelectedByRange(textNodes[i], range);
ancestor = this.getAncestorWithClass(textNodes[i]);
if (selectedText != "" && !ancestor) {
return false;
} else {
ancestors.push(ancestor);
}
}
return ancestors;
},
toggleRange: function(range) {
if (this.isAppliedToRange(range)) {
this.undoToRange(range);
} else {
this.applyToRange(range);
}
}
};
wysihtml5.selection.HTMLApplier = HTMLApplier;
})(wysihtml5, rangy);/**
* Rich Text Query/Formatting Commands
*
* @example
* var commands = new wysihtml5.Commands(editor);
*/
wysihtml5.Commands = Base.extend(
/** @scope wysihtml5.Commands.prototype */ {
constructor: function(editor) {
this.editor = editor;
this.composer = editor.composer;
this.doc = this.composer.doc;
},
/**
* Check whether the browser supports the given command
*
* @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList")
* @example
* commands.supports("createLink");
*/
support: function(command) {
return wysihtml5.browser.supportsCommand(this.doc, command);
},
/**
* Check whether the browser supports the given command
*
* @param {String} command The command string which to execute (eg. "bold", "italic", "insertUnorderedList")
* @param {String} [value] The command value parameter, needed for some commands ("createLink", "insertImage", ...), optional for commands that don't require one ("bold", "underline", ...)
* @example
* commands.exec("insertImage", "http://a1.twimg.com/profile_images/113868655/schrei_twitter_reasonably_small.jpg");
*/
exec: function(command, value) {
var obj = wysihtml5.commands[command],
args = wysihtml5.lang.array(arguments).get(),
method = obj && obj.exec,
result = null;
this.editor.fire("beforecommand:composer");
if (method) {
args.unshift(this.composer);
result = method.apply(obj, args);
} else {
try {
// try/catch for buggy firefox
result = this.doc.execCommand(command, false, value);
} catch(e) {}
}
this.editor.fire("aftercommand:composer");
return result;
},
/**
* Check whether the current command is active
* If the caret is within a bold text, then calling this with command "bold" should return true
*
* @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList")
* @param {String} [commandValue] The command value parameter (eg. for "insertImage" the image src)
* @return {Boolean} Whether the command is active
* @example
* var isCurrentSelectionBold = commands.state("bold");
*/
state: function(command, commandValue) {
var obj = wysihtml5.commands[command],
args = wysihtml5.lang.array(arguments).get(),
method = obj && obj.state;
if (method) {
args.unshift(this.composer);
return method.apply(obj, args);
} else {
try {
// try/catch for buggy firefox
return this.doc.queryCommandState(command);
} catch(e) {
return false;
}
}
},
/**
* Get the current command's value
*
* @param {String} command The command string which to check (eg. "formatBlock")
* @return {String} The command value
* @example
* var currentBlockElement = commands.value("formatBlock");
*/
value: function(command) {
var obj = wysihtml5.commands[command],
method = obj && obj.value;
if (method) {
return method.call(obj, this.composer, command);
} else {
try {
// try/catch for buggy firefox
return this.doc.queryCommandValue(command);
} catch(e) {
return null;
}
}
}
});
(function(wysihtml5) {
var undef;
wysihtml5.commands.bold = {
exec: function(composer, command) {
return wysihtml5.commands.formatInline.exec(composer, command, "b");
},
state: function(composer, command, color) {
// element.ownerDocument.queryCommandState("bold") results:
// firefox: only <b>
// chrome: <b>, <strong>, <h1>, <h2>, ...
// ie: <b>, <strong>
// opera: <b>, <strong>
return wysihtml5.commands.formatInline.state(composer, command, "b");
},
value: function() {
return undef;
}
};
})(wysihtml5);
(function(wysihtml5) {
var undef,
NODE_NAME = "A",
dom = wysihtml5.dom;
function _removeFormat(composer, anchors) {
var length = anchors.length,
i = 0,
anchor,
codeElement,
textContent;
for (; i<length; i++) {
anchor = anchors[i];
codeElement = dom.getParentElement(anchor, { nodeName: "code" });
textContent = dom.getTextContent(anchor);
// if <a> contains url-like text content, rename it to <code> to prevent re-autolinking
// else replace <a> with its childNodes
if (textContent.match(dom.autoLink.URL_REG_EXP) && !codeElement) {
// <code> element is used to prevent later auto-linking of the content
codeElement = dom.renameElement(anchor, "code");
} else {
dom.replaceWithChildNodes(anchor);
}
}
}
function _format(composer, attributes) {
var doc = composer.doc,
tempClass = "_wysihtml5-temp-" + (+new Date()),
tempClassRegExp = /non-matching-class/g,
i = 0,
length,
anchors,
anchor,
hasElementChild,
isEmpty,
elementToSetCaretAfter,
textContent,
whiteSpace,
j;
wysihtml5.commands.formatInline.exec(composer, undef, NODE_NAME, tempClass, tempClassRegExp);
anchors = doc.querySelectorAll(NODE_NAME + "." + tempClass);
length = anchors.length;
for (; i<length; i++) {
anchor = anchors[i];
anchor.removeAttribute("class");
for (j in attributes) {
anchor.setAttribute(j, attributes[j]);
}
}
elementToSetCaretAfter = anchor;
if (length === 1) {
textContent = dom.getTextContent(anchor);
hasElementChild = !!anchor.querySelector("*");
isEmpty = textContent === "" || textContent === wysihtml5.INVISIBLE_SPACE;
if (!hasElementChild && isEmpty) {
dom.setTextContent(anchor, attributes.text || anchor.href);
whiteSpace = doc.createTextNode(" ");
composer.selection.setAfter(anchor);
composer.selection.insertNode(whiteSpace);
elementToSetCaretAfter = whiteSpace;
}
}
composer.selection.setAfter(elementToSetCaretAfter);
}
wysihtml5.commands.createLink = {
/**
* TODO: Use HTMLApplier or formatInline here
*
* Turns selection into a link
* If selection is already a link, it removes the link and wraps it with a <code> element
* The <code> element is needed to avoid auto linking
*
* @example
* // either ...
* wysihtml5.commands.createLink.exec(composer, "createLink", "http://www.google.de");
* // ... or ...
* wysihtml5.commands.createLink.exec(composer, "createLink", { href: "http://www.google.de", target: "_blank" });
*/
exec: function(composer, command, value) {
var anchors = this.state(composer, command);
if (anchors) {
// Selection contains links
composer.selection.executeAndRestore(function() {
_removeFormat(composer, anchors);
});
} else {
// Create links
value = typeof(value) === "object" ? value : { href: value };
_format(composer, value);
}
},
state: function(composer, command) {
return wysihtml5.commands.formatInline.state(composer, command, "A");
},
value: function() {
return undef;
}
};
})(wysihtml5);/**
* document.execCommand("fontSize") will create either inline styles (firefox, chrome) or use font tags
* which we don't want
* Instead we set a css class
*/
(function(wysihtml5) {
var undef,
REG_EXP = /wysiwyg-font-size-[a-z\-]+/g;
wysihtml5.commands.fontSize = {
exec: function(composer, command, size) {
return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP);
},
state: function(composer, command, size) {
return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP);
},
value: function() {
return undef;
}
};
})(wysihtml5);
/**
* document.execCommand("foreColor") will create either inline styles (firefox, chrome) or use font tags
* which we don't want
* Instead we set a css class
*/
(function(wysihtml5) {
var undef,
REG_EXP = /wysiwyg-color-[a-z]+/g;
wysihtml5.commands.foreColor = {
exec: function(composer, command, color) {
return wysihtml5.commands.formatInline.exec(composer, command, "span", "wysiwyg-color-" + color, REG_EXP);
},
state: function(composer, command, color) {
return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-color-" + color, REG_EXP);
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef,
dom = wysihtml5.dom,
DEFAULT_NODE_NAME = "DIV",
// Following elements are grouped
// when the caret is within a H1 and the H4 is invoked, the H1 should turn into H4
// instead of creating a H4 within a H1 which would result in semantically invalid html
BLOCK_ELEMENTS_GROUP = ["H1", "H2", "H3", "H4", "H5", "H6", "P", "BLOCKQUOTE", DEFAULT_NODE_NAME];
/**
* Remove similiar classes (based on classRegExp)
* and add the desired class name
*/
function _addClass(element, className, classRegExp) {
if (element.className) {
_removeClass(element, classRegExp);
element.className += " " + className;
} else {
element.className = className;
}
}
function _removeClass(element, classRegExp) {
element.className = element.className.replace(classRegExp, "");
}
/**
* Check whether given node is a text node and whether it's empty
*/
function _isBlankTextNode(node) {
return node.nodeType === wysihtml5.TEXT_NODE && !wysihtml5.lang.string(node.data).trim();
}
/**
* Returns previous sibling node that is not a blank text node
*/
function _getPreviousSiblingThatIsNotBlank(node) {
var previousSibling = node.previousSibling;
while (previousSibling && _isBlankTextNode(previousSibling)) {
previousSibling = previousSibling.previousSibling;
}
return previousSibling;
}
/**
* Returns next sibling node that is not a blank text node
*/
function _getNextSiblingThatIsNotBlank(node) {
var nextSibling = node.nextSibling;
while (nextSibling && _isBlankTextNode(nextSibling)) {
nextSibling = nextSibling.nextSibling;
}
return nextSibling;
}
/**
* Adds line breaks before and after the given node if the previous and next siblings
* aren't already causing a visual line break (block element or <br>)
*/
function _addLineBreakBeforeAndAfter(node) {
var doc = node.ownerDocument,
nextSibling = _getNextSiblingThatIsNotBlank(node),
previousSibling = _getPreviousSiblingThatIsNotBlank(node);
if (nextSibling && !_isLineBreakOrBlockElement(nextSibling)) {
node.parentNode.insertBefore(doc.createElement("br"), nextSibling);
}
if (previousSibling && !_isLineBreakOrBlockElement(previousSibling)) {
node.parentNode.insertBefore(doc.createElement("br"), node);
}
}
/**
* Removes line breaks before and after the given node
*/
function _removeLineBreakBeforeAndAfter(node) {
var nextSibling = _getNextSiblingThatIsNotBlank(node),
previousSibling = _getPreviousSiblingThatIsNotBlank(node);
if (nextSibling && _isLineBreak(nextSibling)) {
nextSibling.parentNode.removeChild(nextSibling);
}
if (previousSibling && _isLineBreak(previousSibling)) {
previousSibling.parentNode.removeChild(previousSibling);
}
}
function _removeLastChildIfLineBreak(node) {
var lastChild = node.lastChild;
if (lastChild && _isLineBreak(lastChild)) {
lastChild.parentNode.removeChild(lastChild);
}
}
function _isLineBreak(node) {
return node.nodeName === "BR";
}
/**
* Checks whether the elment causes a visual line break
* (<br> or block elements)
*/
function _isLineBreakOrBlockElement(element) {
if (_isLineBreak(element)) {
return true;
}
if (dom.getStyle("display").from(element) === "block") {
return true;
}
return false;
}
/**
* Execute native query command
* and if necessary modify the inserted node's className
*/
function _execCommand(doc, command, nodeName, className) {
if (className) {
var eventListener = dom.observe(doc, "DOMNodeInserted", function(event) {
var target = event.target,
displayStyle;
if (target.nodeType !== wysihtml5.ELEMENT_NODE) {
return;
}
displayStyle = dom.getStyle("display").from(target);
if (displayStyle.substr(0, 6) !== "inline") {
// Make sure that only block elements receive the given class
target.className += " " + className;
}
});
}
doc.execCommand(command, false, nodeName);
if (eventListener) {
eventListener.stop();
}
}
function _selectLineAndWrap(composer, element) {
composer.selection.selectLine();
composer.selection.surround(element);
_removeLineBreakBeforeAndAfter(element);
_removeLastChildIfLineBreak(element);
composer.selection.selectNode(element);
}
function _hasClasses(element) {
return !!wysihtml5.lang.string(element.className).trim();
}
wysihtml5.commands.formatBlock = {
exec: function(composer, command, nodeName, className, classRegExp) {
var doc = composer.doc,
blockElement = this.state(composer, command, nodeName, className, classRegExp),
selectedNode;
nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName;
if (blockElement) {
composer.selection.executeAndRestoreSimple(function() {
if (classRegExp) {
_removeClass(blockElement, classRegExp);
}
var hasClasses = _hasClasses(blockElement);
if (!hasClasses && blockElement.nodeName === (nodeName || DEFAULT_NODE_NAME)) {
// Insert a line break afterwards and beforewards when there are siblings
// that are not of type line break or block element
_addLineBreakBeforeAndAfter(blockElement);
dom.replaceWithChildNodes(blockElement);
} else if (hasClasses) {
// Make sure that styling is kept by renaming the element to <div> and copying over the class name
dom.renameElement(blockElement, DEFAULT_NODE_NAME);
}
});
return;
}
// Find similiar block element and rename it (<h2 class="foo"></h2> => <h1 class="foo"></h1>)
if (nodeName === null || wysihtml5.lang.array(BLOCK_ELEMENTS_GROUP).contains(nodeName)) {
selectedNode = composer.selection.getSelectedNode();
blockElement = dom.getParentElement(selectedNode, {
nodeName: BLOCK_ELEMENTS_GROUP
});
if (blockElement) {
composer.selection.executeAndRestoreSimple(function() {
// Rename current block element to new block element and add class
if (nodeName) {
blockElement = dom.renameElement(blockElement, nodeName);
}
if (className) {
_addClass(blockElement, className, classRegExp);
}
});
return;
}
}
if (composer.commands.support(command)) {
_execCommand(doc, command, nodeName || DEFAULT_NODE_NAME, className);
return;
}
blockElement = doc.createElement(nodeName || DEFAULT_NODE_NAME);
if (className) {
blockElement.className = className;
}
_selectLineAndWrap(composer, blockElement);
},
state: function(composer, command, nodeName, className, classRegExp) {
nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName;
var selectedNode = composer.selection.getSelectedNode();
return dom.getParentElement(selectedNode, {
nodeName: nodeName,
className: className,
classRegExp: classRegExp
});
},
value: function() {
return undef;
}
};
})(wysihtml5);/**
* formatInline scenarios for tag "B" (| = caret, |foo| = selected text)
*
* #1 caret in unformatted text:
* abcdefg|
* output:
* abcdefg<b>|</b>
*
* #2 unformatted text selected:
* abc|deg|h
* output:
* abc<b>|deg|</b>h
*
* #3 unformatted text selected across boundaries:
* ab|c <span>defg|h</span>
* output:
* ab<b>|c </b><span><b>defg</b>|h</span>
*
* #4 formatted text entirely selected
* <b>|abc|</b>
* output:
* |abc|
*
* #5 formatted text partially selected
* <b>ab|c|</b>
* output:
* <b>ab</b>|c|
*
* #6 formatted text selected across boundaries
* <span>ab|c</span> <b>de|fgh</b>
* output:
* <span>ab|c</span> de|<b>fgh</b>
*/
(function(wysihtml5) {
var undef,
// Treat <b> as <strong> and vice versa
ALIAS_MAPPING = {
"strong": "b",
"em": "i",
"b": "strong",
"i": "em"
},
htmlApplier = {};
function _getTagNames(tagName) {
var alias = ALIAS_MAPPING[tagName];
return alias ? [tagName.toLowerCase(), alias.toLowerCase()] : [tagName.toLowerCase()];
}
function _getApplier(tagName, className, classRegExp) {
var identifier = tagName + ":" + className;
if (!htmlApplier[identifier]) {
htmlApplier[identifier] = new wysihtml5.selection.HTMLApplier(_getTagNames(tagName), className, classRegExp, true);
}
return htmlApplier[identifier];
}
wysihtml5.commands.formatInline = {
exec: function(composer, command, tagName, className, classRegExp) {
var range = composer.selection.getRange();
if (!range) {
return false;
}
_getApplier(tagName, className, classRegExp).toggleRange(range);
composer.selection.setSelection(range);
},
state: function(composer, command, tagName, className, classRegExp) {
var doc = composer.doc,
aliasTagName = ALIAS_MAPPING[tagName] || tagName,
range;
// Check whether the document contains a node with the desired tagName
if (!wysihtml5.dom.hasElementWithTagName(doc, tagName) &&
!wysihtml5.dom.hasElementWithTagName(doc, aliasTagName)) {
return false;
}
// Check whether the document contains a node with the desired className
if (className && !wysihtml5.dom.hasElementWithClassName(doc, className)) {
return false;
}
range = composer.selection.getRange();
if (!range) {
return false;
}
return _getApplier(tagName, className, classRegExp).isAppliedToRange(range);
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef;
wysihtml5.commands.insertHTML = {
exec: function(composer, command, html) {
if (composer.commands.support(command)) {
composer.doc.execCommand(command, false, html);
} else {
composer.selection.insertHTML(html);
}
},
state: function() {
return false;
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var NODE_NAME = "IMG";
wysihtml5.commands.insertImage = {
/**
* Inserts an <img>
* If selection is already an image link, it removes it
*
* @example
* // either ...
* wysihtml5.commands.insertImage.exec(composer, "insertImage", "http://www.google.de/logo.jpg");
* // ... or ...
* wysihtml5.commands.insertImage.exec(composer, "insertImage", { src: "http://www.google.de/logo.jpg", title: "foo" });
*/
exec: function(composer, command, value) {
value = typeof(value) === "object" ? value : { src: value };
var doc = composer.doc,
image = this.state(composer),
textNode,
i,
parent;
if (image) {
// Image already selected, set the caret before it and delete it
composer.selection.setBefore(image);
parent = image.parentNode;
parent.removeChild(image);
// and it's parent <a> too if it hasn't got any other relevant child nodes
wysihtml5.dom.removeEmptyTextNodes(parent);
if (parent.nodeName === "A" && !parent.firstChild) {
composer.selection.setAfter(parent);
parent.parentNode.removeChild(parent);
}
// firefox and ie sometimes don't remove the image handles, even though the image got removed
wysihtml5.quirks.redraw(composer.element);
return;
}
image = doc.createElement(NODE_NAME);
for (i in value) {
image[i] = value[i];
}
composer.selection.insertNode(image);
if (wysihtml5.browser.hasProblemsSettingCaretAfterImg()) {
textNode = doc.createTextNode(wysihtml5.INVISIBLE_SPACE);
composer.selection.insertNode(textNode);
composer.selection.setAfter(textNode);
} else {
composer.selection.setAfter(image);
}
},
state: function(composer) {
var doc = composer.doc,
selectedNode,
text,
imagesInSelection;
if (!wysihtml5.dom.hasElementWithTagName(doc, NODE_NAME)) {
return false;
}
selectedNode = composer.selection.getSelectedNode();
if (!selectedNode) {
return false;
}
if (selectedNode.nodeName === NODE_NAME) {
// This works perfectly in IE
return selectedNode;
}
if (selectedNode.nodeType !== wysihtml5.ELEMENT_NODE) {
return false;
}
text = composer.selection.getText();
text = wysihtml5.lang.string(text).trim();
if (text) {
return false;
}
imagesInSelection = composer.selection.getNodes(wysihtml5.ELEMENT_NODE, function(node) {
return node.nodeName === "IMG";
});
if (imagesInSelection.length !== 1) {
return false;
}
return imagesInSelection[0];
},
value: function(composer) {
var image = this.state(composer);
return image && image.src;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef,
LINE_BREAK = "<br>" + (wysihtml5.browser.needsSpaceAfterLineBreak() ? " " : "");
wysihtml5.commands.insertLineBreak = {
exec: function(composer, command) {
if (composer.commands.support(command)) {
composer.doc.execCommand(command, false, null);
if (!wysihtml5.browser.autoScrollsToCaret()) {
composer.selection.scrollIntoView();
}
} else {
composer.commands.exec("insertHTML", LINE_BREAK);
}
},
state: function() {
return false;
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef;
wysihtml5.commands.insertOrderedList = {
exec: function(composer, command) {
var doc = composer.doc,
selectedNode = composer.selection.getSelectedNode(),
list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }),
otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }),
tempClassName = "_wysihtml5-temp-" + new Date().getTime(),
isEmpty,
tempElement;
if (composer.commands.support(command)) {
doc.execCommand(command, false, null);
return;
}
if (list) {
// Unwrap list
// <ol><li>foo</li><li>bar</li></ol>
// becomes:
// foo<br>bar<br>
composer.selection.executeAndRestoreSimple(function() {
wysihtml5.dom.resolveList(list);
});
} else if (otherList) {
// Turn an unordered list into an ordered list
// <ul><li>foo</li><li>bar</li></ul>
// becomes:
// <ol><li>foo</li><li>bar</li></ol>
composer.selection.executeAndRestoreSimple(function() {
wysihtml5.dom.renameElement(otherList, "ol");
});
} else {
// Create list
composer.commands.exec("formatBlock", "div", tempClassName);
tempElement = doc.querySelector("." + tempClassName);
isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE;
composer.selection.executeAndRestoreSimple(function() {
list = wysihtml5.dom.convertToList(tempElement, "ol");
});
if (isEmpty) {
composer.selection.selectNode(list.querySelector("li"));
}
}
},
state: function(composer) {
var selectedNode = composer.selection.getSelectedNode();
return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" });
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef;
wysihtml5.commands.insertUnorderedList = {
exec: function(composer, command) {
var doc = composer.doc,
selectedNode = composer.selection.getSelectedNode(),
list = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" }),
otherList = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "OL" }),
tempClassName = "_wysihtml5-temp-" + new Date().getTime(),
isEmpty,
tempElement;
if (composer.commands.support(command)) {
doc.execCommand(command, false, null);
return;
}
if (list) {
// Unwrap list
// <ul><li>foo</li><li>bar</li></ul>
// becomes:
// foo<br>bar<br>
composer.selection.executeAndRestoreSimple(function() {
wysihtml5.dom.resolveList(list);
});
} else if (otherList) {
// Turn an ordered list into an unordered list
// <ol><li>foo</li><li>bar</li></ol>
// becomes:
// <ul><li>foo</li><li>bar</li></ul>
composer.selection.executeAndRestoreSimple(function() {
wysihtml5.dom.renameElement(otherList, "ul");
});
} else {
// Create list
composer.commands.exec("formatBlock", "div", tempClassName);
tempElement = doc.querySelector("." + tempClassName);
isEmpty = tempElement.innerHTML === "" || tempElement.innerHTML === wysihtml5.INVISIBLE_SPACE;
composer.selection.executeAndRestoreSimple(function() {
list = wysihtml5.dom.convertToList(tempElement, "ul");
});
if (isEmpty) {
composer.selection.selectNode(list.querySelector("li"));
}
}
},
state: function(composer) {
var selectedNode = composer.selection.getSelectedNode();
return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "UL" });
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef;
wysihtml5.commands.italic = {
exec: function(composer, command) {
return wysihtml5.commands.formatInline.exec(composer, command, "i");
},
state: function(composer, command, color) {
// element.ownerDocument.queryCommandState("italic") results:
// firefox: only <i>
// chrome: <i>, <em>, <blockquote>, ...
// ie: <i>, <em>
// opera: only <i>
return wysihtml5.commands.formatInline.state(composer, command, "i");
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef,
CLASS_NAME = "wysiwyg-text-align-center",
REG_EXP = /wysiwyg-text-align-[a-z]+/g;
wysihtml5.commands.justifyCenter = {
exec: function(composer, command) {
return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
},
state: function(composer, command) {
return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef,
CLASS_NAME = "wysiwyg-text-align-left",
REG_EXP = /wysiwyg-text-align-[a-z]+/g;
wysihtml5.commands.justifyLeft = {
exec: function(composer, command) {
return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
},
state: function(composer, command) {
return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef,
CLASS_NAME = "wysiwyg-text-align-right",
REG_EXP = /wysiwyg-text-align-[a-z]+/g;
wysihtml5.commands.justifyRight = {
exec: function(composer, command) {
return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
},
state: function(composer, command) {
return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP);
},
value: function() {
return undef;
}
};
})(wysihtml5);(function(wysihtml5) {
var undef;
wysihtml5.commands.underline = {
exec: function(composer, command) {
return wysihtml5.commands.formatInline.exec(composer, command, "u");
},
state: function(composer, command) {
return wysihtml5.commands.formatInline.state(composer, command, "u");
},
value: function() {
return undef;
}
};
})(wysihtml5);/**
* Undo Manager for wysihtml5
* slightly inspired by http://rniwa.com/editing/undomanager.html#the-undomanager-interface
*/
(function(wysihtml5) {
var Z_KEY = 90,
Y_KEY = 89,
BACKSPACE_KEY = 8,
DELETE_KEY = 46,
MAX_HISTORY_ENTRIES = 40,
UNDO_HTML = '<span id="_wysihtml5-undo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>',
REDO_HTML = '<span id="_wysihtml5-redo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>',
dom = wysihtml5.dom;
function cleanTempElements(doc) {
var tempElement;
while (tempElement = doc.querySelector("._wysihtml5-temp")) {
tempElement.parentNode.removeChild(tempElement);
}
}
wysihtml5.UndoManager = wysihtml5.lang.Dispatcher.extend(
/** @scope wysihtml5.UndoManager.prototype */ {
constructor: function(editor) {
this.editor = editor;
this.composer = editor.composer;
this.element = this.composer.element;
this.history = [this.composer.getValue()];
this.position = 1;
// Undo manager currently only supported in browsers who have the insertHTML command (not IE)
if (this.composer.commands.support("insertHTML")) {
this._observe();
}
},
_observe: function() {
var that = this,
doc = this.composer.sandbox.getDocument(),
lastKey;
// Catch CTRL+Z and CTRL+Y
dom.observe(this.element, "keydown", function(event) {
if (event.altKey || (!event.ctrlKey && !event.metaKey)) {
return;
}
var keyCode = event.keyCode,
isUndo = keyCode === Z_KEY && !event.shiftKey,
isRedo = (keyCode === Z_KEY && event.shiftKey) || (keyCode === Y_KEY);
if (isUndo) {
that.undo();
event.preventDefault();
} else if (isRedo) {
that.redo();
event.preventDefault();
}
});
// Catch delete and backspace
dom.observe(this.element, "keydown", function(event) {
var keyCode = event.keyCode;
if (keyCode === lastKey) {
return;
}
lastKey = keyCode;
if (keyCode === BACKSPACE_KEY || keyCode === DELETE_KEY) {
that.transact();
}
});
// Now this is very hacky:
// These days browsers don't offer a undo/redo event which we could hook into
// to be notified when the user hits undo/redo in the contextmenu.
// Therefore we simply insert two elements as soon as the contextmenu gets opened.
// The last element being inserted will be immediately be removed again by a exexCommand("undo")
// => When the second element appears in the dom tree then we know the user clicked "redo" in the context menu
// => When the first element disappears from the dom tree then we know the user clicked "undo" in the context menu
if (wysihtml5.browser.hasUndoInContextMenu()) {
var interval, observed, cleanUp = function() {
cleanTempElements(doc);
clearInterval(interval);
};
dom.observe(this.element, "contextmenu", function() {
cleanUp();
that.composer.selection.executeAndRestoreSimple(function() {
if (that.element.lastChild) {
that.composer.selection.setAfter(that.element.lastChild);
}
// enable undo button in context menu
doc.execCommand("insertHTML", false, UNDO_HTML);
// enable redo button in context menu
doc.execCommand("insertHTML", false, REDO_HTML);
doc.execCommand("undo", false, null);
});
interval = setInterval(function() {
if (doc.getElementById("_wysihtml5-redo")) {
cleanUp();
that.redo();
} else if (!doc.getElementById("_wysihtml5-undo")) {
cleanUp();
that.undo();
}
}, 400);
if (!observed) {
observed = true;
dom.observe(document, "mousedown", cleanUp);
dom.observe(doc, ["mousedown", "paste", "cut", "copy"], cleanUp);
}
});
}
this.editor
.observe("newword:composer", function() {
that.transact();
})
.observe("beforecommand:composer", function() {
that.transact();
});
},
transact: function() {
var previousHtml = this.history[this.position - 1],
currentHtml = this.composer.getValue();
if (currentHtml == previousHtml) {
return;
}
var length = this.history.length = this.position;
if (length > MAX_HISTORY_ENTRIES) {
this.history.shift();
this.position--;
}
this.position++;
this.history.push(currentHtml);
},
undo: function() {
this.transact();
if (this.position <= 1) {
return;
}
this.set(this.history[--this.position - 1]);
this.editor.fire("undo:composer");
},
redo: function() {
if (this.position >= this.history.length) {
return;
}
this.set(this.history[++this.position - 1]);
this.editor.fire("redo:composer");
},
set: function(html) {
this.composer.setValue(html);
this.editor.focus(true);
}
});
})(wysihtml5);
/**
* TODO: the following methods still need unit test coverage
*/
wysihtml5.views.View = Base.extend(
/** @scope wysihtml5.views.View.prototype */ {
constructor: function(parent, textareaElement, config) {
this.parent = parent;
this.element = textareaElement;
this.config = config;
this._observeViewChange();
},
_observeViewChange: function() {
var that = this;
this.parent.observe("beforeload", function() {
that.parent.observe("change_view", function(view) {
if (view === that.name) {
that.parent.currentView = that;
that.show();
// Using tiny delay here to make sure that the placeholder is set before focusing
setTimeout(function() { that.focus(); }, 0);
} else {
that.hide();
}
});
});
},
focus: function() {
if (this.element.ownerDocument.querySelector(":focus") === this.element) {
return;
}
try { this.element.focus(); } catch(e) {}
},
hide: function() {
this.element.style.display = "none";
},
show: function() {
this.element.style.display = "";
},
disable: function() {
this.element.setAttribute("disabled", "disabled");
},
enable: function() {
this.element.removeAttribute("disabled");
}
});(function(wysihtml5) {
var dom = wysihtml5.dom,
browser = wysihtml5.browser;
wysihtml5.views.Composer = wysihtml5.views.View.extend(
/** @scope wysihtml5.views.Composer.prototype */ {
name: "composer",
// Needed for firefox in order to display a proper caret in an empty contentEditable
CARET_HACK: "<br>",
constructor: function(parent, textareaElement, config) {
this.base(parent, textareaElement, config);
this.textarea = this.parent.textarea;
this._initSandbox();
},
clear: function() {
this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK;
},
getValue: function(parse) {
var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element);
if (parse) {
value = this.parent.parse(value);
}
// Replace all "zero width no breaking space" chars
// which are used as hacks to enable some functionalities
// Also remove all CARET hacks that somehow got left
value = wysihtml5.lang.string(value).replace(wysihtml5.INVISIBLE_SPACE).by("");
return value;
},
setValue: function(html, parse) {
if (parse) {
html = this.parent.parse(html);
}
this.element.innerHTML = html;
},
show: function() {
this.iframe.style.display = this._displayStyle || "";
// Firefox needs this, otherwise contentEditable becomes uneditable
this.disable();
this.enable();
},
hide: function() {
this._displayStyle = dom.getStyle("display").from(this.iframe);
if (this._displayStyle === "none") {
this._displayStyle = null;
}
this.iframe.style.display = "none";
},
disable: function() {
this.element.removeAttribute("contentEditable");
this.base();
},
enable: function() {
this.element.setAttribute("contentEditable", "true");
this.base();
},
focus: function(setToEnd) {
// IE 8 fires the focus event after .focus()
// This is needed by our simulate_placeholder.js to work
// therefore we clear it ourselves this time
if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) {
this.clear();
}
this.base();
var lastChild = this.element.lastChild;
if (setToEnd && lastChild) {
if (lastChild.nodeName === "BR") {
this.selection.setBefore(this.element.lastChild);
} else {
this.selection.setAfter(this.element.lastChild);
}
}
},
getTextContent: function() {
return dom.getTextContent(this.element);
},
hasPlaceholderSet: function() {
return this.getTextContent() == this.textarea.element.getAttribute("placeholder");
},
isEmpty: function() {
var innerHTML = this.element.innerHTML,
elementsWithVisualValue = "blockquote, ul, ol, img, embed, object, table, iframe, svg, video, audio, button, input, select, textarea";
return innerHTML === "" ||
innerHTML === this.CARET_HACK ||
this.hasPlaceholderSet() ||
(this.getTextContent() === "" && !this.element.querySelector(elementsWithVisualValue));
},
_initSandbox: function() {
var that = this;
this.sandbox = new dom.Sandbox(function() {
that._create();
}, {
stylesheets: this.config.stylesheets
});
this.iframe = this.sandbox.getIframe();
// Create hidden field which tells the server after submit, that the user used an wysiwyg editor
var hiddenField = document.createElement("input");
hiddenField.type = "hidden";
hiddenField.name = "_wysihtml5_mode";
hiddenField.value = 1;
// Store reference to current wysihtml5 instance on the textarea element
var textareaElement = this.textarea.element;
dom.insert(this.iframe).after(textareaElement);
dom.insert(hiddenField).after(textareaElement);
},
_create: function() {
var that = this;
this.doc = this.sandbox.getDocument();
this.element = this.doc.body;
this.textarea = this.parent.textarea;
this.element.innerHTML = this.textarea.getValue(true);
this.enable();
// Make sure our selection handler is ready
this.selection = new wysihtml5.Selection(this.parent);
// Make sure commands dispatcher is ready
this.commands = new wysihtml5.Commands(this.parent);
dom.copyAttributes([
"className", "spellcheck", "title", "lang", "dir", "accessKey"
]).from(this.textarea.element).to(this.element);
dom.addClass(this.element, this.config.composerClassName);
// Make the editor look like the original textarea, by syncing styles
if (this.config.style) {
this.style();
}
this.observe();
var name = this.config.name;
if (name) {
dom.addClass(this.element, name);
dom.addClass(this.iframe, name);
}
// Simulate html5 placeholder attribute on contentEditable element
var placeholderText = typeof(this.config.placeholder) === "string"
? this.config.placeholder
: this.textarea.element.getAttribute("placeholder");
if (placeholderText) {
dom.simulatePlaceholder(this.parent, this, placeholderText);
}
// Make sure that the browser avoids using inline styles whenever possible
this.commands.exec("styleWithCSS", false);
this._initAutoLinking();
this._initObjectResizing();
this._initUndoManager();
// Simulate html5 autofocus on contentEditable element
if (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) {
setTimeout(function() { that.focus(); }, 100);
}
wysihtml5.quirks.insertLineBreakOnReturn(this);
// IE sometimes leaves a single paragraph, which can't be removed by the user
if (!browser.clearsContentEditableCorrectly()) {
wysihtml5.quirks.ensureProperClearing(this);
}
if (!browser.clearsListsInContentEditableCorrectly()) {
wysihtml5.quirks.ensureProperClearingOfLists(this);
}
// Set up a sync that makes sure that textarea and editor have the same content
if (this.initSync && this.config.sync) {
this.initSync();
}
// Okay hide the textarea, we are ready to go
this.textarea.hide();
// Fire global (before-)load event
this.parent.fire("beforeload").fire("load");
},
_initAutoLinking: function() {
var that = this,
supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(),
supportsAutoLinking = browser.doesAutoLinkingInContentEditable();
if (supportsDisablingOfAutoLinking) {
this.commands.exec("autoUrlDetect", false);
}
if (!this.config.autoLink) {
return;
}
// Only do the auto linking by ourselves when the browser doesn't support auto linking
// OR when he supports auto linking but we were able to turn it off (IE9+)
if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) {
this.parent.observe("newword:composer", function() {
that.selection.executeAndRestore(function(startContainer, endContainer) {
dom.autoLink(endContainer.parentNode);
});
});
}
// Assuming we have the following:
// <a href="http://www.google.de">http://www.google.de</a>
// If a user now changes the url in the innerHTML we want to make sure that
// it's synchronized with the href attribute (as long as the innerHTML is still a url)
var // Use a live NodeList to check whether there are any links in the document
links = this.sandbox.getDocument().getElementsByTagName("a"),
// The autoLink helper method reveals a reg exp to detect correct urls
urlRegExp = dom.autoLink.URL_REG_EXP,
getTextContent = function(element) {
var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim();
if (textContent.substr(0, 4) === "www.") {
textContent = "http://" + textContent;
}
return textContent;
};
dom.observe(this.element, "keydown", function(event) {
if (!links.length) {
return;
}
var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument),
link = dom.getParentElement(selectedNode, { nodeName: "A" }, 4),
textContent;
if (!link) {
return;
}
textContent = getTextContent(link);
// keydown is fired before the actual content is changed
// therefore we set a timeout to change the href
setTimeout(function() {
var newTextContent = getTextContent(link);
if (newTextContent === textContent) {
return;
}
// Only set href when new href looks like a valid url
if (newTextContent.match(urlRegExp)) {
link.setAttribute("href", newTextContent);
}
}, 0);
});
},
_initObjectResizing: function() {
var properties = ["width", "height"],
propertiesLength = properties.length,
element = this.element;
this.commands.exec("enableObjectResizing", this.config.allowObjectResizing);
if (this.config.allowObjectResizing) {
// IE sets inline styles after resizing objects
// The following lines make sure that the width/height css properties
// are copied over to the width/height attributes
if (browser.supportsEvent("resizeend")) {
dom.observe(element, "resizeend", function(event) {
var target = event.target || event.srcElement,
style = target.style,
i = 0,
property;
for(; i<propertiesLength; i++) {
property = properties[i];
if (style[property]) {
target.setAttribute(property, parseInt(style[property], 10));
style[property] = "";
}
}
// After resizing IE sometimes forgets to remove the old resize handles
wysihtml5.quirks.redraw(element);
});
}
} else {
if (browser.supportsEvent("resizestart")) {
dom.observe(element, "resizestart", function(event) { event.preventDefault(); });
}
}
},
_initUndoManager: function() {
new wysihtml5.UndoManager(this.parent);
}
});
})(wysihtml5);(function(wysihtml5) {
var dom = wysihtml5.dom,
doc = document,
win = window,
HOST_TEMPLATE = doc.createElement("div"),
/**
* Styles to copy from textarea to the composer element
*/
TEXT_FORMATTING = [
"background-color",
"color", "cursor",
"font-family", "font-size", "font-style", "font-variant", "font-weight",
"line-height", "letter-spacing",
"text-align", "text-decoration", "text-indent", "text-rendering",
"word-break", "word-wrap", "word-spacing"
],
/**
* Styles to copy from textarea to the iframe
*/
BOX_FORMATTING = [
"background-color",
"border-collapse",
"border-bottom-color", "border-bottom-style", "border-bottom-width",
"border-left-color", "border-left-style", "border-left-width",
"border-right-color", "border-right-style", "border-right-width",
"border-top-color", "border-top-style", "border-top-width",
"clear", "display", "float",
"margin-bottom", "margin-left", "margin-right", "margin-top",
"outline-color", "outline-offset", "outline-width", "outline-style",
"padding-left", "padding-right", "padding-top", "padding-bottom",
"position", "top", "left", "right", "bottom", "z-index",
"vertical-align", "text-align",
"-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing",
"-webkit-box-shadow", "-moz-box-shadow", "-ms-box-shadow","box-shadow",
"-webkit-border-top-right-radius", "-moz-border-radius-topright", "border-top-right-radius",
"-webkit-border-bottom-right-radius", "-moz-border-radius-bottomright", "border-bottom-right-radius",
"-webkit-border-bottom-left-radius", "-moz-border-radius-bottomleft", "border-bottom-left-radius",
"-webkit-border-top-left-radius", "-moz-border-radius-topleft", "border-top-left-radius",
"width", "height"
],
/**
* Styles to sync while the window gets resized
*/
RESIZE_STYLE = [
"width", "height",
"top", "left", "right", "bottom"
],
ADDITIONAL_CSS_RULES = [
"html { height: 100%; }",
"body { min-height: 100%; padding: 0; margin: 0; margin-top: -1px; padding-top: 1px; }",
"._wysihtml5-temp { display: none; }",
wysihtml5.browser.isGecko ?
"body.placeholder { color: graytext !important; }" :
"body.placeholder { color: #a9a9a9 !important; }",
"body[disabled] { background-color: #eee !important; color: #999 !important; cursor: default !important; }",
// Ensure that user see's broken images and can delete them
"img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }"
];
/**
* With "setActive" IE offers a smart way of focusing elements without scrolling them into view:
* http://msdn.microsoft.com/en-us/library/ms536738(v=vs.85).aspx
*
* Other browsers need a more hacky way: (pssst don't tell my mama)
* In order to prevent the element being scrolled into view when focusing it, we simply
* move it out of the scrollable area, focus it, and reset it's position
*/
var focusWithoutScrolling = function(element) {
if (element.setActive) {
// Following line could cause a js error when the textarea is invisible
// See https://github.com/xing/wysihtml5/issues/9
try { element.setActive(); } catch(e) {}
} else {
var elementStyle = element.style,
originalScrollTop = doc.documentElement.scrollTop || doc.body.scrollTop,
originalScrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft,
originalStyles = {
position: elementStyle.position,
top: elementStyle.top,
left: elementStyle.left,
WebkitUserSelect: elementStyle.WebkitUserSelect
};
dom.setStyles({
position: "absolute",
top: "-99999px",
left: "-99999px",
// Don't ask why but temporarily setting -webkit-user-select to none makes the whole thing performing smoother
WebkitUserSelect: "none"
}).on(element);
element.focus();
dom.setStyles(originalStyles).on(element);
if (win.scrollTo) {
// Some browser extensions unset this method to prevent annoyances
// "Better PopUp Blocker" for Chrome http://code.google.com/p/betterpopupblocker/source/browse/trunk/blockStart.js#100
// Issue: http://code.google.com/p/betterpopupblocker/issues/detail?id=1
win.scrollTo(originalScrollLeft, originalScrollTop);
}
}
};
wysihtml5.views.Composer.prototype.style = function() {
var that = this,
originalActiveElement = doc.querySelector(":focus"),
textareaElement = this.textarea.element,
hasPlaceholder = textareaElement.hasAttribute("placeholder"),
originalPlaceholder = hasPlaceholder && textareaElement.getAttribute("placeholder");
this.focusStylesHost = this.focusStylesHost || HOST_TEMPLATE.cloneNode(false);
this.blurStylesHost = this.blurStylesHost || HOST_TEMPLATE.cloneNode(false);
// Remove placeholder before copying (as the placeholder has an affect on the computed style)
if (hasPlaceholder) {
textareaElement.removeAttribute("placeholder");
}
if (textareaElement === originalActiveElement) {
textareaElement.blur();
}
// --------- iframe styles (has to be set before editor styles, otherwise IE9 sets wrong fontFamily on blurStylesHost) ---------
dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.iframe).andTo(this.blurStylesHost);
// --------- editor styles ---------
dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.element).andTo(this.blurStylesHost);
// --------- apply standard rules ---------
dom.insertCSS(ADDITIONAL_CSS_RULES).into(this.element.ownerDocument);
// --------- :focus styles ---------
focusWithoutScrolling(textareaElement);
dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.focusStylesHost);
dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.focusStylesHost);
// Make sure that we don't change the display style of the iframe when copying styles oblur/onfocus
// this is needed for when the change_view event is fired where the iframe is hidden and then
// the blur event fires and re-displays it
var boxFormattingStyles = wysihtml5.lang.array(BOX_FORMATTING).without(["display"]);
// --------- restore focus ---------
if (originalActiveElement) {
originalActiveElement.focus();
} else {
textareaElement.blur();
}
// --------- restore placeholder ---------
if (hasPlaceholder) {
textareaElement.setAttribute("placeholder", originalPlaceholder);
}
// When copying styles, we only get the computed style which is never returned in percent unit
// Therefore we've to recalculate style onresize
if (!wysihtml5.browser.hasCurrentStyleProperty()) {
var winObserver = dom.observe(win, "resize", function() {
// Remove event listener if composer doesn't exist anymore
if (!dom.contains(document.documentElement, that.iframe)) {
winObserver.stop();
return;
}
var originalTextareaDisplayStyle = dom.getStyle("display").from(textareaElement),
originalComposerDisplayStyle = dom.getStyle("display").from(that.iframe);
textareaElement.style.display = "";
that.iframe.style.display = "none";
dom.copyStyles(RESIZE_STYLE)
.from(textareaElement)
.to(that.iframe)
.andTo(that.focusStylesHost)
.andTo(that.blurStylesHost);
that.iframe.style.display = originalComposerDisplayStyle;
textareaElement.style.display = originalTextareaDisplayStyle;
});
}
// --------- Sync focus/blur styles ---------
this.parent.observe("focus:composer", function() {
dom.copyStyles(boxFormattingStyles) .from(that.focusStylesHost).to(that.iframe);
dom.copyStyles(TEXT_FORMATTING) .from(that.focusStylesHost).to(that.element);
});
this.parent.observe("blur:composer", function() {
dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.iframe);
dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element);
});
return this;
};
})(wysihtml5);/**
* Taking care of events
* - Simulating 'change' event on contentEditable element
* - Handling drag & drop logic
* - Catch paste events
* - Dispatch proprietary newword:composer event
* - Keyboard shortcuts
*/
(function(wysihtml5) {
var dom = wysihtml5.dom,
browser = wysihtml5.browser,
/**
* Map keyCodes to query commands
*/
shortcuts = {
"66": "bold", // B
"73": "italic", // I
"85": "underline" // U
};
wysihtml5.views.Composer.prototype.observe = function() {
var that = this,
state = this.getValue(),
iframe = this.sandbox.getIframe(),
element = this.element,
focusBlurElement = browser.supportsEventsInIframeCorrectly() ? element : this.sandbox.getWindow(),
// Firefox < 3.5 doesn't support the drop event, instead it supports a so called "dragdrop" event which behaves almost the same
pasteEvents = browser.supportsEvent("drop") ? ["drop", "paste"] : ["dragdrop", "paste"];
// --------- destroy:composer event ---------
dom.observe(iframe, "DOMNodeRemoved", function() {
clearInterval(domNodeRemovedInterval);
that.parent.fire("destroy:composer");
});
// DOMNodeRemoved event is not supported in IE 8
var domNodeRemovedInterval = setInterval(function() {
if (!dom.contains(document.documentElement, iframe)) {
clearInterval(domNodeRemovedInterval);
that.parent.fire("destroy:composer");
}
}, 250);
// --------- Focus & blur logic ---------
dom.observe(focusBlurElement, "focus", function() {
that.parent.fire("focus").fire("focus:composer");
// Delay storing of state until all focus handler are fired
// especially the one which resets the placeholder
setTimeout(function() { state = that.getValue(); }, 0);
});
dom.observe(focusBlurElement, "blur", function() {
if (state !== that.getValue()) {
that.parent.fire("change").fire("change:composer");
}
that.parent.fire("blur").fire("blur:composer");
});
if (wysihtml5.browser.isIos()) {
// When on iPad/iPhone/IPod after clicking outside of editor, the editor loses focus
// but the UI still acts as if the editor has focus (blinking caret and onscreen keyboard visible)
// We prevent that by focusing a temporary input element which immediately loses focus
dom.observe(element, "blur", function() {
var input = element.ownerDocument.createElement("input"),
originalScrollTop = document.documentElement.scrollTop || document.body.scrollTop,
originalScrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
try {
that.selection.insertNode(input);
} catch(e) {
element.appendChild(input);
}
input.focus();
input.parentNode.removeChild(input);
window.scrollTo(originalScrollLeft, originalScrollTop);
});
}
// --------- Drag & Drop logic ---------
dom.observe(element, "dragenter", function() {
that.parent.fire("unset_placeholder");
});
if (browser.firesOnDropOnlyWhenOnDragOverIsCancelled()) {
dom.observe(element, ["dragover", "dragenter"], function(event) {
event.preventDefault();
});
}
dom.observe(element, pasteEvents, function(event) {
var dataTransfer = event.dataTransfer,
data;
console.log('PASTED', event);
if (dataTransfer && browser.supportsDataTransfer()) {
data = dataTransfer.getData("text/html") || dataTransfer.getData("text/plain");
}
if (data) {
element.focus();
that.commands.exec("insertHTML", data);
that.parent.fire("paste").fire("paste:composer");
event.stopPropagation();
event.preventDefault();
} else {
setTimeout(function() {
that.parent.fire("paste").fire("paste:composer");
}, 0);
}
});
// --------- neword event ---------
dom.observe(element, "keyup", function(event) {
var keyCode = event.keyCode;
if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) {
that.parent.fire("newword:composer");
}
});
this.parent.observe("paste:composer", function() {
setTimeout(function() { that.parent.fire("newword:composer"); }, 0);
});
// --------- Make sure that images are selected when clicking on them ---------
if (!browser.canSelectImagesInContentEditable()) {
dom.observe(element, "mousedown", function(event) {
var target = event.target;
if (target.nodeName === "IMG") {
that.selection.selectNode(target);
event.preventDefault();
}
});
}
// --------- Shortcut logic ---------
dom.observe(element, "keydown", function(event) {
var keyCode = event.keyCode,
command = shortcuts[keyCode];
if ((event.ctrlKey || event.metaKey) && !event.altKey && command) {
that.commands.exec(command);
event.preventDefault();
}
});
// --------- Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor ---------
dom.observe(element, "keydown", function(event) {
var target = that.selection.getSelectedNode(true),
keyCode = event.keyCode,
parent;
if (target && target.nodeName === "IMG" && (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY)) { // 8 => backspace, 46 => delete
parent = target.parentNode;
// delete the <img>
parent.removeChild(target);
// and it's parent <a> too if it hasn't got any other child nodes
if (parent.nodeName === "A" && !parent.firstChild) {
parent.parentNode.removeChild(parent);
}
setTimeout(function() { wysihtml5.quirks.redraw(element); }, 0);
event.preventDefault();
}
});
// --------- Show url in tooltip when hovering links or images ---------
var titlePrefixes = {
IMG: "Image: ",
A: "Link: "
};
dom.observe(element, "mouseover", function(event) {
var target = event.target,
nodeName = target.nodeName,
title;
if (nodeName !== "A" && nodeName !== "IMG") {
return;
}
var hasTitle = target.hasAttribute("title");
if(!hasTitle){
title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src"));
target.setAttribute("title", title);
}
});
};
})(wysihtml5);/**
* Class that takes care that the value of the composer and the textarea is always in sync
*/
(function(wysihtml5) {
var INTERVAL = 400;
wysihtml5.views.Synchronizer = Base.extend(
/** @scope wysihtml5.views.Synchronizer.prototype */ {
constructor: function(editor, textarea, composer) {
this.editor = editor;
this.textarea = textarea;
this.composer = composer;
this._observe();
},
/**
* Sync html from composer to textarea
* Takes care of placeholders
* @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea
*/
fromComposerToTextarea: function(shouldParseHtml) {
this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue()).trim(), shouldParseHtml);
},
/**
* Sync value of textarea to composer
* Takes care of placeholders
* @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer
*/
fromTextareaToComposer: function(shouldParseHtml) {
var textareaValue = this.textarea.getValue();
if (textareaValue) {
this.composer.setValue(textareaValue, shouldParseHtml);
} else {
this.composer.clear();
this.editor.fire("set_placeholder");
}
},
/**
* Invoke syncing based on view state
* @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer/textarea
*/
sync: function(shouldParseHtml) {
if (this.editor.currentView.name === "textarea") {
this.fromTextareaToComposer(shouldParseHtml);
} else {
this.fromComposerToTextarea(shouldParseHtml);
}
},
/**
* Initializes interval-based syncing
* also makes sure that on-submit the composer's content is synced with the textarea
* immediately when the form gets submitted
*/
_observe: function() {
var interval,
that = this,
form = this.textarea.element.form,
startInterval = function() {
interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL);
},
stopInterval = function() {
clearInterval(interval);
interval = null;
};
startInterval();
if (form) {
// If the textarea is in a form make sure that after onreset and onsubmit the composer
// has the correct state
wysihtml5.dom.observe(form, "submit", function() {
that.sync(true);
});
wysihtml5.dom.observe(form, "reset", function() {
setTimeout(function() { that.fromTextareaToComposer(); }, 0);
});
}
this.editor.observe("change_view", function(view) {
if (view === "composer" && !interval) {
that.fromTextareaToComposer(true);
startInterval();
} else if (view === "textarea") {
that.fromComposerToTextarea(true);
stopInterval();
}
});
this.editor.observe("destroy:composer", stopInterval);
}
});
})(wysihtml5);
wysihtml5.views.Textarea = wysihtml5.views.View.extend(
/** @scope wysihtml5.views.Textarea.prototype */ {
name: "textarea",
constructor: function(parent, textareaElement, config) {
this.base(parent, textareaElement, config);
this._observe();
},
clear: function() {
this.element.value = "";
},
getValue: function(parse) {
var value = this.isEmpty() ? "" : this.element.value;
if (parse) {
value = this.parent.parse(value);
}
return value;
},
setValue: function(html, parse) {
if (parse) {
html = this.parent.parse(html);
}
this.element.value = html;
},
hasPlaceholderSet: function() {
var supportsPlaceholder = wysihtml5.browser.supportsPlaceholderAttributeOn(this.element),
placeholderText = this.element.getAttribute("placeholder") || null,
value = this.element.value,
isEmpty = !value;
return (supportsPlaceholder && isEmpty) || (value === placeholderText);
},
isEmpty: function() {
return !wysihtml5.lang.string(this.element.value).trim() || this.hasPlaceholderSet();
},
_observe: function() {
var element = this.element,
parent = this.parent,
eventMapping = {
focusin: "focus",
focusout: "blur"
},
/**
* Calling focus() or blur() on an element doesn't synchronously trigger the attached focus/blur events
* This is the case for focusin and focusout, so let's use them whenever possible, kkthxbai
*/
events = wysihtml5.browser.supportsEvent("focusin") ? ["focusin", "focusout", "change"] : ["focus", "blur", "change"];
parent.observe("beforeload", function() {
wysihtml5.dom.observe(element, events, function(event) {
var eventName = eventMapping[event.type] || event.type;
parent.fire(eventName).fire(eventName + ":textarea");
});
wysihtml5.dom.observe(element, ["paste", "drop"], function() {
setTimeout(function() { parent.fire("paste").fire("paste:textarea"); }, 0);
});
});
}
});/**
* Toolbar Dialog
*
* @param {Element} link The toolbar link which causes the dialog to show up
* @param {Element} container The dialog container
*
* @example
* <!-- Toolbar link -->
* <a data-wysihtml5-command="insertImage">insert an image</a>
*
* <!-- Dialog -->
* <div data-wysihtml5-dialog="insertImage" style="display: none;">
* <label>
* URL: <input data-wysihtml5-dialog-field="src" value="http://">
* </label>
* <label>
* Alternative text: <input data-wysihtml5-dialog-field="alt" value="">
* </label>
* </div>
*
* <script>
* var dialog = new wysihtml5.toolbar.Dialog(
* document.querySelector("[data-wysihtml5-command='insertImage']"),
* document.querySelector("[data-wysihtml5-dialog='insertImage']")
* );
* dialog.observe("save", function(attributes) {
* // do something
* });
* </script>
*/
(function(wysihtml5) {
var dom = wysihtml5.dom,
CLASS_NAME_OPENED = "wysihtml5-command-dialog-opened",
SELECTOR_FORM_ELEMENTS = "input, select, textarea",
SELECTOR_FIELDS = "[data-wysihtml5-dialog-field]",
ATTRIBUTE_FIELDS = "data-wysihtml5-dialog-field";
wysihtml5.toolbar.Dialog = wysihtml5.lang.Dispatcher.extend(
/** @scope wysihtml5.toolbar.Dialog.prototype */ {
constructor: function(link, container) {
this.link = link;
this.container = container;
},
_observe: function() {
if (this._observed) {
return;
}
var that = this,
callbackWrapper = function(event) {
var attributes = that._serialize();
if (attributes == that.elementToChange) {
that.fire("edit", attributes);
} else {
that.fire("save", attributes);
}
that.hide();
event.preventDefault();
event.stopPropagation();
};
dom.observe(that.link, "click", function(event) {
if (dom.hasClass(that.link, CLASS_NAME_OPENED)) {
setTimeout(function() { that.hide(); }, 0);
}
});
dom.observe(this.container, "keydown", function(event) {
var keyCode = event.keyCode;
if (keyCode === wysihtml5.ENTER_KEY) {
callbackWrapper(event);
}
if (keyCode === wysihtml5.ESCAPE_KEY) {
that.hide();
}
});
dom.delegate(this.container, "[data-wysihtml5-dialog-action=save]", "click", callbackWrapper);
dom.delegate(this.container, "[data-wysihtml5-dialog-action=cancel]", "click", function(event) {
that.fire("cancel");
that.hide();
event.preventDefault();
event.stopPropagation();
});
var formElements = this.container.querySelectorAll(SELECTOR_FORM_ELEMENTS),
i = 0,
length = formElements.length,
_clearInterval = function() { clearInterval(that.interval); };
for (; i<length; i++) {
dom.observe(formElements[i], "change", _clearInterval);
}
this._observed = true;
},
/**
* Grabs all fields in the dialog and puts them in key=>value style in an object which
* then gets returned
*/
_serialize: function() {
var data = this.elementToChange || {},
fields = this.container.querySelectorAll(SELECTOR_FIELDS),
length = fields.length,
i = 0;
for (; i<length; i++) {
data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value;
}
return data;
},
/**
* Takes the attributes of the "elementToChange"
* and inserts them in their corresponding dialog input fields
*
* Assume the "elementToChange" looks like this:
* <a href="http://www.google.com" target="_blank">foo</a>
*
* and we have the following dialog:
* <input type="text" data-wysihtml5-dialog-field="href" value="">
* <input type="text" data-wysihtml5-dialog-field="target" value="">
*
* after calling _interpolate() the dialog will look like this
* <input type="text" data-wysihtml5-dialog-field="href" value="http://www.google.com">
* <input type="text" data-wysihtml5-dialog-field="target" value="_blank">
*
* Basically it adopted the attribute values into the corresponding input fields
*
*/
_interpolate: function(avoidHiddenFields) {
var field,
fieldName,
newValue,
focusedElement = document.querySelector(":focus"),
fields = this.container.querySelectorAll(SELECTOR_FIELDS),
length = fields.length,
i = 0;
for (; i<length; i++) {
field = fields[i];
// Never change elements where the user is currently typing in
if (field === focusedElement) {
continue;
}
// Don't update hidden fields
// See https://github.com/xing/wysihtml5/pull/14
if (avoidHiddenFields && field.type === "hidden") {
continue;
}
fieldName = field.getAttribute(ATTRIBUTE_FIELDS);
newValue = this.elementToChange ? (this.elementToChange[fieldName] || "") : field.defaultValue;
field.value = newValue;
}
},
/**
* Show the dialog element
*/
show: function(elementToChange) {
var that = this,
firstField = this.container.querySelector(SELECTOR_FORM_ELEMENTS);
this.elementToChange = elementToChange;
this._observe();
this._interpolate();
if (elementToChange) {
this.interval = setInterval(function() { that._interpolate(true); }, 500);
}
dom.addClass(this.link, CLASS_NAME_OPENED);
this.container.style.display = "";
this.fire("show");
if (firstField && !elementToChange) {
try {
firstField.focus();
} catch(e) {}
}
},
/**
* Hide the dialog element
*/
hide: function() {
clearInterval(this.interval);
this.elementToChange = null;
dom.removeClass(this.link, CLASS_NAME_OPENED);
this.container.style.display = "none";
this.fire("hide");
}
});
})(wysihtml5);
/**
* Converts speech-to-text and inserts this into the editor
* As of now (2011/03/25) this only is supported in Chrome >= 11
*
* Note that it sends the recorded audio to the google speech recognition api:
* http://stackoverflow.com/questions/4361826/does-chrome-have-buil-in-speech-recognition-for-input-type-text-x-webkit-speec
*
* Current HTML5 draft can be found here
* http://lists.w3.org/Archives/Public/public-xg-htmlspeech/2011Feb/att-0020/api-draft.html
*
* "Accessing Google Speech API Chrome 11"
* http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/
*/
(function(wysihtml5) {
var dom = wysihtml5.dom;
var linkStyles = {
position: "relative"
};
var wrapperStyles = {
left: 0,
margin: 0,
opacity: 0,
overflow: "hidden",
padding: 0,
position: "absolute",
top: 0,
zIndex: 1
};
var inputStyles = {
cursor: "inherit",
fontSize: "50px",
height: "50px",
marginTop: "-25px",
outline: 0,
padding: 0,
position: "absolute",
right: "-4px",
top: "50%"
};
var inputAttributes = {
"x-webkit-speech": "",
"speech": ""
};
wysihtml5.toolbar.Speech = function(parent, link) {
var input = document.createElement("input");
if (!wysihtml5.browser.supportsSpeechApiOn(input)) {
link.style.display = "none";
return;
}
var wrapper = document.createElement("div");
wysihtml5.lang.object(wrapperStyles).merge({
width: link.offsetWidth + "px",
height: link.offsetHeight + "px"
});
dom.insert(input).into(wrapper);
dom.insert(wrapper).into(link);
dom.setStyles(inputStyles).on(input);
dom.setAttributes(inputAttributes).on(input)
dom.setStyles(wrapperStyles).on(wrapper);
dom.setStyles(linkStyles).on(link);
var eventName = "onwebkitspeechchange" in input ? "webkitspeechchange" : "speechchange";
dom.observe(input, eventName, function() {
parent.execCommand("insertText", input.value);
input.value = "";
});
dom.observe(input, "click", function(event) {
if (dom.hasClass(link, "wysihtml5-command-disabled")) {
event.preventDefault();
}
event.stopPropagation();
});
};
})(wysihtml5);/**
* Toolbar
*
* @param {Object} parent Reference to instance of Editor instance
* @param {Element} container Reference to the toolbar container element
*
* @example
* <div id="toolbar">
* <a data-wysihtml5-command="createLink">insert link</a>
* <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1">insert h1</a>
* </div>
*
* <script>
* var toolbar = new wysihtml5.toolbar.Toolbar(editor, document.getElementById("toolbar"));
* </script>
*/
(function(wysihtml5) {
var CLASS_NAME_COMMAND_DISABLED = "wysihtml5-command-disabled",
CLASS_NAME_COMMANDS_DISABLED = "wysihtml5-commands-disabled",
CLASS_NAME_COMMAND_ACTIVE = "wysihtml5-command-active",
CLASS_NAME_ACTION_ACTIVE = "wysihtml5-action-active",
dom = wysihtml5.dom;
wysihtml5.toolbar.Toolbar = Base.extend(
/** @scope wysihtml5.toolbar.Toolbar.prototype */ {
constructor: function(editor, container) {
this.editor = editor;
this.container = typeof(container) === "string" ? document.getElementById(container) : container;
this.composer = editor.composer;
this._getLinks("command");
this._getLinks("action");
this._observe();
this.show();
var speechInputLinks = this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"),
length = speechInputLinks.length,
i = 0;
for (; i<length; i++) {
new wysihtml5.toolbar.Speech(this, speechInputLinks[i]);
}
},
_getLinks: function(type) {
var links = this[type + "Links"] = wysihtml5.lang.array(this.container.querySelectorAll("[data-wysihtml5-" + type + "]")).get(),
length = links.length,
i = 0,
mapping = this[type + "Mapping"] = {},
link,
group,
name,
value,
dialog;
for (; i<length; i++) {
link = links[i];
name = link.getAttribute("data-wysihtml5-" + type);
value = link.getAttribute("data-wysihtml5-" + type + "-value");
group = this.container.querySelector("[data-wysihtml5-" + type + "-group='" + name + "']");
dialog = this._getDialog(link, name);
mapping[name + ":" + value] = {
link: link,
group: group,
name: name,
value: value,
dialog: dialog,
state: false
};
}
},
_getDialog: function(link, command) {
var that = this,
dialogElement = this.container.querySelector("[data-wysihtml5-dialog='" + command + "']"),
dialog,
caretBookmark;
if (dialogElement) {
dialog = new wysihtml5.toolbar.Dialog(link, dialogElement);
dialog.observe("show", function() {
caretBookmark = that.composer.selection.getBookmark();
that.editor.fire("show:dialog", { command: command, dialogContainer: dialogElement, commandLink: link });
});
dialog.observe("save", function(attributes) {
if (caretBookmark) {
that.composer.selection.setBookmark(caretBookmark);
}
that._execCommand(command, attributes);
that.editor.fire("save:dialog", { command: command, dialogContainer: dialogElement, commandLink: link });
});
dialog.observe("cancel", function() {
that.editor.focus(false);
that.editor.fire("cancel:dialog", { command: command, dialogContainer: dialogElement, commandLink: link });
});
}
return dialog;
},
/**
* @example
* var toolbar = new wysihtml5.Toolbar();
* // Insert a <blockquote> element or wrap current selection in <blockquote>
* toolbar.execCommand("formatBlock", "blockquote");
*/
execCommand: function(command, commandValue) {
if (this.commandsDisabled) {
return;
}
var commandObj = this.commandMapping[command + ":" + commandValue];
// Show dialog when available
if (commandObj && commandObj.dialog && !commandObj.state) {
commandObj.dialog.show();
} else {
this._execCommand(command, commandValue);
}
},
_execCommand: function(command, commandValue) {
// Make sure that composer is focussed (false => don't move caret to the end)
this.editor.focus(false);
this.composer.commands.exec(command, commandValue);
this._updateLinkStates();
},
execAction: function(action) {
var editor = this.editor;
switch(action) {
case "change_view":
if (editor.currentView === editor.textarea) {
editor.fire("change_view", "composer");
} else {
editor.fire("change_view", "textarea");
}
break;
}
},
_observe: function() {
var that = this,
editor = this.editor,
container = this.container,
links = this.commandLinks.concat(this.actionLinks),
length = links.length,
i = 0;
for (; i<length; i++) {
// 'javascript:;' and unselectable=on Needed for IE, but done in all browsers to make sure that all get the same css applied
// (you know, a:link { ... } doesn't match anchors with missing href attribute)
dom.setAttributes({
href: "javascript:;",
unselectable: "on"
}).on(links[i]);
}
// Needed for opera
dom.delegate(container, "[data-wysihtml5-command]", "mousedown", function(event) { event.preventDefault(); });
dom.delegate(container, "[data-wysihtml5-command]", "click", function(event) {
var link = this,
command = link.getAttribute("data-wysihtml5-command"),
commandValue = link.getAttribute("data-wysihtml5-command-value");
that.execCommand(command, commandValue);
event.preventDefault();
});
dom.delegate(container, "[data-wysihtml5-action]", "click", function(event) {
var action = this.getAttribute("data-wysihtml5-action");
that.execAction(action);
event.preventDefault();
});
editor.observe("focus:composer", function() {
that.bookmark = null;
clearInterval(that.interval);
that.interval = setInterval(function() { that._updateLinkStates(); }, 500);
});
editor.observe("blur:composer", function() {
clearInterval(that.interval);
});
editor.observe("destroy:composer", function() {
clearInterval(that.interval);
});
editor.observe("change_view", function(currentView) {
// Set timeout needed in order to let the blur event fire first
setTimeout(function() {
that.commandsDisabled = (currentView !== "composer");
that._updateLinkStates();
if (that.commandsDisabled) {
dom.addClass(container, CLASS_NAME_COMMANDS_DISABLED);
} else {
dom.removeClass(container, CLASS_NAME_COMMANDS_DISABLED);
}
}, 0);
});
},
_updateLinkStates: function() {
var element = this.composer.element,
commandMapping = this.commandMapping,
actionMapping = this.actionMapping,
i,
state,
action,
command;
// every millisecond counts... this is executed quite often
for (i in commandMapping) {
command = commandMapping[i];
if (this.commandsDisabled) {
state = false;
dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE);
if (command.group) {
dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE);
}
if (command.dialog) {
command.dialog.hide();
}
} else {
state = this.composer.commands.state(command.name, command.value);
if (wysihtml5.lang.object(state).isArray()) {
// Grab first and only object/element in state array, otherwise convert state into boolean
// to avoid showing a dialog for multiple selected elements which may have different attributes
// eg. when two links with different href are selected, the state will be an array consisting of both link elements
// but the dialog interface can only update one
state = state.length === 1 ? state[0] : true;
}
dom.removeClass(command.link, CLASS_NAME_COMMAND_DISABLED);
if (command.group) {
dom.removeClass(command.group, CLASS_NAME_COMMAND_DISABLED);
}
}
if (command.state === state) {
continue;
}
command.state = state;
if (state) {
dom.addClass(command.link, CLASS_NAME_COMMAND_ACTIVE);
if (command.group) {
dom.addClass(command.group, CLASS_NAME_COMMAND_ACTIVE);
}
if (command.dialog) {
if (typeof(state) === "object") {
command.dialog.show(state);
} else {
command.dialog.hide();
}
}
} else {
dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE);
if (command.group) {
dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE);
}
if (command.dialog) {
command.dialog.hide();
}
}
}
for (i in actionMapping) {
action = actionMapping[i];
if (action.name === "change_view") {
action.state = this.editor.currentView === this.editor.textarea;
if (action.state) {
dom.addClass(action.link, CLASS_NAME_ACTION_ACTIVE);
} else {
dom.removeClass(action.link, CLASS_NAME_ACTION_ACTIVE);
}
}
}
},
show: function() {
this.container.style.display = "";
},
hide: function() {
this.container.style.display = "none";
}
});
})(wysihtml5);
/**
* WYSIHTML5 Editor
*
* @param {Element} textareaElement Reference to the textarea which should be turned into a rich text interface
* @param {Object} [config] See defaultConfig object below for explanation of each individual config option
*
* @events
* load
* beforeload (for internal use only)
* focus
* focus:composer
* focus:textarea
* blur
* blur:composer
* blur:textarea
* change
* change:composer
* change:textarea
* paste
* paste:composer
* paste:textarea
* newword:composer
* destroy:composer
* undo:composer
* redo:composer
* beforecommand:composer
* aftercommand:composer
* change_view
*/
(function(wysihtml5) {
var undef;
var defaultConfig = {
// Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body
name: undef,
// Whether the editor should look like the textarea (by adopting styles)
style: true,
// Id of the toolbar element, pass falsey value if you don't want any toolbar logic
toolbar: undef,
// Whether urls, entered by the user should automatically become clickable-links
autoLink: true,
// Object which includes parser rules to apply when html gets inserted via copy & paste
// See parser_rules/*.js for examples
parserRules: { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} },
// Parser method to use when the user inserts content via copy & paste
parser: wysihtml5.dom.parse,
// Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option
composerClassName: "wysihtml5-editor",
// Class name to add to the body when the wysihtml5 editor is supported
bodyClassName: "wysihtml5-supported",
// Array (or single string) of stylesheet urls to be loaded in the editor's iframe
stylesheets: [],
// Placeholder text to use, defaults to the placeholder attribute on the textarea element
placeholderText: undef,
// Whether the composer should allow the user to manually resize images, tables etc.
allowObjectResizing: true,
// Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5)
supportTouchDevices: true
};
wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend(
/** @scope wysihtml5.Editor.prototype */ {
constructor: function(textareaElement, config) {
this.textareaElement = typeof(textareaElement) === "string" ? document.getElementById(textareaElement) : textareaElement;
this.config = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get();
this.textarea = new wysihtml5.views.Textarea(this, this.textareaElement, this.config);
this.currentView = this.textarea;
this._isCompatible = wysihtml5.browser.supported();
// Sort out unsupported/unwanted browsers here
if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) {
var that = this;
setTimeout(function() { that.fire("beforeload").fire("load"); }, 0);
return;
}
// Add class name to body, to indicate that the editor is supported
wysihtml5.dom.addClass(document.body, this.config.bodyClassName);
this.composer = new wysihtml5.views.Composer(this, this.textareaElement, this.config);
this.currentView = this.composer;
if (typeof(this.config.parser) === "function") {
this._initParser();
}
this.observe("beforeload", function() {
this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer);
if (this.config.toolbar) {
this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar);
}
});
try {
console.log("Heya! This page is using wysihtml5 for rich text editing. Check out https://github.com/xing/wysihtml5");
} catch(e) {}
},
isCompatible: function() {
return this._isCompatible;
},
clear: function() {
this.currentView.clear();
return this;
},
getValue: function(parse) {
return this.currentView.getValue(parse);
},
setValue: function(html, parse) {
if (!html) {
return this.clear();
}
this.currentView.setValue(html, parse);
return this;
},
focus: function(setToEnd) {
this.currentView.focus(setToEnd);
return this;
},
/**
* Deactivate editor (make it readonly)
*/
disable: function() {
this.currentView.disable();
return this;
},
/**
* Activate editor
*/
enable: function() {
this.currentView.enable();
return this;
},
isEmpty: function() {
return this.currentView.isEmpty();
},
hasPlaceholderSet: function() {
return this.currentView.hasPlaceholderSet();
},
parse: function(htmlOrElement) {
var returnValue = this.config.parser(htmlOrElement, this.config.parserRules, this.composer.sandbox.getDocument(), true);
if (typeof(htmlOrElement) === "object") {
wysihtml5.quirks.redraw(htmlOrElement);
}
return returnValue;
},
/**
* Prepare html parser logic
* - Observes for paste and drop
*/
_initParser: function() {
this.observe("paste:composer", function() {
var keepScrollPosition = true,
that = this;
that.composer.selection.executeAndRestore(function() {
wysihtml5.quirks.cleanPastedHTML(that.composer.element);
that.parse(that.composer.element);
}, keepScrollPosition);
});
this.observe("paste:textarea", function() {
var value = this.textarea.getValue(),
newValue;
newValue = this.parse(value);
this.textarea.setValue(newValue);
});
}
});
})(wysihtml5);
| JavaScript |
!function ($) {
"use strict";
// version: 2.8
// by Mattia Larentis - follow me on twitter! @SpiritualGuru
var addToAttribute = function (obj, array, value) {
var i = 0
, length = array.length;
for (; i < length; i++) {
obj = obj[array[i]] = obj[array[i]] || i == ( length - 1) ? value : {}
}
};
$.fn.toggleButtons = function (method) {
var $element
, $div
, transitionSpeed = 0.05
, methods = {
init: function (opt) {
this.each(function () {
var $spanLeft
, $spanRight
, options
, moving
, dataAttribute = {};
$element = $(this);
$element.addClass('toggle-button');
$.each($element.data(), function (i, el) {
var key
, tmp = {};
if (i.indexOf("togglebutton") === 0) {
key = i.match(/[A-Z][a-z]+/g);
key = $.map(key, function (n) {
return (n.toLowerCase());
});
addToAttribute(tmp, key, el);
dataAttribute = $.extend(true, dataAttribute, tmp);
}
});
options = $.extend(true, {}, $.fn.toggleButtons.defaults, opt, dataAttribute);
$(this).data('options', options);
$spanLeft = $('<span></span>').addClass("labelLeft").text(options.label.enabled === undefined ? "ON" : options.label.enabled);
$spanRight = $('<span></span>').addClass("labelRight").text(options.label.disabled === undefined ? "OFF " : options.label.disabled);
// html layout
$div = $element.find('input:checkbox').wrap($('<div></div>')).parent();
$div.append($spanLeft);
$div.append($('<label></label>').attr('for', $element.find('input').attr('id')));
$div.append($spanRight);
if ($element.find('input').is(':checked'))
$element.find('>div').css('left', "0");
else $element.find('>div').css('left', "-50%");
if (options.animated) {
if (options.transitionspeed !== undefined)
if (/^(\d*%$)/.test(options.transitionspeed)) // is a percent value?
transitionSpeed = 0.05 * parseInt(options.transitionspeed) / 100;
else
transitionSpeed = options.transitionspeed;
}
else transitionSpeed = 0;
$(this).data('transitionSpeed', transitionSpeed * 1000);
options["width"] /= 2;
// width of the bootstrap-toggle-button
$element
.css('width', options.width * 2)
.find('>div').css('width', options.width * 3)
.find('>span, >label').css('width', options.width);
// height of the bootstrap-toggle-button
$element
.css('height', options.height)
.find('span, label')
.css('height', options.height)
.filter('span')
.css('line-height', options.height + "px");
if ($element.find('input').is(':disabled'))
$(this).addClass('deactivate');
$element.find('span').css(options.font);
// enabled custom color
if (options.style.enabled === undefined) {
if (options.style.custom !== undefined && options.style.custom.enabled !== undefined && options.style.custom.enabled.background !== undefined) {
$spanLeft.css('color', options.style.custom.enabled.color);
if (options.style.custom.enabled.gradient === undefined)
$spanLeft.css('background', options.style.custom.enabled.background);
else $.each(["-webkit-", "-moz-", "-o-", ""], function (i, el) {
$spanLeft.css('background-image', el + 'linear-gradient(top, ' + options.style.custom.enabled.background + ',' + options.style.custom.enabled.gradient + ')');
});
}
}
else $spanLeft.addClass(options.style.enabled);
// disabled custom color
if (options.style.disabled === undefined) {
if (options.style.custom !== undefined && options.style.custom.disabled !== undefined && options.style.custom.disabled.background !== undefined) {
$spanRight.css('color', options.style.custom.disabled.color);
if (options.style.custom.disabled.gradient === undefined)
$spanRight.css('background', options.style.custom.disabled.background);
else $.each(["-webkit-", "-moz-", "-o-", ""], function (i, el) {
$spanRight.css('background-image', el + 'linear-gradient(top, ' + options.style.custom.disabled.background + ',' + options.style.custom.disabled.gradient + ')');
});
}
}
else $spanRight.addClass(options.style.disabled);
var changeStatus = function ($this) {
$this.siblings('label')
.trigger('mousedown')
.trigger('mouseup')
.trigger('click');
};
$spanLeft.on('click', function (e) {
changeStatus($(this));
});
$spanRight.on('click', function (e) {
changeStatus($(this));
});
$element.find('input').on('change', function (e, skipOnChange) {
var $element = $(this).parent()
, active = $(this).is(':checked')
, $toggleButton = $(this).closest('.toggle-button');
$element.stop().animate({'left': active ? '0' : '-50%'}, $toggleButton.data('transitionSpeed'));
options = $toggleButton.data('options');
if (!skipOnChange)
options.onChange($element, active, e);
});
$element.find('label').on('mousedown touchstart', function (e) {
moving = false;
e.preventDefault();
e.stopImmediatePropagation();
if ($(this).closest('.toggle-button').is('.deactivate'))
$(this).off('click');
else {
$(this).on('mousemove touchmove', function (e) {
var $element = $(this).closest('.toggle-button')
, relativeX = (e.pageX || e.originalEvent.targetTouches[0].pageX) - $element.offset().left
, percent = ((relativeX / (options.width * 2)) * 100);
moving = true;
e.stopImmediatePropagation();
e.preventDefault();
if (percent < 25)
percent = 25;
else if (percent > 75)
percent = 75;
$element.find('>div').css('left', (percent - 75) + "%");
});
$(this).on('click touchend', function (e) {
var $target = $(e.target)
, $myCheckBox = $target.siblings('input');
e.stopImmediatePropagation();
e.preventDefault();
$(this).off('mouseleave');
if (moving)
if (parseInt($(this).parent().css('left')) < -25)
$myCheckBox.attr('checked', false);
else $myCheckBox.attr('checked', true);
else $myCheckBox.attr("checked", !$myCheckBox.is(":checked"));
$myCheckBox.trigger('change');
});
$(this).on('mouseleave', function (e) {
var $myCheckBox = $(this).siblings('input');
e.preventDefault();
e.stopImmediatePropagation();
$(this).off('mouseleave');
$(this).trigger('mouseup');
if (parseInt($(this).parent().css('left')) < -25)
$myCheckBox.attr('checked', false);
else $myCheckBox.attr('checked', true);
$myCheckBox.trigger('change');
});
$(this).on('mouseup', function (e) {
e.stopImmediatePropagation();
e.preventDefault();
$(this).off('mousemove');
});
}
});
}
);
return this;
},
toggleActivation: function () {
$(this).toggleClass('deactivate');
},
toggleState: function (skipOnChange) {
var $input = $(this).find('input');
$input.attr('checked', !$input.is(':checked')).trigger('change', skipOnChange);
},
setState: function(value, skipOnChange) {
$(this).find('input').attr('checked', value).trigger('change', skipOnChange);
},
status: function () {
return $(this).find('input:checkbox').is(':checked');
},
destroy: function () {
var $div = $(this).find('div')
, $checkbox;
$div.find(':not(input:checkbox)').remove();
$checkbox = $div.children();
$checkbox.unwrap().unwrap();
$checkbox.unbind('change');
return $checkbox;
}
};
if (methods[method])
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
else if (typeof method === 'object' || !method)
return methods.init.apply(this, arguments);
else
$.error('Method ' + method + ' does not exist!');
};
$.fn.toggleButtons.defaults = {
onChange: function () {
},
width: 100,
height: 25,
font: {},
animated: true,
transitionspeed: undefined,
label: {
enabled: undefined,
disabled: undefined
},
style: {
enabled: undefined,
disabled: undefined,
custom: {
enabled: {
background: undefined,
gradient: undefined,
color: "#FFFFFF"
},
disabled: {
background: undefined,
gradient: undefined,
color: "#FFFFFF"
}
}
}
};
}($);
| JavaScript |
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
"iTotalPages": Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
};
}
/* Bootstrap style pagination control */
$.extend( $.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function( oSettings, nPaging, fnDraw ) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function ( e ) {
e.preventDefault();
if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
fnDraw( oSettings );
}
};
$(nPaging).append(
'<ul class="fancy pagination">'+
'<li class="prev disabled"><a href="#">← '+oLang.sPrevious+'</a></li>'+
'<li class="next disabled"><a href="#">'+oLang.sNext+' → </a></li>'+
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
$(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
},
"fnUpdate": function ( oSettings, fnDraw ) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);
if ( oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
}
else if ( oPaging.iPage <= iHalf ) {
iStart = 1;
iEnd = iListLength;
} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for ( i=0, iLen=an.length ; i<iLen ; i++ ) {
// Remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// Add the new list items and their event handlers
for ( j=iStart ; j<=iEnd ; j++ ) {
sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
$('<li '+sClass+'><a href="#">'+j+'</a></li>')
.insertBefore( $('li:last', an[i])[0] )
.bind('click', function (e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
fnDraw( oSettings );
} );
}
// Add / remove disabled classes from the static elements
if ( oPaging.iPage === 0 ) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
} );
| JavaScript |
$(function(){
$("a[href*='#']").click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 500);
return false;
});
});
| JavaScript |
/*! Javascript plotting library for jQuery, v. 0.7.
*
* Released under the MIT license by IOLA, December 2007.
*
*/
// first an inline dependency, jquery.colorhelpers.js, we inline it here
// for convenience
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
// the actual Flot code
(function($) {
function Plot(placeholder, data_, options_, plugins) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
var series = [],
options = {
// the color theme used for graphs
colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#ccc", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: 5, // distance from grid edge to default legend container within plot
backgroundColor: null, // null means auto-detect
backgroundOpacity: 0.85 // set to 0 to avoid background
},
xaxis: {
show: null, // null = auto-detect, true = always, false = never
position: "bottom", // or "top"
mode: null, // null or "time"
color: null, // base color, labels, ticks
tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
transform: null, // null or f: number -> number to transform axis
inverseTransform: null, // if transform is set, this should be the inverse function
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
reserveSpace: null, // whether to reserve space even if axis isn't shown
tickLength: null, // size in pixels of ticks, or "full" for whole line
alignTicksWithAxis: null, // axis number or null for no sync
// mode specific options
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null, // number or [number, "unit"]
monthNames: null, // list of names of months
timeformat: null, // format string to use
twelveHourClock: false // 12 or 24 time in time mode
},
yaxis: {
autoscaleMargin: 0.02,
position: "left" // or "right"
},
xaxes: [],
yaxes: [],
series: {
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff",
symbol: "circle" // or callback
},
lines: {
// we don't put in show: false so we can see
// whether lines were actively disabled
lineWidth: 2, // in pixels
fill: false,
fillColor: null,
steps: false
},
bars: {
show: false,
lineWidth: 2, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: null,
align: "left", // or "center"
horizontal: false
},
shadowSize: 3
},
grid: {
show: true,
aboveData: false,
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
borderColor: null, // set if different from the grid color
tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
labelMargin: 5, // in pixels
axisMargin: 8, // in pixels
borderWidth: 2, // in pixels
minBorderMargin: null, // in pixels, null means taken from points radius
markings: null, // array of ranges or fn: axes -> array of ranges
markingsColor: "#f4f4f4",
markingsLineWidth: 2,
// interactive stuff
clickable: false,
hoverable: false,
autoHighlight: true, // highlight in case mouse is near
mouseActiveRadius: 10 // how far the mouse can be away to activate an item
},
hooks: {}
},
canvas = null, // the canvas for the plot itself
overlay = null, // canvas for interactive stuff on top of plot
eventHolder = null, // jQuery object that events should be bound to
ctx = null, octx = null,
xaxes = [], yaxes = [],
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
canvasWidth = 0, canvasHeight = 0,
plotWidth = 0, plotHeight = 0,
hooks = {
processOptions: [],
processRawData: [],
processDatapoints: [],
drawSeries: [],
draw: [],
bindEvents: [],
drawOverlay: [],
shutdown: []
},
plot = this;
// public functions
plot.setData = setData;
plot.setupGrid = setupGrid;
plot.draw = draw;
plot.getPlaceholder = function() { return placeholder; };
plot.getCanvas = function() { return canvas; };
plot.getPlotOffset = function() { return plotOffset; };
plot.width = function () { return plotWidth; };
plot.height = function () { return plotHeight; };
plot.offset = function () {
var o = eventHolder.offset();
o.left += plotOffset.left;
o.top += plotOffset.top;
return o;
};
plot.getData = function () { return series; };
plot.getAxes = function () {
var res = {}, i;
$.each(xaxes.concat(yaxes), function (_, axis) {
if (axis)
res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
});
return res;
};
plot.getXAxes = function () { return xaxes; };
plot.getYAxes = function () { return yaxes; };
plot.c2p = canvasToAxisCoords;
plot.p2c = axisToCanvasCoords;
plot.getOptions = function () { return options; };
plot.highlight = highlight;
plot.unhighlight = unhighlight;
plot.triggerRedrawOverlay = triggerRedrawOverlay;
plot.pointOffset = function(point) {
return {
left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left),
top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top)
};
};
plot.shutdown = shutdown;
plot.resize = function () {
getCanvasDimensions();
resizeCanvas(canvas);
resizeCanvas(overlay);
};
// public attributes
plot.hooks = hooks;
// initialize
initPlugins(plot);
parseOptions(options_);
setupCanvases();
setData(data_);
setupGrid();
draw();
bindEvents();
function executeHooks(hook, args) {
args = [plot].concat(args);
for (var i = 0; i < hook.length; ++i)
hook[i].apply(this, args);
}
function initPlugins() {
for (var i = 0; i < plugins.length; ++i) {
var p = plugins[i];
p.init(plot);
if (p.options)
$.extend(true, options, p.options);
}
}
function parseOptions(opts) {
var i;
$.extend(true, options, opts);
if (options.xaxis.color == null)
options.xaxis.color = options.grid.color;
if (options.yaxis.color == null)
options.yaxis.color = options.grid.color;
if (options.xaxis.tickColor == null) // backwards-compatibility
options.xaxis.tickColor = options.grid.tickColor;
if (options.yaxis.tickColor == null) // backwards-compatibility
options.yaxis.tickColor = options.grid.tickColor;
if (options.grid.borderColor == null)
options.grid.borderColor = options.grid.color;
if (options.grid.tickColor == null)
options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
// fill in defaults in axes, copy at least always the
// first as the rest of the code assumes it'll be there
for (i = 0; i < Math.max(1, options.xaxes.length); ++i)
options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]);
for (i = 0; i < Math.max(1, options.yaxes.length); ++i)
options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]);
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
if (options.x2axis) {
options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
options.xaxes[1].position = "top";
}
if (options.y2axis) {
options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
options.yaxes[1].position = "right";
}
if (options.grid.coloredAreas)
options.grid.markings = options.grid.coloredAreas;
if (options.grid.coloredAreasColor)
options.grid.markingsColor = options.grid.coloredAreasColor;
if (options.lines)
$.extend(true, options.series.lines, options.lines);
if (options.points)
$.extend(true, options.series.points, options.points);
if (options.bars)
$.extend(true, options.series.bars, options.bars);
if (options.shadowSize != null)
options.series.shadowSize = options.shadowSize;
// save options on axes for future reference
for (i = 0; i < options.xaxes.length; ++i)
getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
for (i = 0; i < options.yaxes.length; ++i)
getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
// add hooks from options
for (var n in hooks)
if (options.hooks[n] && options.hooks[n].length)
hooks[n] = hooks[n].concat(options.hooks[n]);
executeHooks(hooks.processOptions, [options]);
}
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s = $.extend(true, {}, options.series);
if (d[i].data != null) {
s.data = d[i].data; // move the data instead of deep-copy
delete d[i].data;
$.extend(true, s, d[i]);
d[i].data = s.data;
}
else
s.data = d[i];
res.push(s);
}
return res;
}
function axisNumber(obj, coord) {
var a = obj[coord + "axis"];
if (typeof a == "object") // if we got a real axis, extract number
a = a.n;
if (typeof a != "number")
a = 1; // default to first axis
return a;
}
function allAxes() {
// return flat array without annoying null entries
return $.grep(xaxes.concat(yaxes), function (a) { return a; });
}
function canvasToAxisCoords(pos) {
// return an object with x/y corresponding to all used axes
var res = {}, i, axis;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used)
res["x" + axis.n] = axis.c2p(pos.left);
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used)
res["y" + axis.n] = axis.c2p(pos.top);
}
if (res.x1 !== undefined)
res.x = res.x1;
if (res.y1 !== undefined)
res.y = res.y1;
return res;
}
function axisToCanvasCoords(pos) {
// get canvas coords from the first pair of x/y found in pos
var res = {}, i, axis, key;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used) {
key = "x" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "x";
if (pos[key] != null) {
res.left = axis.p2c(pos[key]);
break;
}
}
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used) {
key = "y" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "y";
if (pos[key] != null) {
res.top = axis.p2c(pos[key]);
break;
}
}
}
return res;
}
function getOrCreateAxis(axes, number) {
if (!axes[number - 1])
axes[number - 1] = {
n: number, // save the number for future reference
direction: axes == xaxes ? "x" : "y",
options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
};
return axes[number - 1];
}
function fillInSeriesOptions() {
var i;
// collect what we already got of colors
var neededColors = series.length,
usedColors = [],
assignedColors = [];
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
--neededColors;
if (typeof sc == "number")
assignedColors.push(sc);
else
usedColors.push($.color.parse(series[i].color));
}
}
// we might need to generate more colors if higher indices
// are assigned
for (i = 0; i < assignedColors.length; ++i) {
neededColors = Math.max(neededColors, assignedColors[i] + 1);
}
// produce colors as needed
var colors = [], variation = 0;
i = 0;
while (colors.length < neededColors) {
var c;
if (options.colors.length == i) // check degenerate case
c = $.color.make(100, 100, 100);
else
c = $.color.parse(options.colors[i]);
// vary color if needed
var sign = variation % 2 == 1 ? -1 : 1;
c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2)
// FIXME: if we're getting to close to something else,
// we should probably skip this one
colors.push(c);
++i;
if (i >= options.colors.length) {
i = 0;
++variation;
}
}
// fill in the options
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// turn on lines automatically in case nothing is set
if (s.lines.show == null) {
var v, show = true;
for (v in s)
if (s[v] && s[v].show) {
show = false;
break;
}
if (show)
s.lines.show = true;
}
// setup axes
s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
}
}
function processData() {
var topSentry = Number.POSITIVE_INFINITY,
bottomSentry = Number.NEGATIVE_INFINITY,
fakeInfinity = Number.MAX_VALUE,
i, j, k, m, length,
s, points, ps, x, y, axis, val, f, p;
function updateAxis(axis, min, max) {
if (min < axis.datamin && min != -fakeInfinity)
axis.datamin = min;
if (max > axis.datamax && max != fakeInfinity)
axis.datamax = max;
}
$.each(allAxes(), function (_, axis) {
// init axis
axis.datamin = topSentry;
axis.datamax = bottomSentry;
axis.used = false;
});
for (i = 0; i < series.length; ++i) {
s = series[i];
s.datapoints = { points: [] };
executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
}
// first pass: clean and copy data
for (i = 0; i < series.length; ++i) {
s = series[i];
var data = s.data, format = s.datapoints.format;
if (!format) {
format = [];
// find out how to copy
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
format.push({ y: true, number: true, required: false, defaultValue: 0 });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
s.datapoints.format = format;
}
if (s.datapoints.pointsize != null)
continue; // already filled in
s.datapoints.pointsize = format.length;
ps = s.datapoints.pointsize;
points = s.datapoints.points;
insertSteps = s.lines.show && s.lines.steps;
s.xaxis.used = s.yaxis.used = true;
for (j = k = 0; j < data.length; ++j, k += ps) {
p = data[j];
var nullify = p == null;
if (!nullify) {
for (m = 0; m < ps; ++m) {
val = p[m];
f = format[m];
if (f) {
if (f.number && val != null) {
val = +val; // convert to number
if (isNaN(val))
val = null;
else if (val == Infinity)
val = fakeInfinity;
else if (val == -Infinity)
val = -fakeInfinity;
}
if (val == null) {
if (f.required)
nullify = true;
if (f.defaultValue != null)
val = f.defaultValue;
}
}
points[k + m] = val;
}
}
if (nullify) {
for (m = 0; m < ps; ++m) {
val = points[k + m];
if (val != null) {
f = format[m];
// extract min/max info
if (f.x)
updateAxis(s.xaxis, val, val);
if (f.y)
updateAxis(s.yaxis, val, val);
}
points[k + m] = null;
}
}
else {
// a little bit of line specific stuff that
// perhaps shouldn't be here, but lacking
// better means...
if (insertSteps && k > 0
&& points[k - ps] != null
&& points[k - ps] != points[k]
&& points[k - ps + 1] != points[k + 1]) {
// copy the point to make room for a middle point
for (m = 0; m < ps; ++m)
points[k + ps + m] = points[k + m];
// middle point has same y
points[k + 1] = points[k - ps + 1];
// we've added a point, better reflect that
k += ps;
}
}
}
}
// give the hooks a chance to run
for (i = 0; i < series.length; ++i) {
s = series[i];
executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
}
// second pass: find datamax/datamin for auto-scaling
for (i = 0; i < series.length; ++i) {
s = series[i];
points = s.datapoints.points,
ps = s.datapoints.pointsize;
var xmin = topSentry, ymin = topSentry,
xmax = bottomSentry, ymax = bottomSentry;
for (j = 0; j < points.length; j += ps) {
if (points[j] == null)
continue;
for (m = 0; m < ps; ++m) {
val = points[j + m];
f = format[m];
if (!f || val == fakeInfinity || val == -fakeInfinity)
continue;
if (f.x) {
if (val < xmin)
xmin = val;
if (val > xmax)
xmax = val;
}
if (f.y) {
if (val < ymin)
ymin = val;
if (val > ymax)
ymax = val;
}
}
}
if (s.bars.show) {
// make sure we got room for the bar on the dancing floor
var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2;
if (s.bars.horizontal) {
ymin += delta;
ymax += delta + s.bars.barWidth;
}
else {
xmin += delta;
xmax += delta + s.bars.barWidth;
}
}
updateAxis(s.xaxis, xmin, xmax);
updateAxis(s.yaxis, ymin, ymax);
}
$.each(allAxes(), function (_, axis) {
if (axis.datamin == topSentry)
axis.datamin = null;
if (axis.datamax == bottomSentry)
axis.datamax = null;
});
}
function makeCanvas(skipPositioning, cls) {
var c = document.createElement('canvas');
c.className = cls;
c.width = canvasWidth;
c.height = canvasHeight;
if (!skipPositioning)
$(c).css({ position: 'absolute', left: 0, top: 0 });
$(c).appendTo(placeholder);
if (!c.getContext) // excanvas hack
c = window.G_vmlCanvasManager.initElement(c);
// used for resetting in case we get replotted
c.getContext("2d").save();
return c;
}
function getCanvasDimensions() {
canvasWidth = placeholder.width();
canvasHeight = placeholder.height();
if (canvasWidth <= 0 || canvasHeight <= 0)
throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
}
function resizeCanvas(c) {
// resizing should reset the state (excanvas seems to be
// buggy though)
if (c.width != canvasWidth)
c.width = canvasWidth;
if (c.height != canvasHeight)
c.height = canvasHeight;
// so try to get back to the initial state (even if it's
// gone now, this should be safe according to the spec)
var cctx = c.getContext("2d");
cctx.restore();
// and save again
cctx.save();
}
function setupCanvases() {
var reused,
existingCanvas = placeholder.children("canvas.base"),
existingOverlay = placeholder.children("canvas.overlay");
if (existingCanvas.length == 0 || existingOverlay == 0) {
// init everything
placeholder.html(""); // make sure placeholder is clear
placeholder.css({ padding: 0 }); // padding messes up the positioning
if (placeholder.css("position") == 'static')
placeholder.css("position", "relative"); // for positioning labels and overlay
getCanvasDimensions();
canvas = makeCanvas(true, "base");
overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features
reused = false;
}
else {
// reuse existing elements
canvas = existingCanvas.get(0);
overlay = existingOverlay.get(0);
reused = true;
}
ctx = canvas.getContext("2d");
octx = overlay.getContext("2d");
// we include the canvas in the event holder too, because IE 7
// sometimes has trouble with the stacking order
eventHolder = $([overlay, canvas]);
if (reused) {
// run shutdown in the old plot object
placeholder.data("plot").shutdown();
// reset reused canvases
plot.resize();
// make sure overlay pixels are cleared (canvas is cleared when we redraw)
octx.clearRect(0, 0, canvasWidth, canvasHeight);
// then whack any remaining obvious garbage left
eventHolder.unbind();
placeholder.children().not([canvas, overlay]).remove();
}
// save in case we get replotted
placeholder.data("plot", plot);
}
function bindEvents() {
// bind events
if (options.grid.hoverable) {
eventHolder.mousemove(onMouseMove);
eventHolder.mouseleave(onMouseLeave);
}
if (options.grid.clickable)
eventHolder.click(onClick);
executeHooks(hooks.bindEvents, [eventHolder]);
}
function shutdown() {
if (redrawTimeout)
clearTimeout(redrawTimeout);
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mouseleave", onMouseLeave);
eventHolder.unbind("click", onClick);
executeHooks(hooks.shutdown, [eventHolder]);
}
function setTransformationHelpers(axis) {
// set helper functions on the axis, assumes plot area
// has been computed already
function identity(x) { return x; }
var s, m, t = axis.options.transform || identity,
it = axis.options.inverseTransform;
// precompute how much the axis is scaling a point
// in canvas space
if (axis.direction == "x") {
s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
m = Math.min(t(axis.max), t(axis.min));
}
else {
s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
s = -s;
m = Math.max(t(axis.max), t(axis.min));
}
// data point to canvas coordinate
if (t == identity) // slight optimization
axis.p2c = function (p) { return (p - m) * s; };
else
axis.p2c = function (p) { return (t(p) - m) * s; };
// canvas coordinate to data point
if (!it)
axis.c2p = function (c) { return m + c / s; };
else
axis.c2p = function (c) { return it(m + c / s); };
}
function measureTickLabels(axis) {
var opts = axis.options, i, ticks = axis.ticks || [], labels = [],
l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv;
function makeDummyDiv(labels, width) {
return $('<div style="position:absolute;top:-10000px;' + width + 'font-size:smaller">' +
'<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis">'
+ labels.join("") + '</div></div>')
.appendTo(placeholder);
}
if (axis.direction == "x") {
// to avoid measuring the widths of the labels (it's slow), we
// construct fixed-size boxes and put the labels inside
// them, we don't need the exact figures and the
// fixed-size box content is easy to center
if (w == null)
w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1));
// measure x label heights
if (h == null) {
labels = [];
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel" style="float:left;width:' + w + 'px">' + l + '</div>');
}
if (labels.length > 0) {
// stick them all in the same div and measure
// collective height
labels.push('<div style="clear:left"></div>');
dummyDiv = makeDummyDiv(labels, "width:10000px;");
h = dummyDiv.height();
dummyDiv.remove();
}
}
}
else if (w == null || h == null) {
// calculate y label dimensions
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel">' + l + '</div>');
}
if (labels.length > 0) {
dummyDiv = makeDummyDiv(labels, "");
if (w == null)
w = dummyDiv.children().width();
if (h == null)
h = dummyDiv.find("div.tickLabel").height();
dummyDiv.remove();
}
}
if (w == null)
w = 0;
if (h == null)
h = 0;
axis.labelWidth = w;
axis.labelHeight = h;
}
function allocateAxisBoxFirstPhase(axis) {
// find the bounding box of the axis by looking at label
// widths/heights and ticks, make room by diminishing the
// plotOffset
var lw = axis.labelWidth,
lh = axis.labelHeight,
pos = axis.options.position,
tickLength = axis.options.tickLength,
axismargin = options.grid.axisMargin,
padding = options.grid.labelMargin,
all = axis.direction == "x" ? xaxes : yaxes,
index;
// determine axis margin
var samePosition = $.grep(all, function (a) {
return a && a.options.position == pos && a.reserveSpace;
});
if ($.inArray(axis, samePosition) == samePosition.length - 1)
axismargin = 0; // outermost
// determine tick length - if we're innermost, we can use "full"
if (tickLength == null)
tickLength = "full";
var sameDirection = $.grep(all, function (a) {
return a && a.reserveSpace;
});
var innermost = $.inArray(axis, sameDirection) == 0;
if (!innermost && tickLength == "full")
tickLength = 5;
if (!isNaN(+tickLength))
padding += +tickLength;
// compute box
if (axis.direction == "x") {
lh += padding;
if (pos == "bottom") {
plotOffset.bottom += lh + axismargin;
axis.box = { top: canvasHeight - plotOffset.bottom, height: lh };
}
else {
axis.box = { top: plotOffset.top + axismargin, height: lh };
plotOffset.top += lh + axismargin;
}
}
else {
lw += padding;
if (pos == "left") {
axis.box = { left: plotOffset.left + axismargin, width: lw };
plotOffset.left += lw + axismargin;
}
else {
plotOffset.right += lw + axismargin;
axis.box = { left: canvasWidth - plotOffset.right, width: lw };
}
}
// save for future reference
axis.position = pos;
axis.tickLength = tickLength;
axis.box.padding = padding;
axis.innermost = innermost;
}
function allocateAxisBoxSecondPhase(axis) {
// set remaining bounding box coordinates
if (axis.direction == "x") {
axis.box.left = plotOffset.left;
axis.box.width = plotWidth;
}
else {
axis.box.top = plotOffset.top;
axis.box.height = plotHeight;
}
}
function setupGrid() {
var i, axes = allAxes();
// first calculate the plot and axis box dimensions
$.each(axes, function (_, axis) {
axis.show = axis.options.show;
if (axis.show == null)
axis.show = axis.used; // by default an axis is visible if it's got data
axis.reserveSpace = axis.show || axis.options.reserveSpace;
setRange(axis);
});
allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0;
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
// make the ticks
setupTickGeneration(axis);
setTicks(axis);
snapRangeToTicks(axis, axis.ticks);
// find labelWidth/Height for axis
measureTickLabels(axis);
});
// with all dimensions in house, we can compute the
// axis boxes, start from the outside (reverse order)
for (i = allocatedAxes.length - 1; i >= 0; --i)
allocateAxisBoxFirstPhase(allocatedAxes[i]);
// make sure we've got enough space for things that
// might stick out
var minMargin = options.grid.minBorderMargin;
if (minMargin == null) {
minMargin = 0;
for (i = 0; i < series.length; ++i)
minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2);
}
for (var a in plotOffset) {
plotOffset[a] += options.grid.borderWidth;
plotOffset[a] = Math.max(minMargin, plotOffset[a]);
}
}
plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
// now we got the proper plotWidth/Height, we can compute the scaling
$.each(axes, function (_, axis) {
setTransformationHelpers(axis);
});
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
allocateAxisBoxSecondPhase(axis);
});
insertAxisLabels();
}
insertLegend();
}
function setRange(axis) {
var opts = axis.options,
min = +(opts.min != null ? opts.min : axis.datamin),
max = +(opts.max != null ? opts.max : axis.datamax),
delta = max - min;
if (delta == 0.0) {
// degenerate case
var widen = max == 0 ? 1 : 0.01;
if (opts.min == null)
min -= widen;
// always widen max if we couldn't widen min to ensure we
// don't fall into min == max which doesn't work
if (opts.max == null || opts.min != null)
max += widen;
}
else {
// consider autoscaling
var margin = opts.autoscaleMargin;
if (margin != null) {
if (opts.min == null) {
min -= delta * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin != null && axis.datamin >= 0)
min = 0;
}
if (opts.max == null) {
max += delta * margin;
if (max > 0 && axis.datamax != null && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function setupTickGeneration(axis) {
var opts = axis.options;
// estimate number of ticks
var noTicks;
if (typeof opts.ticks == "number" && opts.ticks > 0)
noTicks = opts.ticks;
else
// heuristic based on the model a*sqrt(x) fitted to
// some data points that seemed reasonable
noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight);
var delta = (axis.max - axis.min) / noTicks,
size, generator, unit, formatter, i, magn, norm;
if (opts.mode == "time") {
// pretty handling of time
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var spec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"], [3, "month"], [6, "month"],
[1, "year"]
];
var minSize = 0;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number")
minSize = opts.tickSize;
else
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
for (var i = 0; i < spec.length - 1; ++i)
if (delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize)
break;
size = spec[i][0];
unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10));
norm = (delta / timeUnitSize.year) / magn;
if (norm < 1.5)
size = 1;
else if (norm < 3)
size = 2;
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
}
axis.tickSize = opts.tickSize || [size, unit];
generator = function(axis) {
var ticks = [],
tickSize = axis.tickSize[0], unit = axis.tickSize[1],
d = new Date(axis.min);
var step = tickSize * timeUnitSize[unit];
if (unit == "second")
d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
if (unit == "minute")
d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
if (unit == "hour")
d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
if (unit == "month")
d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
if (unit == "year")
d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
// reset smaller components
d.setUTCMilliseconds(0);
if (step >= timeUnitSize.minute)
d.setUTCSeconds(0);
if (step >= timeUnitSize.hour)
d.setUTCMinutes(0);
if (step >= timeUnitSize.day)
d.setUTCHours(0);
if (step >= timeUnitSize.day * 4)
d.setUTCDate(1);
if (step >= timeUnitSize.year)
d.setUTCMonth(0);
var carry = 0, v = Number.NaN, prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month") {
if (tickSize < 1) {
// a bit complicated - we'll divide the month
// up but we need to take care of fractions
// so we don't end up in the middle of a day
d.setUTCDate(1);
var start = d.getTime();
d.setUTCMonth(d.getUTCMonth() + 1);
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getUTCHours();
d.setUTCHours(0);
}
else
d.setUTCMonth(d.getUTCMonth() + tickSize);
}
else if (unit == "year") {
d.setUTCFullYear(d.getUTCFullYear() + tickSize);
}
else
d.setTime(v + step);
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
var d = new Date(v);
// first check global format
if (opts.timeformat != null)
return $.plot.formatDate(d, opts.timeformat, opts.monthNames);
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
if (t < timeUnitSize.minute)
fmt = "%h:%M:%S" + suffix;
else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day)
fmt = "%h:%M" + suffix;
else
fmt = "%b %d %h:%M" + suffix;
}
else if (t < timeUnitSize.month)
fmt = "%b %d";
else if (t < timeUnitSize.year) {
if (span < timeUnitSize.year)
fmt = "%b";
else
fmt = "%b %y";
}
else
fmt = "%y";
return $.plot.formatDate(d, fmt, opts.monthNames);
};
}
else {
// pretty rounding of base-10 numbers
var maxDec = opts.tickDecimals;
var dec = -Math.floor(Math.log(delta) / Math.LN10);
if (maxDec != null && dec > maxDec)
dec = maxDec;
magn = Math.pow(10, -dec);
norm = delta / magn; // norm is between 1.0 and 10.0
if (norm < 1.5)
size = 1;
else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
}
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
if (opts.minTickSize != null && size < opts.minTickSize)
size = opts.minTickSize;
axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
axis.tickSize = opts.tickSize || size;
generator = function (axis) {
var ticks = [];
// spew out all possible ticks
var start = floorInBase(axis.min, axis.tickSize),
i = 0, v = Number.NaN, prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
return v.toFixed(axis.tickDecimals);
};
}
if (opts.alignTicksWithAxis != null) {
var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
if (otherAxis && otherAxis.used && otherAxis != axis) {
// consider snapping min/max to outermost nice ticks
var niceTicks = generator(axis);
if (niceTicks.length > 0) {
if (opts.min == null)
axis.min = Math.min(axis.min, niceTicks[0]);
if (opts.max == null && niceTicks.length > 1)
axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
}
generator = function (axis) {
// copy ticks, scaled to this axis
var ticks = [], v, i;
for (i = 0; i < otherAxis.ticks.length; ++i) {
v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
v = axis.min + v * (axis.max - axis.min);
ticks.push(v);
}
return ticks;
};
// we might need an extra decimal since forced
// ticks don't necessarily fit naturally
if (axis.mode != "time" && opts.tickDecimals == null) {
var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1),
ts = generator(axis);
// only proceed if the tick interval rounded
// with an extra decimal doesn't give us a
// zero at end
if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
axis.tickDecimals = extraDec;
}
}
}
axis.tickGenerator = generator;
if ($.isFunction(opts.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
else
axis.tickFormatter = formatter;
}
function setTicks(axis) {
var oticks = axis.options.ticks, ticks = [];
if (oticks == null || (typeof oticks == "number" && oticks > 0))
ticks = axis.tickGenerator(axis);
else if (oticks) {
if ($.isFunction(oticks))
// generate the ticks
ticks = oticks({ min: axis.min, max: axis.max });
else
ticks = oticks;
}
// clean up/labelify the supplied ticks, copy them over
var i, v;
axis.ticks = [];
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = +t[0];
if (t.length > 1)
label = t[1];
}
else
v = +t;
if (label == null)
label = axis.tickFormatter(v, axis);
if (!isNaN(v))
axis.ticks.push({ v: v, label: label });
}
}
function snapRangeToTicks(axis, ticks) {
if (axis.options.autoscaleMargin && ticks.length > 0) {
// snap to ticks
if (axis.options.min == null)
axis.min = Math.min(axis.min, ticks[0].v);
if (axis.options.max == null && ticks.length > 1)
axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
}
}
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
var grid = options.grid;
// draw background, if any
if (grid.show && grid.backgroundColor)
drawBackground();
if (grid.show && !grid.aboveData)
drawGrid();
for (var i = 0; i < series.length; ++i) {
executeHooks(hooks.drawSeries, [ctx, series[i]]);
drawSeries(series[i]);
}
executeHooks(hooks.draw, [ctx]);
if (grid.show && grid.aboveData)
drawGrid();
}
function extractRange(ranges, coord) {
var axis, from, to, key, axes = allAxes();
for (i = 0; i < axes.length; ++i) {
axis = axes[i];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? xaxes[0] : yaxes[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function drawBackground() {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
ctx.fillRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
function drawGrid() {
var i;
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// draw markings
var markings = options.grid.markings;
if (markings) {
if ($.isFunction(markings)) {
var axes = plot.getAxes();
// xmin etc. is backwards compatibility, to be
// removed in the future
axes.xmin = axes.xaxis.min;
axes.xmax = axes.xaxis.max;
axes.ymin = axes.yaxis.min;
axes.ymax = axes.yaxis.max;
markings = markings(axes);
}
for (i = 0; i < markings.length; ++i) {
var m = markings[i],
xrange = extractRange(m, "x"),
yrange = extractRange(m, "y");
// fill in missing
if (xrange.from == null)
xrange.from = xrange.axis.min;
if (xrange.to == null)
xrange.to = xrange.axis.max;
if (yrange.from == null)
yrange.from = yrange.axis.min;
if (yrange.to == null)
yrange.to = yrange.axis.max;
// clip
if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
continue;
xrange.from = Math.max(xrange.from, xrange.axis.min);
xrange.to = Math.min(xrange.to, xrange.axis.max);
yrange.from = Math.max(yrange.from, yrange.axis.min);
yrange.to = Math.min(yrange.to, yrange.axis.max);
if (xrange.from == xrange.to && yrange.from == yrange.to)
continue;
// then draw
xrange.from = xrange.axis.p2c(xrange.from);
xrange.to = xrange.axis.p2c(xrange.to);
yrange.from = yrange.axis.p2c(yrange.from);
yrange.to = yrange.axis.p2c(yrange.to);
if (xrange.from == xrange.to || yrange.from == yrange.to) {
// draw line
ctx.beginPath();
ctx.strokeStyle = m.color || options.grid.markingsColor;
ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
ctx.moveTo(xrange.from, yrange.from);
ctx.lineTo(xrange.to, yrange.to);
ctx.stroke();
}
else {
// fill area
ctx.fillStyle = m.color || options.grid.markingsColor;
ctx.fillRect(xrange.from, yrange.to,
xrange.to - xrange.from,
yrange.from - yrange.to);
}
}
}
// draw the ticks
var axes = allAxes(), bw = options.grid.borderWidth;
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box,
t = axis.tickLength, x, y, xoff, yoff;
if (!axis.show || axis.ticks.length == 0)
continue
ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString();
ctx.lineWidth = 1;
// find the edges
if (axis.direction == "x") {
x = 0;
if (t == "full")
y = (axis.position == "top" ? 0 : plotHeight);
else
y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
}
else {
y = 0;
if (t == "full")
x = (axis.position == "left" ? 0 : plotWidth);
else
x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
}
// draw tick bar
if (!axis.innermost) {
ctx.beginPath();
xoff = yoff = 0;
if (axis.direction == "x")
xoff = plotWidth;
else
yoff = plotHeight;
if (ctx.lineWidth == 1) {
x = Math.floor(x) + 0.5;
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
ctx.stroke();
}
// draw ticks
ctx.beginPath();
for (i = 0; i < axis.ticks.length; ++i) {
var v = axis.ticks[i].v;
xoff = yoff = 0;
if (v < axis.min || v > axis.max
// skip those lying on the axes if we got a border
|| (t == "full" && bw > 0
&& (v == axis.min || v == axis.max)))
continue;
if (axis.direction == "x") {
x = axis.p2c(v);
yoff = t == "full" ? -plotHeight : t;
if (axis.position == "top")
yoff = -yoff;
}
else {
y = axis.p2c(v);
xoff = t == "full" ? -plotWidth : t;
if (axis.position == "left")
xoff = -xoff;
}
if (ctx.lineWidth == 1) {
if (axis.direction == "x")
x = Math.floor(x) + 0.5;
else
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
}
ctx.stroke();
}
// draw border
if (bw) {
ctx.lineWidth = bw;
ctx.strokeStyle = options.grid.borderColor;
ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
}
ctx.restore();
}
function insertAxisLabels() {
placeholder.find(".tickLabels").remove();
var html = ['<div class="tickLabels" style="font-size:smaller">'];
var axes = allAxes();
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box;
if (!axis.show)
continue;
//debug: html.push('<div style="position:absolute;opacity:0.10;background-color:red;left:' + box.left + 'px;top:' + box.top + 'px;width:' + box.width + 'px;height:' + box.height + 'px"></div>')
html.push('<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis" style="color:' + axis.options.color + '">');
for (var i = 0; i < axis.ticks.length; ++i) {
var tick = axis.ticks[i];
if (!tick.label || tick.v < axis.min || tick.v > axis.max)
continue;
var pos = {}, align;
if (axis.direction == "x") {
align = "center";
pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2);
if (axis.position == "bottom")
pos.top = box.top + box.padding;
else
pos.bottom = canvasHeight - (box.top + box.height - box.padding);
}
else {
pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2);
if (axis.position == "left") {
pos.right = canvasWidth - (box.left + box.width - box.padding)
align = "right";
}
else {
pos.left = box.left + box.padding;
align = "left";
}
}
pos.width = axis.labelWidth;
var style = ["position:absolute", "text-align:" + align ];
for (var a in pos)
style.push(a + ":" + pos[a] + "px")
html.push('<div class="tickLabel" style="' + style.join(';') + '">' + tick.label + '</div>');
}
html.push('</div>');
}
html.push('</div>');
placeholder.append(html.join(""));
}
function drawSeries(series) {
if (series.lines.show)
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
prevx = null, prevy = null;
ctx.beginPath();
for (var i = ps; i < points.length; i += ps) {
var x1 = points[i - ps], y1 = points[i - ps + 1],
x2 = points[i], y2 = points[i + 1];
if (x1 == null || x2 == null)
continue;
// clip with ymin
if (y1 <= y2 && y1 < axisy.min) {
if (y2 < axisy.min)
continue; // line segment is outside
// compute new intersection point
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min) {
if (y1 < axisy.min)
continue;
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max) {
if (y2 > axisy.max)
continue;
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max) {
if (y1 > axisy.max)
continue;
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (x1 != prevx || y1 != prevy)
ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
prevx = x2;
prevy = y2;
ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
}
ctx.stroke();
}
function plotLineArea(datapoints, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
bottom = Math.min(Math.max(0, axisy.min), axisy.max),
i = 0, top, areaOpen = false,
ypos = 1, segmentStart = 0, segmentEnd = 0;
// we process each segment in two turns, first forward
// direction to sketch out top, then once we hit the
// end we go backwards to sketch the bottom
while (true) {
if (ps > 0 && i > points.length + ps)
break;
i += ps; // ps is negative if going backwards
var x1 = points[i - ps],
y1 = points[i - ps + ypos],
x2 = points[i], y2 = points[i + ypos];
if (areaOpen) {
if (ps > 0 && x1 != null && x2 == null) {
// at turning point
segmentEnd = i;
ps = -ps;
ypos = 2;
continue;
}
if (ps < 0 && i == segmentStart + ps) {
// done with the reverse sweep
ctx.fill();
areaOpen = false;
ps = -ps;
ypos = 1;
i = segmentStart = segmentEnd + ps;
continue;
}
}
if (x1 == null || x2 == null)
continue;
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= axisy.max && y2 >= axisy.max) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
continue;
}
else if (y1 <= axisy.min && y2 <= axisy.min) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
continue;
}
// else it's a bit more complicated, there might
// be a flat maxed out rectangle first, then a
// triangular cutout or reverse; to find these
// keep track of the current x values
var x1old = x1, x2old = x2;
// clip the y values, without shortcutting, we
// go through all cases in turn
// clip with ymin
if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
// it goes to (x1, y1), but we fill that below
}
// fill triangular section, this sometimes result
// in redundant points if (x1, y1) hasn't changed
// from previous line to, but we just ignore that
ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth,
sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (lw > 0 && sw > 0) {
// draw shadow as a thick and thin line with transparency
ctx.lineWidth = sw;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
// position shadow at angle from the mid of line
var angle = Math.PI/18;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
ctx.lineWidth = sw/2;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
if (fillStyle) {
ctx.fillStyle = fillStyle;
plotLineArea(series.datapoints, series.xaxis, series.yaxis);
}
if (lw > 0)
plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var x = points[i], y = points[i + 1];
if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
continue;
ctx.beginPath();
x = axisx.p2c(x);
y = axisy.p2c(y) + offset;
if (symbol == "circle")
ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
else
symbol(ctx, x, y, radius, shadow);
ctx.closePath();
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.points.lineWidth,
sw = series.shadowSize,
radius = series.points.radius,
symbol = series.points.symbol;
if (lw > 0 && sw > 0) {
// draw shadow in two steps
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPoints(series.datapoints, radius, null, w + w/2, true,
series.xaxis, series.yaxis, symbol);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPoints(series.datapoints, radius, null, w/2, true,
series.xaxis, series.yaxis, symbol);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
plotPoints(series.datapoints, radius,
getFillStyle(series.points, series.color), 0, false,
series.xaxis, series.yaxis, symbol);
ctx.restore();
}
function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
var left, right, bottom, top,
drawLeft, drawRight, drawTop, drawBottom,
tmp;
// in horizontal mode, we start the bar from the left
// instead of from the bottom so it appears to be
// horizontal rather than vertical
if (horizontal) {
drawBottom = drawRight = drawTop = true;
drawLeft = false;
left = b;
right = x;
top = y + barLeft;
bottom = y + barRight;
// account for negative bars
if (right < left) {
tmp = right;
right = left;
left = tmp;
drawLeft = true;
drawRight = false;
}
}
else {
drawLeft = drawRight = drawTop = true;
drawBottom = false;
left = x + barLeft;
right = x + barRight;
bottom = b;
top = y;
// account for negative bars
if (top < bottom) {
tmp = top;
top = bottom;
bottom = tmp;
drawBottom = true;
drawTop = false;
}
}
// clip
if (right < axisx.min || left > axisx.max ||
top < axisy.min || bottom > axisy.max)
return;
if (left < axisx.min) {
left = axisx.min;
drawLeft = false;
}
if (right > axisx.max) {
right = axisx.max;
drawRight = false;
}
if (bottom < axisy.min) {
bottom = axisy.min;
drawBottom = false;
}
if (top > axisy.max) {
top = axisy.max;
drawTop = false;
}
left = axisx.p2c(left);
bottom = axisy.p2c(bottom);
right = axisx.p2c(right);
top = axisy.p2c(top);
// fill the bar
if (fillStyleCallback) {
c.beginPath();
c.moveTo(left, bottom);
c.lineTo(left, top);
c.lineTo(right, top);
c.lineTo(right, bottom);
c.fillStyle = fillStyleCallback(bottom, top);
c.fill();
}
// draw outline
if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
c.beginPath();
// FIXME: inline moveTo is buggy with excanvas
c.moveTo(left, bottom + offset);
if (drawLeft)
c.lineTo(left, top + offset);
else
c.moveTo(left, top + offset);
if (drawTop)
c.lineTo(right, top + offset);
else
c.moveTo(right, top + offset);
if (drawRight)
c.lineTo(right, bottom + offset);
else
c.moveTo(right, bottom + offset);
if (drawBottom)
c.lineTo(left, bottom + offset);
else
c.moveTo(left, bottom + offset);
c.stroke();
}
}
function drawSeriesBars(series) {
function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// FIXME: figure out a way to add shadows (for instance along the right edge)
ctx.lineWidth = series.bars.lineWidth;
ctx.strokeStyle = series.color;
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis);
ctx.restore();
}
function getFillStyle(filloptions, seriesColor, bottom, top) {
var fill = filloptions.fill;
if (!fill)
return null;
if (filloptions.fillColor)
return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
var c = $.color.parse(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
return c.toString();
}
function insertLegend() {
placeholder.find(".legend").remove();
if (!options.legend.show)
return;
var fragments = [], rowStarted = false,
lf = options.legend.labelFormatter, s, label;
for (var i = 0; i < series.length; ++i) {
s = series[i];
label = s.label;
if (!label)
continue;
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
if (lf)
label = lf(label, s);
fragments.push(
'<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + s.color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel">' + label + '</td>');
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length == 0)
return;
var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
$(options.legend.container).html(table);
else {
var pos = "",
p = options.legend.position,
m = options.legend.margin;
if (m[0] == null)
m = [m, m];
if (p.charAt(0) == "n")
pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
c = options.grid.backgroundColor;
if (c && typeof c == "string")
c = $.color.parse(c);
else
c = $.color.extract(legend, 'background-color');
c.a = 1;
c = c.toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
// interactive features
var highlights = [],
redrawTimeout = null;
// returns the data item the mouse is over, or null if none is found
function findNearbyItem(mouseX, mouseY, seriesFilter) {
var maxDistance = options.grid.mouseActiveRadius,
smallestDistance = maxDistance * maxDistance + 1,
item = null, foundPoint = false, i, j;
for (i = series.length - 1; i >= 0; --i) {
if (!seriesFilter(series[i]))
continue;
var s = series[i],
axisx = s.xaxis,
axisy = s.yaxis,
points = s.datapoints.points,
ps = s.datapoints.pointsize,
mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
my = axisy.c2p(mouseY),
maxx = maxDistance / axisx.scale,
maxy = maxDistance / axisy.scale;
// with inverse transforms, we can't use the maxx/maxy
// optimization, sadly
if (axisx.options.inverseTransform)
maxx = Number.MAX_VALUE;
if (axisy.options.inverseTransform)
maxy = Number.MAX_VALUE;
if (s.lines.show || s.points.show) {
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1];
if (x == null)
continue;
// For points and lines, the cursor must be within a
// certain distance to the data point
if (x - mx > maxx || x - mx < -maxx ||
y - my > maxy || y - my < -maxy)
continue;
// We have to calculate distances in pixels, not in
// data units, because the scales of the axes may be different
var dx = Math.abs(axisx.p2c(x) - mouseX),
dy = Math.abs(axisy.p2c(y) - mouseY),
dist = dx * dx + dy * dy; // we save the sqrt
// use <= to ensure last point takes precedence
// (last generally means on top of)
if (dist < smallestDistance) {
smallestDistance = dist;
item = [i, j / ps];
}
}
}
if (s.bars.show && !item) { // no other point can be nearby
var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2,
barRight = barLeft + s.bars.barWidth;
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1], b = points[j + 2];
if (x == null)
continue;
// for a bar graph, the cursor must be inside the bar
if (series[i].bars.horizontal ?
(mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
my >= y + barLeft && my <= y + barRight) :
(mx >= x + barLeft && mx <= x + barRight &&
my >= Math.min(b, y) && my <= Math.max(b, y)))
item = [i, j / ps];
}
}
}
if (item) {
i = item[0];
j = item[1];
ps = series[i].datapoints.pointsize;
return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
dataIndex: j,
series: series[i],
seriesIndex: i };
}
return null;
}
function onMouseMove(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return s["hoverable"] != false; });
}
function onMouseLeave(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return false; });
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters
// so we share their code)
function triggerClickHoverEvent(eventname, event, seriesFilter) {
var offset = eventHolder.offset(),
canvasX = event.pageX - offset.left - plotOffset.left,
canvasY = event.pageY - offset.top - plotOffset.top,
pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
pos.pageX = event.pageX;
pos.pageY = event.pageY;
var item = findNearbyItem(canvasX, canvasY, seriesFilter);
if (item) {
// fill in mouse pos for any listeners out there
item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left);
item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top);
}
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname &&
!(item && h.series == item.series &&
h.point[0] == item.datapoint[0] &&
h.point[1] == item.datapoint[1]))
unhighlight(h.series, h.point);
}
if (item)
highlight(item.series, item.datapoint, eventname);
}
placeholder.trigger(eventname, [ pos, item ]);
}
function triggerRedrawOverlay() {
if (!redrawTimeout)
redrawTimeout = setTimeout(drawOverlay, 30);
}
function drawOverlay() {
redrawTimeout = null;
// draw highlights
octx.save();
octx.clearRect(0, 0, canvasWidth, canvasHeight);
octx.translate(plotOffset.left, plotOffset.top);
var i, hi;
for (i = 0; i < highlights.length; ++i) {
hi = highlights[i];
if (hi.series.bars.show)
drawBarHighlight(hi.series, hi.point);
else
drawPointHighlight(hi.series, hi.point);
}
octx.restore();
executeHooks(hooks.drawOverlay, [octx]);
}
function highlight(s, point, auto) {
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i == -1) {
highlights.push({ series: s, point: point, auto: auto });
triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s, point) {
if (s == null && point == null) {
highlights = [];
triggerRedrawOverlay();
}
if (typeof s == "number")
s = series[s];
if (typeof point == "number")
point = s.data[point];
var i = indexOfHighlight(s, point);
if (i != -1) {
highlights.splice(i, 1);
triggerRedrawOverlay();
}
}
function indexOfHighlight(s, p) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s && h.point[0] == p[0]
&& h.point[1] == p[1])
return i;
}
return -1;
}
function drawPointHighlight(series, point) {
var x = point[0], y = point[1],
axisx = series.xaxis, axisy = series.yaxis;
if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
return;
var pointRadius = series.points.radius + series.points.lineWidth / 2;
octx.lineWidth = pointRadius;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var radius = 1.5 * pointRadius,
x = axisx.p2c(x),
y = axisy.p2c(y);
octx.beginPath();
if (series.points.symbol == "circle")
octx.arc(x, y, radius, 0, 2 * Math.PI, false);
else
series.points.symbol(octx, x, y, radius, false);
octx.closePath();
octx.stroke();
}
function drawBarHighlight(series, point) {
octx.lineWidth = series.bars.lineWidth;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
}
function getColorOrGradient(spec, bottom, top, defaultColor) {
if (typeof spec == "string")
return spec;
else {
// assume this is a gradient spec; IE currently only
// supports a simple vertical gradient properly, so that's
// what we support too
var gradient = ctx.createLinearGradient(0, top, 0, bottom);
for (var i = 0, l = spec.colors.length; i < l; ++i) {
var c = spec.colors[i];
if (typeof c != "string") {
var co = $.color.parse(defaultColor);
if (c.brightness != null)
co = co.scale('rgb', c.brightness)
if (c.opacity != null)
co.a *= c.opacity;
c = co.toString();
}
gradient.addColorStop(i / (l - 1), c);
}
return gradient;
}
}
}
$.plot = function(placeholder, data, options) {
//var t0 = new Date();
var plot = new Plot($(placeholder), data, options, $.plot.plugins);
//(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
return plot;
};
$.plot.version = "0.7";
$.plot.plugins = [];
// returns a string with the date d formatted according to fmt
$.plot.formatDate = function(d, fmt, monthNames) {
var leftPad = function(n) {
n = "" + n;
return n.length == 1 ? "0" + n : n;
};
var r = [];
var escape = false, padNext = false;
var hours = d.getUTCHours();
var isAM = hours < 12;
if (monthNames == null)
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
if (fmt.search(/%p|%P/) != -1) {
if (hours > 12) {
hours = hours - 12;
} else if (hours == 0) {
hours = 12;
}
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'h': c = "" + hours; break;
case 'H': c = leftPad(hours); break;
case 'M': c = leftPad(d.getUTCMinutes()); break;
case 'S': c = leftPad(d.getUTCSeconds()); break;
case 'd': c = "" + d.getUTCDate(); break;
case 'm': c = "" + (d.getUTCMonth() + 1); break;
case 'y': c = "" + d.getUTCFullYear(); break;
case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case '0': c = ""; padNext = true; break;
}
if (c && padNext) {
c = leftPad(c);
padNext = false;
}
r.push(c);
if (!padNext)
escape = false;
}
else {
if (c == "%")
escape = true;
else
r.push(c);
}
}
return r.join("");
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
})(jQuery);
| JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Coming Soon Countdown ===== */
$(function () {
var austDay = new Date();
austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 26);
$('#countdown').countdown({until: austDay});
$('#year').text(austDay.getFullYear());
}); | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Tooltips ===== */
$('.tooltip-test > button').tooltip();
/* ===== Popovers ===== */
$('.popover-test > button').popover();
/* ===== Smooth Scrolling ===== */
$(document).ready(function(){
$('a[href*=#typography],a[href*=#buttons], a[href*=#navs], a[href*=#pagination], a[href*=#tooltips], a[href*=#popovers], a[href*=#panels], a[href*=#accordion], a[href*=#carousel], a[href*=#info-boards], a[href*=#social-links], a[href*=#responsive-iframes]').bind("click", function(e){
var anchor = $(this);
$('html, body').stop().animate({
scrollTop: $(anchor.attr('href')).offset().top
}, 1000);
e.preventDefault();
});
return false;
});
| JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Tooltips ===== */
$('#bonus-tip').tooltip(); | JavaScript |
//** jQuery Scroll to Top Control script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** Available/ usage terms at http://www.dynamicdrive.com (March 30th, 09')
//** v1.1 (April 7th, 09'):
//** 1) Adds ability to scroll to an absolute position (from top of page) or specific element on the page instead.
//** 2) Fixes scroll animation not working in Opera.
var scrolltotop={
//startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control
//scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top).
setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]},
controlHTML: '<i class="fa fa-angle-up backtotop"></i>', //HTML for control, which is auto wrapped in DIV w/ ID="topcontrol"
controlattrs: {offsetx:5, offsety:5}, //offset of control relative to right/ bottom of window corner
anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links
state: {isvisible:false, shouldvisible:false},
scrollup:function(){
if (!this.cssfixedsupport) //if control is positioned using JavaScript
this.$control.css({opacity:0}) //hide control immediately after clicking it
var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto)
if (typeof dest=="string" && jQuery('#'+dest).length==1) //check element set by string exists
dest=jQuery('#'+dest).offset().top
else
dest=0
this.$body.animate({scrollTop: dest}, this.setting.scrollduration);
},
keepfixed:function(){
var $window=jQuery(window)
var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx
var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety
this.$control.css({left:controlx+'px', top:controly+'px'})
},
togglecontrol:function(){
var scrolltop=jQuery(window).scrollTop()
if (!this.cssfixedsupport)
this.keepfixed()
this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false
if (this.state.shouldvisible && !this.state.isvisible){
this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0])
this.state.isvisible=true
}
else if (this.state.shouldvisible==false && this.state.isvisible){
this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1])
this.state.isvisible=false
}
},
init:function(){
jQuery(document).ready(function($){
var mainobj=scrolltotop
var iebrws=document.all
mainobj.cssfixedsupport=!iebrws || iebrws && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode
mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body')
mainobj.$control=$('<div id="topcontrol">'+mainobj.controlHTML+'</div>')
.css({position:mainobj.cssfixedsupport? 'fixed' : 'absolute', bottom:mainobj.controlattrs.offsety, right:mainobj.controlattrs.offsetx, opacity:0, cursor:'pointer'})
.attr({title:''})
.click(function(){mainobj.scrollup(); return false})
.appendTo('body')
if (document.all && !window.XMLHttpRequest && mainobj.$control.text()!='') //loose check for IE6 and below, plus whether control contains any text
mainobj.$control.css({width:mainobj.$control.width()}) //IE6- seems to require an explicit width on a DIV containing text
mainobj.togglecontrol()
$('a[href="' + mainobj.anchorkeyword +'"]').click(function(){
mainobj.scrollup()
return false
})
$(window).bind('scroll resize', function(e){
mainobj.togglecontrol()
})
})
}
}
scrolltotop.init() | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
// Isotop Gallery
// ==============
var $container = $('#isotope-container');
$container.isotope({
itemSelector : '.isotope-item',
});
$('#filters a').click(function(){
var selector = $(this).attr('data-filter');
$container.isotope({ filter: selector });
return false;
}); | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Sign Up popovers ===== */
$(function(){
$('#name').popover();
});
$(function(){
$('#username').popover();
});
$(function(){
$('#email').popover();
});
$(function(){
$('#password').popover();
});
$(function(){
$('#repeat-password').popover();
}); | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Tooltips ===== */
$('#tooltip').tooltip(); | JavaScript |
/*------------------------------------------------------------------
Project: Paperclip
Author: Yevgeny S.
URL: https://twitter.com/YevSim
Version: 1.0
Created: 11/03/2014
Last change: 01/04/2014
-------------------------------------------------------------------*/
/* ===== Navbar Search ===== */
$('#navbar-search > a').on('click', function() {
$('#navbar-search > a > i').toggleClass('fa-search fa-times');
$("#navbar-search-box").toggleClass('show hidden animated fadeInUp');
return false;
});
/*===== Pricing Bonus ===== */
$('#bonus .pricing-number > .fa-scissors').on('click', function() {
$(this).css('left', '100%'); /* Cutting */
setTimeout(function(){ /* Removing the scissors */
$('#bonus .pricing-number > .fa-scissors').addClass('hidden');
$('#bonus .pricing-body ul').addClass('animated fadeOutDown');
}, 2000);
return false;
});
/* ===== Lost password form ===== */
$('.pwd-lost > .pwd-lost-q > a').on('click', function() {
$(".pwd-lost > .pwd-lost-q").toggleClass("show hidden");
$(".pwd-lost > .pwd-lost-f").toggleClass("hidden show animated fadeIn");
return false;
});
/* ===== Thumbs rating ===== */
$('.rating .voteup').on('click', function () {
var up = $(this).closest('div').find('.up');
up.text(parseInt(up.text(),10) + 1);
return false;
});
$('.rating .votedown').on('click', function () {
var down = $(this).closest('div').find('.down');
down.text(parseInt(down.text(),10) + 1);
return false;
});
/* ===== Responsive Showcase ===== */
$('.responsive-showcase ul > li > i').on('click', function() {
var device = $(this).data('device');
$('.responsive-showcase ul > li > i').addClass("inactive");
$(this).removeClass("inactive");
$('.responsive-showcase img').removeClass("show");
$('.responsive-showcase img').addClass("hidden");
$('.responsive-showcase img' + device).toggleClass("hidden show");
$('.responsive-showcase img' + device).addClass("animated fadeIn");
return false;
});
/* ===== Services ===== */
$('.service-item').hover (function() {
$(this).children("i").toggleClass("fa-rotate-90");
return false;
});
| JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
/*
Automatic, anti-aliased rounded corners.
By Steven Wittens
Based on http://pro.html.it/esempio/nifty/
Thanks to Jacob from Oddlabs.com for fixing two nasty bugs.
*/
function NiftyCheck() {
if(!document.getElementById || !document.createElement) {
return false;
}
var b = navigator.userAgent.toLowerCase();
if (b.indexOf("msie 5") > 0 && b.indexOf("opera") == -1) {
return false;
}
return true;
}
function Rounded(selector, bk, color, sizex, sizey) {
var i;
var v = getElementsBySelector(selector);
var l = v.length;
for (i = 0; i < l; i++) {
AddTop(v[i], bk, color, sizex, sizey);
AddBottom(v[i], bk, color, sizex, sizey);
}
}
Math.sqr = function (x) {
return x*x;
};
function Blend(a, b, alpha) {
var ca = Array(
parseInt('0x' + a.substring(1, 3)),
parseInt('0x' + a.substring(3, 5)),
parseInt('0x' + a.substring(5, 7))
);
var cb = Array(
parseInt('0x' + b.substring(1, 3)),
parseInt('0x' + b.substring(3, 5)),
parseInt('0x' + b.substring(5, 7))
);
r = '0' + Math.round(ca[0] + (cb[0] - ca[0])*alpha).toString(16);
g = '0' + Math.round(ca[1] + (cb[1] - ca[1])*alpha).toString(16);
b = '0' + Math.round(ca[2] + (cb[2] - ca[2])*alpha).toString(16);
return '#'
+ r.substring(r.length - 2)
+ g.substring(g.length - 2)
+ b.substring(b.length - 2);
}
function AddTop(el, bk, color, sizex, sizey) {
var i, j;
var d = document.createElement("div");
d.style.backgroundColor = bk;
d.className = "rounded";
var lastarc = 0;
for (i = 1; i <= sizey; i++) {
var coverage, arc2, arc3;
// Find intersection of arc with bottom of pixel row
arc = Math.sqrt(1.0 - Math.sqr(1.0 - i / sizey)) * sizex;
// Calculate how many pixels are bg, fg and blended.
var n_bg = sizex - Math.ceil(arc);
var n_fg = Math.floor(lastarc);
var n_aa = sizex - n_bg - n_fg;
// Create pixel row wrapper
var x = document.createElement("div");
var y = d;
x.style.margin = "0px " + n_bg +"px";
// Make a wrapper per anti-aliased pixel (at least one)
for (j = 1; j <= n_aa; j++) {
// Calculate coverage per pixel
// (approximates circle by a line within the pixel)
if (j == 1) {
if (j == n_aa) {
// Single pixel
coverage = ((arc + lastarc) * .5) - n_fg;
}
else {
// First in a run
arc2 = Math.sqrt(1.0 - Math.sqr(1.0 - (n_bg + 1) / sizex)) * sizey;
coverage = (arc2 - (sizey - i)) * (arc - n_fg - n_aa + 1) * .5;
}
}
else if (j == n_aa) {
// Last in a run
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = 1.0 - (1.0 - (arc2 - (sizey - i))) * (1.0 - (lastarc - n_fg)) * .5;
}
else {
// Middle of a run
arc3 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j) / sizex)) * sizey;
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = ((arc2 + arc3) * .5) - (sizey - i);
}
x.style.backgroundColor = Blend(bk, color, coverage);
y.appendChild(x);
y = x;
var x = document.createElement("div");
x.style.margin = "0px 1px";
}
x.style.backgroundColor = color;
y.appendChild(x);
lastarc = arc;
}
el.insertBefore(d, el.firstChild);
}
function AddBottom(el, bk, color, sizex, sizey) {
var i, j;
var d = document.createElement("div");
d.className = "rounded";
d.style.backgroundColor = bk;
var lastarc = 0;
for (i = 1; i <= sizey; i++) {
var coverage, arc2, arc3;
// Find intersection of arc with bottom of pixel row
arc = Math.sqrt(1.0 - Math.sqr(1.0 - i / sizey)) * sizex;
// Calculate how many pixels are bg, fg and blended.
var n_bg = sizex - Math.ceil(arc);
var n_fg = Math.floor(lastarc);
var n_aa = sizex - n_bg - n_fg;
// Create pixel row wrapper
var x = document.createElement("div");
var y = d;
x.style.margin = "0px " + n_bg + "px";
// Make a wrapper per anti-aliased pixel (at least one)
for (j = 1; j <= n_aa; j++) {
// Calculate coverage per pixel
// (approximates circle by a line within the pixel)
if (j == 1) {
if (j == n_aa) {
// Single pixel
coverage = ((arc + lastarc) * .5) - n_fg;
}
else {
// First in a run
arc2 = Math.sqrt(1.0 - Math.sqr(1.0 - (n_bg + 1) / sizex)) * sizey;
coverage = (arc2 - (sizey - i)) * (arc - n_fg - n_aa + 1) * .5;
}
}
else if (j == n_aa) {
// Last in a run
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = 1.0 - (1.0 - (arc2 - (sizey - i))) * (1.0 - (lastarc - n_fg)) * .5;
}
else {
// Middle of a run
arc3 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j) / sizex)) * sizey;
arc2 = Math.sqrt(1.0 - Math.sqr((sizex - n_bg - j + 1) / sizex)) * sizey;
coverage = ((arc2 + arc3) * .5) - (sizey - i);
}
x.style.backgroundColor = Blend(bk, color, coverage);
y.insertBefore(x, y.firstChild);
y = x;
var x = document.createElement("div");
x.style.margin = "0px 1px";
}
x.style.backgroundColor = color;
y.insertBefore(x, y.firstChild);
lastarc = arc;
}
el.appendChild(d);
}
function getElementsBySelector(selector) {
var i;
var s = [];
var selid = "";
var selclass = "";
var tag = selector;
var objlist = [];
if (selector.indexOf(" ") > 0) { //descendant selector like "tag#id tag"
s = selector.split(" ");
var fs = s[0].split("#");
if (fs.length == 1) {
return objlist;
}
return document.getElementById(fs[1]).getElementsByTagName(s[1]);
}
if (selector.indexOf("#") > 0) { //id selector like "tag#id"
s = selector.split("#");
tag = s[0];
selid = s[1];
}
if (selid != "") {
objlist.push(document.getElementById(selid));
return objlist;
}
if (selector.indexOf(".") > 0) { //class selector like "tag.class"
s = selector.split(".");
tag = s[0];
selclass = s[1];
}
var v = document.getElementsByTagName(tag); // tag selector like "tag"
if (selclass == "") {
return v;
}
for (i = 0; i < v.length; i++) {
if (v[i].className == selclass) {
objlist.push(v[i]);
}
}
return objlist;
}
| JavaScript |
function schedule_reload(){
setTimeout(reload, 3000);
}
function reload(){
window.location=window.location;
}
window.onload=schedule_reload(); | JavaScript |
{
"service" : {
"api" : "fastcgi",
"socket" : "stdin" // use server's socket
}
}
| JavaScript |
/*
* Easy Slider 1.7 - jQuery plugin
* written by Alen Grakalic
* http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
*
* Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* Built for jQuery library
* http://jquery.com
*
*/
/*
* markup example for $("#slider").easySlider();
*
* <div id="slider">
* <ul>
* <li><img src="images/01.jpg" alt="" /></li>
* <li><img src="images/02.jpg" alt="" /></li>
* <li><img src="images/03.jpg" alt="" /></li>
* <li><img src="images/04.jpg" alt="" /></li>
* <li><img src="images/05.jpg" alt="" /></li>
* </ul>
* </div>
*
*/
(function($) {
$.fn.easySlider = function(options){
// default configuration properties
var defaults = {
prevId: 'prevBtn',
prevText: 'Previous',
nextId: 'nextBtn',
nextText: 'Next',
controlsShow: true,
controlsBefore: '',
controlsAfter: '',
controlsFade: true,
firstId: 'firstBtn',
firstText: 'First',
firstShow: false,
lastId: 'lastBtn',
lastText: 'Last',
lastShow: false,
vertical: false,
speed: 800,
auto: false,
pause: 2000,
continuous: false,
numeric: false,
numericId: 'controls'
};
var options = $.extend(defaults, options);
this.each(function() {
var obj = $(this);
var s = $("li", obj).length;
var w = $("li", obj).width();
var h = $("li", obj).height();
var clickable = true;
obj.width(w);
obj.height(h);
obj.css("overflow","hidden");
var ts = s-1;
var t = 0;
$("ul", obj).css('width',s*w);
if(options.continuous){
$("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px"));
$("ul", obj).append($("ul li:nth-child(2)", obj).clone());
$("ul", obj).css('width',(s+1)*w);
};
if(!options.vertical) $("li", obj).css('float','left');
if(options.controlsShow){
var html = options.controlsBefore;
if(options.numeric){
html += '<ol id="'+ options.numericId +'"></ol>';
} else {
if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>';
html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';
};
html += options.controlsAfter;
$(obj).after(html);
};
if(options.numeric){
for(var i=0;i<s;i++){
$(document.createElement("li"))
.attr('id',options.numericId + (i+1))
.html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>')
.appendTo($("#"+ options.numericId))
.click(function(){
animate($("a",$(this)).attr('rel'),true);
});
};
} else {
$("a","#"+options.nextId).click(function(){
animate("next",true);
});
$("a","#"+options.prevId).click(function(){
animate("prev",true);
});
$("a","#"+options.firstId).click(function(){
animate("first",true);
});
$("a","#"+options.lastId).click(function(){
animate("last",true);
});
};
function setCurrent(i){
i = parseInt(i)+1;
$("li", "#" + options.numericId).removeClass("current");
$("li#" + options.numericId + i).addClass("current");
};
function adjust(){
if(t>ts) t=0;
if(t<0) t=ts;
if(!options.vertical) {
$("ul",obj).css("margin-left",(t*w*-1));
} else {
$("ul",obj).css("margin-left",(t*h*-1));
}
clickable = true;
if(options.numeric) setCurrent(t);
};
function animate(dir,clicked){
if (clickable){
clickable = false;
var ot = t;
switch(dir){
case "next":
t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;
break;
case "prev":
t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
break;
case "first":
t = 0;
break;
case "last":
t = ts;
break;
default:
t = dir;
break;
};
var diff = Math.abs(ot-t);
var speed = diff*options.speed;
if(!options.vertical) {
p = (t*w*-1);
$("ul",obj).animate(
{ marginLeft: p },
{ queue:false, duration:speed, complete:adjust }
);
} else {
p = (t*h*-1);
$("ul",obj).animate(
{ marginTop: p },
{ queue:false, duration:speed, complete:adjust }
);
};
if(!options.continuous && options.controlsFade){
if(t==ts){
$("a","#"+options.nextId).hide();
$("a","#"+options.lastId).hide();
} else {
$("a","#"+options.nextId).show();
$("a","#"+options.lastId).show();
};
if(t==0){
$("a","#"+options.prevId).hide();
$("a","#"+options.firstId).hide();
} else {
$("a","#"+options.prevId).show();
$("a","#"+options.firstId).show();
};
};
if(clicked) clearTimeout(timeout);
if(options.auto && dir=="next" && !clicked){;
timeout = setTimeout(function(){
animate("next",false);
},diff*options.speed+options.pause);
};
};
};
// init
var timeout;
if(options.auto){;
timeout = setTimeout(function(){
animate("next",false);
},options.pause);
};
if(options.numeric) setCurrent(0);
if(!options.continuous && options.controlsFade){
$("a","#"+options.prevId).hide();
$("a","#"+options.firstId).hide();
};
});
};
})(jQuery);
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/css',
'text!dat/gui/saveDialogue.html',
'text!dat/gui/style.css',
'dat/controllers/factory',
'dat/controllers/Controller',
'dat/controllers/BooleanController',
'dat/controllers/FunctionController',
'dat/controllers/NumberControllerBox',
'dat/controllers/NumberControllerSlider',
'dat/controllers/OptionController',
'dat/controllers/ColorController',
'dat/utils/requestAnimationFrame',
'dat/dom/CenteredDiv',
'dat/dom/dom',
'dat/utils/common'
], function(css, saveDialogueContents, styleSheet, controllerFactory, Controller, BooleanController, FunctionController, NumberControllerBox, NumberControllerSlider, OptionController, ColorController, requestAnimationFrame, CenteredDiv, dom, common) {
css.inject(styleSheet);
/** Outer-most className for GUI's */
var CSS_NAMESPACE = 'dg';
var HIDE_KEY_CODE = 72;
/** The only value shared between the JS and SCSS. Use caution. */
var CLOSE_BUTTON_HEIGHT = 20;
var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
var SUPPORTS_LOCAL_STORAGE = (function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
var SAVE_DIALOGUE;
/** Have we yet to create an autoPlace GUI? */
var auto_place_virgin = true;
/** Fixed position div that auto place GUI's go inside */
var auto_place_container;
/** Are we hiding the GUI's ? */
var hide = false;
/** GUI's which should be hidden */
var hideable_guis = [];
/**
* A lightweight controller library for JavaScript. It allows you to easily
* manipulate variables and fire functions on the fly.
* @class
*
* @member dat.gui
*
* @param {Object} [params]
* @param {String} [params.name] The name of this GUI.
* @param {Object} [params.load] JSON object representing the saved state of
* this GUI.
* @param {Boolean} [params.auto=true]
* @param {dat.gui.GUI} [params.parent] The GUI I'm nested in.
* @param {Boolean} [params.closed] If true, starts closed
*/
var GUI = function(params) {
var _this = this;
/**
* Outermost DOM Element
* @type DOMElement
*/
this.domElement = document.createElement('div');
this.__ul = document.createElement('ul');
this.domElement.appendChild(this.__ul);
dom.addClass(this.domElement, CSS_NAMESPACE);
/**
* Nested GUI's by name
* @ignore
*/
this.__folders = {};
this.__controllers = [];
/**
* List of objects I'm remembering for save, only used in top level GUI
* @ignore
*/
this.__rememberedObjects = [];
/**
* Maps the index of remembered objects to a map of controllers, only used
* in top level GUI.
*
* @private
* @ignore
*
* @example
* [
* {
* propertyName: Controller,
* anotherPropertyName: Controller
* },
* {
* propertyName: Controller
* }
* ]
*/
this.__rememberedObjectIndecesToControllers = [];
this.__listening = [];
params = params || {};
// Default parameters
params = common.defaults(params, {
autoPlace: true,
width: GUI.DEFAULT_WIDTH
});
params = common.defaults(params, {
resizable: params.autoPlace,
hideable: params.autoPlace
});
if (!common.isUndefined(params.load)) {
// Explicit preset
if (params.preset) params.load.preset = params.preset;
} else {
params.load = { preset: DEFAULT_DEFAULT_PRESET_NAME };
}
if (common.isUndefined(params.parent) && params.hideable) {
hideable_guis.push(this);
}
// Only root level GUI's are resizable.
params.resizable = common.isUndefined(params.parent) && params.resizable;
if (params.autoPlace && common.isUndefined(params.scrollable)) {
params.scrollable = true;
}
// params.scrollable = common.isUndefined(params.parent) && params.scrollable === true;
// Not part of params because I don't want people passing this in via
// constructor. Should be a 'remembered' value.
var use_local_storage =
SUPPORTS_LOCAL_STORAGE &&
localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
Object.defineProperties(this,
/** @lends dat.gui.GUI.prototype */
{
/**
* The parent <code>GUI</code>
* @type dat.gui.GUI
*/
parent: {
get: function() {
return params.parent;
}
},
scrollable: {
get: function() {
return params.scrollable;
}
},
/**
* Handles <code>GUI</code>'s element placement for you
* @type Boolean
*/
autoPlace: {
get: function() {
return params.autoPlace;
}
},
/**
* The identifier for a set of saved values
* @type String
*/
preset: {
get: function() {
if (_this.parent) {
return _this.getRoot().preset;
} else {
return params.load.preset;
}
},
set: function(v) {
if (_this.parent) {
_this.getRoot().preset = v;
} else {
params.load.preset = v;
}
setPresetSelectIndex(this);
_this.revert();
}
},
/**
* The width of <code>GUI</code> element
* @type Number
*/
width: {
get: function() {
return params.width;
},
set: function(v) {
params.width = v;
setWidth(_this, v);
}
},
/**
* The name of <code>GUI</code>. Used for folders. i.e
* a folder's name
* @type String
*/
name: {
get: function() {
return params.name;
},
set: function(v) {
// TODO Check for collisions among sibling folders
params.name = v;
if (title_row_name) {
title_row_name.innerHTML = params.name;
}
}
},
/**
* Whether the <code>GUI</code> is collapsed or not
* @type Boolean
*/
closed: {
get: function() {
return params.closed;
},
set: function(v) {
params.closed = v;
if (params.closed) {
dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
} else {
dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
}
// For browsers that aren't going to respect the CSS transition,
// Lets just check our height against the window height right off
// the bat.
this.onResize();
if (_this.__closeButton) {
_this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
}
}
},
/**
* Contains all presets
* @type Object
*/
load: {
get: function() {
return params.load;
}
},
/**
* Determines whether or not to use <a href="https://developer.mozilla.org/en/DOM/Storage#localStorage">localStorage</a> as the means for
* <code>remember</code>ing
* @type Boolean
*/
useLocalStorage: {
get: function() {
return use_local_storage;
},
set: function(bool) {
if (SUPPORTS_LOCAL_STORAGE) {
use_local_storage = bool;
if (bool) {
dom.bind(window, 'unload', saveToLocalStorage);
} else {
dom.unbind(window, 'unload', saveToLocalStorage);
}
localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
}
}
}
});
// Are we a root level GUI?
if (common.isUndefined(params.parent)) {
params.closed = false;
dom.addClass(this.domElement, GUI.CLASS_MAIN);
dom.makeSelectable(this.domElement, false);
// Are we supposed to be loading locally?
if (SUPPORTS_LOCAL_STORAGE) {
if (use_local_storage) {
_this.useLocalStorage = true;
var saved_gui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
if (saved_gui) {
params.load = JSON.parse(saved_gui);
}
}
}
this.__closeButton = document.createElement('div');
this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
this.domElement.appendChild(this.__closeButton);
dom.bind(this.__closeButton, 'click', function() {
_this.closed = !_this.closed;
});
// Oh, you're a nested GUI!
} else {
if (params.closed === undefined) {
params.closed = true;
}
var title_row_name = document.createTextNode(params.name);
dom.addClass(title_row_name, 'controller-name');
var title_row = addRow(_this, title_row_name);
var on_click_title = function(e) {
e.preventDefault();
_this.closed = !_this.closed;
return false;
};
dom.addClass(this.__ul, GUI.CLASS_CLOSED);
dom.addClass(title_row, 'title');
dom.bind(title_row, 'click', on_click_title);
if (!params.closed) {
this.closed = false;
}
}
if (params.autoPlace) {
if (common.isUndefined(params.parent)) {
if (auto_place_virgin) {
auto_place_container = document.createElement('div');
dom.addClass(auto_place_container, CSS_NAMESPACE);
dom.addClass(auto_place_container, GUI.CLASS_AUTO_PLACE_CONTAINER);
document.body.appendChild(auto_place_container);
auto_place_virgin = false;
}
// Put it in the dom for you.
auto_place_container.appendChild(this.domElement);
// Apply the auto styles
dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
}
// Make it not elastic.
if (!this.parent) setWidth(_this, params.width);
}
dom.bind(window, 'resize', function() { _this.onResize() });
dom.bind(this.__ul, 'webkitTransitionEnd', function() { _this.onResize(); });
dom.bind(this.__ul, 'transitionend', function() { _this.onResize() });
dom.bind(this.__ul, 'oTransitionEnd', function() { _this.onResize() });
this.onResize();
if (params.resizable) {
addResizeHandle(this);
}
function saveToLocalStorage() {
localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
}
var root = _this.getRoot();
function resetWidth() {
var root = _this.getRoot();
root.width += 1;
common.defer(function() {
root.width -= 1;
});
}
if (!params.parent) {
resetWidth();
}
};
GUI.toggleHide = function() {
hide = !hide;
common.each(hideable_guis, function(gui) {
gui.domElement.style.zIndex = hide ? -999 : 999;
gui.domElement.style.opacity = hide ? 0 : 1;
});
};
GUI.CLASS_AUTO_PLACE = 'a';
GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
GUI.CLASS_MAIN = 'main';
GUI.CLASS_CONTROLLER_ROW = 'cr';
GUI.CLASS_TOO_TALL = 'taller-than-window';
GUI.CLASS_CLOSED = 'closed';
GUI.CLASS_CLOSE_BUTTON = 'close-button';
GUI.CLASS_DRAG = 'drag';
GUI.DEFAULT_WIDTH = 245;
GUI.TEXT_CLOSED = 'Close Controls';
GUI.TEXT_OPEN = 'Open Controls';
dom.bind(window, 'keydown', function(e) {
if (document.activeElement.type !== 'text' &&
(e.which === HIDE_KEY_CODE || e.keyCode == HIDE_KEY_CODE)) {
GUI.toggleHide();
}
}, false);
common.extend(
GUI.prototype,
/** @lends dat.gui.GUI */
{
/**
* @param object
* @param property
* @returns {dat.controllers.Controller} The new controller that was added.
* @instance
*/
add: function(object, property) {
return add(
this,
object,
property,
{
factoryArgs: Array.prototype.slice.call(arguments, 2)
}
);
},
/**
* @param object
* @param property
* @returns {dat.controllers.ColorController} The new controller that was added.
* @instance
*/
addColor: function(object, property) {
return add(
this,
object,
property,
{
color: true
}
);
},
/**
* @param controller
* @instance
*/
remove: function(controller) {
// TODO listening?
this.__ul.removeChild(controller.__li);
this.__controllers.slice(this.__controllers.indexOf(controller), 1);
var _this = this;
common.defer(function() {
_this.onResize();
});
},
destroy: function() {
if (this.autoPlace) {
auto_place_container.removeChild(this.domElement);
}
},
/**
* @param name
* @returns {dat.gui.GUI} The new folder.
* @throws {Error} if this GUI already has a folder by the specified
* name
* @instance
*/
addFolder: function(name) {
// We have to prevent collisions on names in order to have a key
// by which to remember saved values
if (this.__folders[name] !== undefined) {
throw new Error('You already have a folder in this GUI by the' +
' name "' + name + '"');
}
var new_gui_params = { name: name, parent: this };
// We need to pass down the autoPlace trait so that we can
// attach event listeners to open/close folder actions to
// ensure that a scrollbar appears if the window is too short.
new_gui_params.autoPlace = this.autoPlace;
// Do we have saved appearance data for this folder?
if (this.load && // Anything loaded?
this.load.folders && // Was my parent a dead-end?
this.load.folders[name]) { // Did daddy remember me?
// Start me closed if I was closed
new_gui_params.closed = this.load.folders[name].closed;
// Pass down the loaded data
new_gui_params.load = this.load.folders[name];
}
var gui = new GUI(new_gui_params);
this.__folders[name] = gui;
var li = addRow(this, gui.domElement);
dom.addClass(li, 'folder');
return gui;
},
open: function() {
this.closed = false;
},
close: function() {
this.closed = true;
},
onResize: function() {
var root = this.getRoot();
if (root.scrollable) {
var top = dom.getOffset(root.__ul).top;
var h = 0;
common.each(root.__ul.childNodes, function(node) {
if (! (root.autoPlace && node === root.__save_row))
h += dom.getHeight(node);
});
if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
} else {
dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = 'auto';
}
}
if (root.__resize_handle) {
common.defer(function() {
root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
});
}
if (root.__closeButton) {
root.__closeButton.style.width = root.width + 'px';
}
},
/**
* Mark objects for saving. The order of these objects cannot change as
* the GUI grows. When remembering new objects, append them to the end
* of the list.
*
* @param {Object...} objects
* @throws {Error} if not called on a top level GUI.
* @instance
*/
remember: function() {
if (common.isUndefined(SAVE_DIALOGUE)) {
SAVE_DIALOGUE = new CenteredDiv();
SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents;
}
if (this.parent) {
throw new Error("You can only call remember on a top level GUI.");
}
var _this = this;
common.each(Array.prototype.slice.call(arguments), function(object) {
if (_this.__rememberedObjects.length == 0) {
addSaveMenu(_this);
}
if (_this.__rememberedObjects.indexOf(object) == -1) {
_this.__rememberedObjects.push(object);
}
});
if (this.autoPlace) {
// Set save row width
setWidth(this, this.width);
}
},
/**
* @returns {dat.gui.GUI} the topmost parent GUI of a nested GUI.
* @instance
*/
getRoot: function() {
var gui = this;
while (gui.parent) {
gui = gui.parent;
}
return gui;
},
/**
* @returns {Object} a JSON object representing the current state of
* this GUI as well as its remembered properties.
* @instance
*/
getSaveObject: function() {
var toReturn = this.load;
toReturn.closed = this.closed;
// Am I remembering any values?
if (this.__rememberedObjects.length > 0) {
toReturn.preset = this.preset;
if (!toReturn.remembered) {
toReturn.remembered = {};
}
toReturn.remembered[this.preset] = getCurrentPreset(this);
}
toReturn.folders = {};
common.each(this.__folders, function(element, key) {
toReturn.folders[key] = element.getSaveObject();
});
return toReturn;
},
save: function() {
if (!this.load.remembered) {
this.load.remembered = {};
}
this.load.remembered[this.preset] = getCurrentPreset(this);
markPresetModified(this, false);
},
saveAs: function(presetName) {
if (!this.load.remembered) {
// Retain default values upon first save
this.load.remembered = {};
this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
}
this.load.remembered[presetName] = getCurrentPreset(this);
this.preset = presetName;
addPresetOption(this, presetName, true);
},
revert: function(gui) {
common.each(this.__controllers, function(controller) {
// Make revert work on Default.
if (!this.getRoot().load.remembered) {
controller.setValue(controller.initialValue);
} else {
recallSavedValue(gui || this.getRoot(), controller);
}
}, this);
common.each(this.__folders, function(folder) {
folder.revert(folder);
});
if (!gui) {
markPresetModified(this.getRoot(), false);
}
},
listen: function(controller) {
var init = this.__listening.length == 0;
this.__listening.push(controller);
if (init) updateDisplays(this.__listening);
}
}
);
function add(gui, object, property, params) {
if (object[property] === undefined) {
throw new Error("Object " + object + " has no property \"" + property + "\"");
}
var controller;
if (params.color) {
controller = new ColorController(object, property);
} else {
var factoryArgs = [object,property].concat(params.factoryArgs);
controller = controllerFactory.apply(gui, factoryArgs);
}
if (params.before instanceof Controller) {
params.before = params.before.__li;
}
recallSavedValue(gui, controller);
dom.addClass(controller.domElement, 'c');
var name = document.createElement('span');
dom.addClass(name, 'property-name');
name.innerHTML = controller.property;
var container = document.createElement('div');
container.appendChild(name);
container.appendChild(controller.domElement);
var li = addRow(gui, container, params.before);
dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
dom.addClass(li, typeof controller.getValue());
augmentController(gui, li, controller);
gui.__controllers.push(controller);
return controller;
}
/**
* Add a row to the end of the GUI or before another row.
*
* @param gui
* @param [dom] If specified, inserts the dom content in the new row
* @param [liBefore] If specified, places the new row before another row
*/
function addRow(gui, dom, liBefore) {
var li = document.createElement('li');
if (dom) li.appendChild(dom);
if (liBefore) {
gui.__ul.insertBefore(li, params.before);
} else {
gui.__ul.appendChild(li);
}
gui.onResize();
return li;
}
function augmentController(gui, li, controller) {
controller.__li = li;
controller.__gui = gui;
common.extend(controller, {
options: function(options) {
if (arguments.length > 1) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [common.toArray(arguments)]
}
);
}
if (common.isArray(options) || common.isObject(options)) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [options]
}
);
}
},
name: function(v) {
controller.__li.firstElementChild.firstElementChild.innerHTML = v;
return controller;
},
listen: function() {
controller.__gui.listen(controller);
return controller;
},
remove: function() {
controller.__gui.remove(controller);
return controller;
}
});
// All sliders should be accompanied by a box.
if (controller instanceof NumberControllerSlider) {
var box = new NumberControllerBox(controller.object, controller.property,
{ min: controller.__min, max: controller.__max, step: controller.__step });
common.each(['updateDisplay', 'onChange', 'onFinishChange'], function(method) {
var pc = controller[method];
var pb = box[method];
controller[method] = box[method] = function() {
var args = Array.prototype.slice.call(arguments);
pc.apply(controller, args);
return pb.apply(box, args);
}
});
dom.addClass(li, 'has-slider');
controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
}
else if (controller instanceof NumberControllerBox) {
var r = function(returned) {
// Have we defined both boundaries?
if (common.isNumber(controller.__min) && common.isNumber(controller.__max)) {
// Well, then lets just replace this with a slider.
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [controller.__min, controller.__max, controller.__step]
});
}
return returned;
};
controller.min = common.compose(r, controller.min);
controller.max = common.compose(r, controller.max);
}
else if (controller instanceof BooleanController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__checkbox, 'click');
});
dom.bind(controller.__checkbox, 'click', function(e) {
e.stopPropagation(); // Prevents double-toggle
})
}
else if (controller instanceof FunctionController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__button, 'click');
});
dom.bind(li, 'mouseover', function() {
dom.addClass(controller.__button, 'hover');
});
dom.bind(li, 'mouseout', function() {
dom.removeClass(controller.__button, 'hover');
});
}
else if (controller instanceof ColorController) {
dom.addClass(li, 'color');
controller.updateDisplay = common.compose(function(r) {
li.style.borderLeftColor = controller.__color.toString();
return r;
}, controller.updateDisplay);
controller.updateDisplay();
}
controller.setValue = common.compose(function(r) {
if (gui.getRoot().__preset_select && controller.isModified()) {
markPresetModified(gui.getRoot(), true);
}
return r;
}, controller.setValue);
}
function recallSavedValue(gui, controller) {
// Find the topmost GUI, that's where remembered objects live.
var root = gui.getRoot();
// Does the object we're controlling match anything we've been told to
// remember?
var matched_index = root.__rememberedObjects.indexOf(controller.object);
// Why yes, it does!
if (matched_index != -1) {
// Let me fetch a map of controllers for thcommon.isObject.
var controller_map =
root.__rememberedObjectIndecesToControllers[matched_index];
// Ohp, I believe this is the first controller we've created for this
// object. Lets make the map fresh.
if (controller_map === undefined) {
controller_map = {};
root.__rememberedObjectIndecesToControllers[matched_index] =
controller_map;
}
// Keep track of this controller
controller_map[controller.property] = controller;
// Okay, now have we saved any values for this controller?
if (root.load && root.load.remembered) {
var preset_map = root.load.remembered;
// Which preset are we trying to load?
var preset;
if (preset_map[gui.preset]) {
preset = preset_map[gui.preset];
} else if (preset_map[DEFAULT_DEFAULT_PRESET_NAME]) {
// Uhh, you can have the default instead?
preset = preset_map[DEFAULT_DEFAULT_PRESET_NAME];
} else {
// Nada.
return;
}
// Did the loaded object remember thcommon.isObject?
if (preset[matched_index] &&
// Did we remember this particular property?
preset[matched_index][controller.property] !== undefined) {
// We did remember something for this guy ...
var value = preset[matched_index][controller.property];
// And that's what it is.
controller.initialValue = value;
controller.setValue(value);
}
}
}
}
function getLocalStorageHash(gui, key) {
// TODO how does this deal with multiple GUI's?
return document.location.href + '.' + key;
}
function addSaveMenu(gui) {
var div = gui.__save_row = document.createElement('li');
dom.addClass(gui.domElement, 'has-save');
gui.__ul.insertBefore(div, gui.__ul.firstChild);
dom.addClass(div, 'save-row');
var gears = document.createElement('span');
gears.innerHTML = ' ';
dom.addClass(gears, 'button gears');
// TODO replace with FunctionController
var button = document.createElement('span');
button.innerHTML = 'Save';
dom.addClass(button, 'button');
dom.addClass(button, 'save');
var button2 = document.createElement('span');
button2.innerHTML = 'New';
dom.addClass(button2, 'button');
dom.addClass(button2, 'save-as');
var button3 = document.createElement('span');
button3.innerHTML = 'Revert';
dom.addClass(button3, 'button');
dom.addClass(button3, 'revert');
var select = gui.__preset_select = document.createElement('select');
if (gui.load && gui.load.remembered) {
common.each(gui.load.remembered, function(value, key) {
addPresetOption(gui, key, key == gui.preset);
});
} else {
addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
}
dom.bind(select, 'change', function() {
for (var index = 0; index < gui.__preset_select.length; index++) {
gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
}
gui.preset = this.value;
});
div.appendChild(select);
div.appendChild(gears);
div.appendChild(button);
div.appendChild(button2);
div.appendChild(button3);
if (SUPPORTS_LOCAL_STORAGE) {
var saveLocally = document.getElementById('dg-save-locally');
var explain = document.getElementById('dg-local-explain');
saveLocally.style.display = 'block';
var localStorageCheckBox = document.getElementById('dg-local-storage');
if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
localStorageCheckBox.setAttribute('checked', 'checked');
}
function showHideExplain() {
explain.style.display = gui.useLocalStorage ? 'block' : 'none';
}
showHideExplain();
// TODO: Use a boolean controller, fool!
dom.bind(localStorageCheckBox, 'change', function() {
gui.useLocalStorage = !gui.useLocalStorage;
showHideExplain();
});
}
var newConstructorTextArea = document.getElementById('dg-new-constructor');
dom.bind(newConstructorTextArea, 'keydown', function(e) {
if (e.metaKey && (e.which === 67 || e.keyCode == 67)) {
SAVE_DIALOGUE.hide();
}
});
dom.bind(gears, 'click', function() {
newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
SAVE_DIALOGUE.show();
newConstructorTextArea.focus();
newConstructorTextArea.select();
});
dom.bind(button, 'click', function() {
gui.save();
});
dom.bind(button2, 'click', function() {
var presetName = prompt('Enter a new preset name.');
if (presetName) gui.saveAs(presetName);
});
dom.bind(button3, 'click', function() {
gui.revert();
});
// div.appendChild(button2);
}
function addResizeHandle(gui) {
gui.__resize_handle = document.createElement('div');
common.extend(gui.__resize_handle.style, {
width: '6px',
marginLeft: '-3px',
height: '200px',
cursor: 'ew-resize',
position: 'absolute'
// border: '1px solid blue'
});
var pmouseX;
dom.bind(gui.__resize_handle, 'mousedown', dragStart);
dom.bind(gui.__closeButton, 'mousedown', dragStart);
gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
function dragStart(e) {
e.preventDefault();
pmouseX = e.clientX;
dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.bind(window, 'mousemove', drag);
dom.bind(window, 'mouseup', dragStop);
return false;
}
function drag(e) {
e.preventDefault();
gui.width += pmouseX - e.clientX;
gui.onResize();
pmouseX = e.clientX;
return false;
}
function dragStop() {
dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.unbind(window, 'mousemove', drag);
dom.unbind(window, 'mouseup', dragStop);
}
}
function setWidth(gui, w) {
gui.domElement.style.width = w + 'px';
// Auto placed save-rows are position fixed, so we have to
// set the width manually if we want it to bleed to the edge
if (gui.__save_row && gui.autoPlace) {
gui.__save_row.style.width = w + 'px';
}if (gui.__closeButton) {
gui.__closeButton.style.width = w + 'px';
}
}
function getCurrentPreset(gui, useInitialValues) {
var toReturn = {};
// For each object I'm remembering
common.each(gui.__rememberedObjects, function(val, index) {
var saved_values = {};
// The controllers I've made for thcommon.isObject by property
var controller_map =
gui.__rememberedObjectIndecesToControllers[index];
// Remember each value for each property
common.each(controller_map, function(controller, property) {
saved_values[property] = useInitialValues ? controller.initialValue : controller.getValue();
});
// Save the values for thcommon.isObject
toReturn[index] = saved_values;
});
return toReturn;
}
function addPresetOption(gui, name, setSelected) {
var opt = document.createElement('option');
opt.innerHTML = name;
opt.value = name;
gui.__preset_select.appendChild(opt);
if (setSelected) {
gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
}
}
function setPresetSelectIndex(gui) {
for (var index = 0; index < gui.__preset_select.length; index++) {
if (gui.__preset_select[index].value == gui.preset) {
gui.__preset_select.selectedIndex = index;
}
}
}
function markPresetModified(gui, modified) {
var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
// console.log('mark', modified, opt);
if (modified) {
opt.innerHTML = opt.value + "*";
} else {
opt.innerHTML = opt.value;
}
}
function updateDisplays(controllerArray) {
if (controllerArray.length != 0) {
requestAnimationFrame(function() {
updateDisplays(controllerArray);
});
}
common.each(controllerArray, function(c) {
c.updateDisplay();
});
}
return GUI;
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
], function() {
/**
* requirejs version of Paul Irish's RequestAnimationFrame
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
window.setTimeout(callback, 1000 / 60);
};
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([],
function() {
return {
load: function (url, doc) {
doc = doc || document;
var link = doc.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
doc.getElementsByTagName('head')[0].appendChild(link);
},
inject: function(css, doc) {
doc = doc || document;
var injected = document.createElement('style');
injected.type = 'text/css';
injected.innerHTML = css;
doc.getElementsByTagName('head')[0].appendChild(injected);
}
}
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
], function() {
var ARR_EACH = Array.prototype.forEach;
var ARR_SLICE = Array.prototype.slice;
/**
* Band-aid methods for things that should be a lot easier in JavaScript.
* Implementation and structure inspired by underscore.js
* http://documentcloud.github.com/underscore/
*/
return {
BREAK: {},
extend: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (!this.isUndefined(obj[key]))
target[key] = obj[key];
}, this);
return target;
},
defaults: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (this.isUndefined(target[key]))
target[key] = obj[key];
}, this);
return target;
},
compose: function() {
var toCall = ARR_SLICE.call(arguments);
return function() {
var args = ARR_SLICE.call(arguments);
for (var i = toCall.length -1; i >= 0; i--) {
args = [toCall[i].apply(this, args)];
}
return args[0];
}
},
each: function(obj, itr, scope) {
if (ARR_EACH && obj.forEach === ARR_EACH) {
obj.forEach(itr, scope);
} else if (obj.length === obj.length + 0) { // Is number but not NaN
for (var key = 0, l = obj.length; key < l; key++)
if (key in obj && itr.call(scope, obj[key], key) === this.BREAK)
return;
} else {
for (var key in obj)
if (itr.call(scope, obj[key], key) === this.BREAK)
return;
}
},
defer: function(fnc) {
setTimeout(fnc, 0);
},
toArray: function(obj) {
if (obj.toArray) return obj.toArray();
return ARR_SLICE.call(obj);
},
isUndefined: function(obj) {
return obj === undefined;
},
isNull: function(obj) {
return obj === null;
},
isNaN: function(obj) {
return obj !== obj;
},
isArray: Array.isArray || function(obj) {
return obj.constructor === Array;
},
isObject: function(obj) {
return obj === Object(obj);
},
isNumber: function(obj) {
return obj === obj+0;
},
isString: function(obj) {
return obj === obj+'';
},
isBoolean: function(obj) {
return obj === false || obj === true;
},
isFunction: function(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
};
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/common'
], function(common) {
return function(color) {
if (color.a == 1 || common.isUndefined(color.a)) {
var s = color.hex.toString(16);
while (s.length < 6) {
s = '0' + s;
}
return '#' + s;
} else {
return 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',' + color.a + ')';
}
}
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/color/interpret',
'dat/color/math',
'dat/color/toString',
'dat/utils/common'
], function(interpret, math, toString, common) {
var Color = function() {
this.__state = interpret.apply(this, arguments);
if (this.__state === false) {
throw 'Failed to interpret color arguments';
}
this.__state.a = this.__state.a || 1;
};
Color.COMPONENTS = ['r','g','b','h','s','v','hex','a'];
common.extend(Color.prototype, {
toString: function() {
return toString(this);
},
toOriginal: function() {
return this.__state.conversion.write(this);
}
});
defineRGBComponent(Color.prototype, 'r', 2);
defineRGBComponent(Color.prototype, 'g', 1);
defineRGBComponent(Color.prototype, 'b', 0);
defineHSVComponent(Color.prototype, 'h');
defineHSVComponent(Color.prototype, 's');
defineHSVComponent(Color.prototype, 'v');
Object.defineProperty(Color.prototype, 'a', {
get: function() {
return this.__state.a;
},
set: function(v) {
this.__state.a = v;
}
});
Object.defineProperty(Color.prototype, 'hex', {
get: function() {
if (!this.__state.space !== 'HEX') {
this.__state.hex = math.rgb_to_hex(this.r, this.g, this.b);
}
return this.__state.hex;
},
set: function(v) {
this.__state.space = 'HEX';
this.__state.hex = v;
}
});
function defineRGBComponent(target, component, componentHexIndex) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'RGB') {
return this.__state[component];
}
recalculateRGB(this, component, componentHexIndex);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'RGB') {
recalculateRGB(this, component, componentHexIndex);
this.__state.space = 'RGB';
}
this.__state[component] = v;
}
});
}
function defineHSVComponent(target, component) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'HSV')
return this.__state[component];
recalculateHSV(this);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'HSV') {
recalculateHSV(this);
this.__state.space = 'HSV';
}
this.__state[component] = v;
}
});
}
function recalculateRGB(color, component, componentHexIndex) {
if (color.__state.space === 'HEX') {
color.__state[component] = math.component_from_hex(color.__state.hex, componentHexIndex);
} else if (color.__state.space === 'HSV') {
common.extend(color.__state, math.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
} else {
throw 'Corrupted color state';
}
}
function recalculateHSV(color) {
var result = math.rgb_to_hsv(color.r, color.g, color.b);
common.extend(color.__state,
{
s: result.s,
v: result.v
}
);
if (!common.isNaN(result.h)) {
color.__state.h = result.h;
} else if (common.isUndefined(color.__state.h)) {
color.__state.h = 0;
}
}
return Color;
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
], function() {
var tmpComponent;
return {
hsv_to_rgb: function(h, s, v) {
var hi = Math.floor(h / 60) % 6;
var f = h / 60 - Math.floor(h / 60);
var p = v * (1.0 - s);
var q = v * (1.0 - (f * s));
var t = v * (1.0 - ((1.0 - f) * s));
var c = [
[v, t, p],
[q, v, p],
[p, v, t],
[p, q, v],
[t, p, v],
[v, p, q]
][hi];
return {
r: c[0] * 255,
g: c[1] * 255,
b: c[2] * 255
};
},
rgb_to_hsv: function(r, g, b) {
var min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s;
if (max != 0) {
s = delta / max;
} else {
return {
h: NaN,
s: 0,
v: 0
};
}
if (r == max) {
h = (g - b) / delta;
} else if (g == max) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h /= 6;
if (h < 0) {
h += 1;
}
return {
h: h * 360,
s: s,
v: max / 255
};
},
rgb_to_hex: function(r, g, b) {
var hex = this.hex_with_component(0, 2, r);
hex = this.hex_with_component(hex, 1, g);
hex = this.hex_with_component(hex, 0, b);
return hex;
},
component_from_hex: function(hex, componentIndex) {
return (hex >> (componentIndex * 8)) & 0xFF;
},
hex_with_component: function(hex, componentIndex, value) {
return value << (tmpComponent = componentIndex * 8) | (hex & ~ (0xFF << tmpComponent));
}
}
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/color/toString',
'dat/utils/common'
], function(toString, common) {
var result, toReturn;
var interpret = function() {
toReturn = false;
var original = arguments.length > 1 ? common.toArray(arguments) : arguments[0];
common.each(INTERPRETATIONS, function(family) {
if (family.litmus(original)) {
common.each(family.conversions, function(conversion, conversionName) {
result = conversion.read(original);
if (toReturn === false && result !== false) {
toReturn = result;
result.conversionName = conversionName;
result.conversion = conversion;
return common.BREAK;
}
});
return common.BREAK;
}
});
return toReturn;
};
var INTERPRETATIONS = [
// Strings
{
litmus: common.isString,
conversions: {
THREE_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt(
'0x' +
test[1].toString() + test[1].toString() +
test[2].toString() + test[2].toString() +
test[3].toString() + test[3].toString())
};
},
write: toString
},
SIX_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9]{6})$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt('0x' + test[1].toString())
};
},
write: toString
},
CSS_RGB: {
read: function(original) {
var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3])
};
},
write: toString
},
CSS_RGBA: {
read: function(original) {
var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3]),
a: parseFloat(test[4])
};
},
write: toString
}
}
},
// Numbers
{
litmus: common.isNumber,
conversions: {
HEX: {
read: function(original) {
return {
space: 'HEX',
hex: original,
conversionName: 'HEX'
}
},
write: function(color) {
return color.hex;
}
}
}
},
// Arrays
{
litmus: common.isArray,
conversions: {
RGB_ARRAY: {
read: function(original) {
if (original.length != 3) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2]
};
},
write: function(color) {
return [color.r, color.g, color.b];
}
},
RGBA_ARRAY: {
read: function(original) {
if (original.length != 4) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2],
a: original[3]
};
},
write: function(color) {
return [color.r, color.g, color.b, color.a];
}
}
}
},
// Objects
{
litmus: common.isObject,
conversions: {
RGBA_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b) &&
common.isNumber(original.a)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b,
a: original.a
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b,
a: color.a
}
}
},
RGB_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b
}
}
},
HSVA_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v) &&
common.isNumber(original.a)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v,
a: original.a
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v,
a: color.a
}
}
},
HSV_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v
}
}
}
}
}
];
return interpret;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/common'
], function(common) {
/**
* @class An "abstract" class that represents a given property of an object.
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var Controller = function(object, property) {
this.initialValue = object[property];
/**
* Those who extend this class will put their DOM elements in here.
* @type {DOMElement}
*/
this.domElement = document.createElement('div');
/**
* The object to manipulate
* @type {Object}
*/
this.object = object;
/**
* The name of the property to manipulate
* @type {String}
*/
this.property = property;
/**
* The function to be called on change.
* @type {Function}
* @ignore
*/
this.__onChange = undefined;
/**
* The function to be called on finishing change.
* @type {Function}
* @ignore
*/
this.__onFinishChange = undefined;
};
common.extend(
Controller.prototype,
/** @lends dat.controllers.Controller.prototype */
{
/**
* Specify that a function fire every time someone changes the value with
* this Controller.
*
* @param {Function} fnc This function will be called whenever the value
* is modified via this Controller.
* @returns {dat.controllers.Controller} this
*/
onChange: function(fnc) {
this.__onChange = fnc;
return this;
},
/**
* Specify that a function fire every time someone "finishes" changing
* the value wih this Controller. Useful for values that change
* incrementally like numbers or strings.
*
* @param {Function} fnc This function will be called whenever
* someone "finishes" changing the value via this Controller.
* @returns {dat.controllers.Controller} this
*/
onFinishChange: function(fnc) {
this.__onFinishChange = fnc;
return this;
},
/**
* Change the value of <code>object[property]</code>
*
* @param {Object} newValue The new value of <code>object[property]</code>
*/
setValue: function(newValue) {
this.object[this.property] = newValue;
if (this.__onChange) {
this.__onChange.call(this, newValue);
}
this.updateDisplay();
return this;
},
/**
* Gets the value of <code>object[property]</code>
*
* @returns {Object} The current value of <code>object[property]</code>
*/
getValue: function() {
return this.object[this.property];
},
/**
* Refreshes the visual display of a Controller in order to keep sync
* with the object's current value.
* @returns {dat.controllers.Controller} this
*/
updateDisplay: function() {
return this;
},
/**
* @returns {Boolean} true if the value has deviated from initialValue
*/
isModified: function() {
return this.initialValue !== this.getValue()
}
}
);
return Controller;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/OptionController',
'dat/controllers/NumberControllerBox',
'dat/controllers/NumberControllerSlider',
'dat/controllers/StringController',
'dat/controllers/FunctionController',
'dat/controllers/BooleanController',
'dat/utils/common'
],
function(OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) {
return function(object, property) {
var initialValue = object[property];
// Providing options?
if (common.isArray(arguments[2]) || common.isObject(arguments[2])) {
return new OptionController(object, property, arguments[2]);
}
// Providing a map?
if (common.isNumber(initialValue)) {
if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) {
// Has min and max.
return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
} else {
return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] });
}
}
if (common.isString(initialValue)) {
return new StringController(object, property);
}
if (common.isFunction(initialValue)) {
return new FunctionController(object, property, '');
}
if (common.isBoolean(initialValue)) {
return new BooleanController(object, property);
}
}
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/NumberController',
'dat/dom/dom',
'dat/utils/common'
], function(NumberController, dom, common) {
/**
* @class Represents a given property of an object that is a number and
* provides an input element with which to manipulate it.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerBox = function(object, property, params) {
this.__truncationSuspended = false;
NumberControllerBox.superclass.call(this, object, property, params);
var _this = this;
/**
* {Number} Previous mouse y position
* @ignore
*/
var prev_y;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
// Makes it so manually specified values are not truncated.
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'mousedown', onMouseDown);
dom.bind(this.__input, 'keydown', function(e) {
// When pressing entire, you can be as precise as you want.
if (e.keyCode === 13) {
_this.__truncationSuspended = true;
this.blur();
_this.__truncationSuspended = false;
}
});
function onChange() {
var attempted = parseFloat(_this.__input.value);
if (!common.isNaN(attempted)) _this.setValue(attempted);
}
function onBlur() {
onChange();
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
prev_y = e.clientY;
}
function onMouseDrag(e) {
var diff = prev_y - e.clientY;
_this.setValue(_this.getValue() + diff * _this.__impliedStep);
prev_y = e.clientY;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
NumberControllerBox.superclass = NumberController;
common.extend(
NumberControllerBox.prototype,
NumberController.prototype,
{
updateDisplay: function() {
this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
return NumberControllerBox.superclass.prototype.updateDisplay.call(this);
}
}
);
function roundToDecimal(value, decimals) {
var tenTo = Math.pow(10, decimals);
return Math.round(value * tenTo) / tenTo;
}
return NumberControllerBox;
});
| JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/NumberController',
'dat/dom/dom',
'dat/utils/css',
'dat/utils/common',
'text!dat/controllers/NumberControllerSlider.css'
],
function(NumberController, dom, css, common, styleSheet) {
/**
* @class Represents a given property of an object that is a number, contains
* a minimum and maximum, and provides a slider element with which to
* manipulate it. It should be noted that the slider element is made up of
* <code><div></code> tags, <strong>not</strong> the html5
* <code><slider></code> element.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Number} minValue Minimum allowed value
* @param {Number} maxValue Maximum allowed value
* @param {Number} stepValue Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerSlider = function(object, property, min, max, step) {
NumberControllerSlider.superclass.call(this, object, property, { min: min, max: max, step: step });
var _this = this;
this.__background = document.createElement('div');
this.__foreground = document.createElement('div');
dom.bind(this.__background, 'mousedown', onMouseDown);
dom.addClass(this.__background, 'slider');
dom.addClass(this.__foreground, 'slider-fg');
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
onMouseDrag(e);
}
function onMouseDrag(e) {
e.preventDefault();
var offset = dom.getOffset(_this.__background);
var width = dom.getWidth(_this.__background);
_this.setValue(
map(e.clientX, offset.left, offset.left + width, _this.__min, _this.__max)
);
return false;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.__background.appendChild(this.__foreground);
this.domElement.appendChild(this.__background);
};
NumberControllerSlider.superclass = NumberController;
/**
* Injects default stylesheet for slider elements.
*/
NumberControllerSlider.useDefaultStyles = function() {
css.inject(styleSheet);
};
common.extend(
NumberControllerSlider.prototype,
NumberController.prototype,
{
updateDisplay: function() {
var pct = (this.getValue() - this.__min)/(this.__max - this.__min);
this.__foreground.style.width = pct*100+'%';
return NumberControllerSlider.superclass.prototype.updateDisplay.call(this);
}
}
);
function map(v, i1, i2, o1, o2) {
return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
}
return NumberControllerSlider;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/utils/common'
], function(Controller, common) {
/**
* @class Represents a given property of an object that is a number.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberController = function(object, property, params) {
NumberController.superclass.call(this, object, property);
params = params || {};
this.__min = params.min;
this.__max = params.max;
this.__step = params.step;
if (common.isUndefined(this.__step)) {
if (this.initialValue == 0) {
this.__impliedStep = 1; // What are we, psychics?
} else {
// Hey Doug, check this out.
this.__impliedStep = Math.pow(10, Math.floor(Math.log(this.initialValue)/Math.LN10))/10;
}
} else {
this.__impliedStep = this.__step;
}
this.__precision = numDecimals(this.__impliedStep);
};
NumberController.superclass = Controller;
common.extend(
NumberController.prototype,
Controller.prototype,
/** @lends dat.controllers.NumberController.prototype */
{
setValue: function(v) {
if (this.__min !== undefined && v < this.__min) {
v = this.__min;
} else if (this.__max !== undefined && v > this.__max) {
v = this.__max;
}
if (this.__step !== undefined && v % this.__step != 0) {
v = Math.round(v / this.__step) * this.__step;
}
return NumberController.superclass.prototype.setValue.call(this, v);
},
/**
* Specify a minimum value for <code>object[property]</code>.
*
* @param {Number} minValue The minimum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
min: function(v) {
this.__min = v;
return this;
},
/**
* Specify a maximum value for <code>object[property]</code>.
*
* @param {Number} maxValue The maximum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
max: function(v) {
this.__max = v;
return this;
},
/**
* Specify a step value that dat.controllers.NumberController
* increments by.
*
* @param {Number} stepValue The step value for
* dat.controllers.NumberController
* @default if minimum and maximum specified increment is 1% of the
* difference otherwise stepValue is 1
* @returns {dat.controllers.NumberController} this
*/
step: function(v) {
this.__step = v;
return this;
}
}
);
function numDecimals(x) {
x = x.toString();
if (x.indexOf('.') > -1) {
return x.length - x.indexOf('.') - 1;
} else {
return 0;
}
}
return NumberController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
],
function(Controller, dom, common) {
/**
* @class Provides a select input to alter the property of an object, using a
* list of accepted values.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object|string[]} options A map of labels to acceptable values, or
* a list of acceptable string values.
*
* @member dat.controllers
*/
var OptionController = function(object, property, options) {
OptionController.superclass.call(this, object, property);
var _this = this;
/**
* The drop down menu
* @ignore
*/
this.__select = document.createElement('select');
if (common.isArray(options)) {
var map = {};
common.each(options, function(element) {
map[element] = element;
});
options = map;
}
common.each(options, function(value, key) {
var opt = document.createElement('option');
opt.innerHTML = key;
opt.setAttribute('value', value);
_this.__select.appendChild(opt);
});
// Acknowledge original value
this.updateDisplay();
dom.bind(this.__select, 'change', function() {
var desiredValue = this.options[this.selectedIndex].value;
_this.setValue(desiredValue);
});
this.domElement.appendChild(this.__select);
};
OptionController.superclass = Controller;
common.extend(
OptionController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = OptionController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
return toReturn;
},
updateDisplay: function() {
this.__select.value = this.getValue();
return OptionController.superclass.prototype.updateDisplay.call(this);
}
}
);
return OptionController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
], function(Controller, dom, common) {
/**
* @class Provides a checkbox input to alter the boolean property of an object.
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var BooleanController = function(object, property) {
BooleanController.superclass.call(this, object, property);
var _this = this;
this.__prev = this.getValue();
this.__checkbox = document.createElement('input');
this.__checkbox.setAttribute('type', 'checkbox');
dom.bind(this.__checkbox, 'change', onChange, false);
this.domElement.appendChild(this.__checkbox);
// Match original value
this.updateDisplay();
function onChange() {
_this.setValue(!_this.__prev);
}
};
BooleanController.superclass = Controller;
common.extend(
BooleanController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = BooleanController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.__prev = this.getValue();
return toReturn;
},
updateDisplay: function() {
if (this.getValue() === true) {
this.__checkbox.setAttribute('checked', 'checked');
this.__checkbox.checked = true;
} else {
this.__checkbox.checked = false;
}
return BooleanController.superclass.prototype.updateDisplay.call(this);
}
}
);
return BooleanController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
], function(Controller, dom, common) {
/**
* @class Provides a text input to alter the string property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var StringController = function(object, property) {
StringController.superclass.call(this, object, property);
var _this = this;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
dom.bind(this.__input, 'keyup', onChange);
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) {
this.blur();
}
});
function onChange() {
_this.setValue(_this.__input.value);
}
function onBlur() {
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
StringController.superclass = Controller;
common.extend(
StringController.prototype,
Controller.prototype,
{
updateDisplay: function() {
// Stops the caret from moving on account of:
// keyup -> setValue -> updateDisplay
if (!dom.isActive(this.__input)) {
this.__input.value = this.getValue();
}
return StringController.superclass.prototype.updateDisplay.call(this);
}
}
);
return StringController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/utils/common'
], function(Controller, dom, common) {
/**
* @class Provides a GUI interface to fire a specified method, a property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var FunctionController = function(object, property, text) {
FunctionController.superclass.call(this, object, property);
var _this = this;
this.__button = document.createElement('div');
this.__button.innerHTML = text === undefined ? 'Fire' : text;
dom.bind(this.__button, 'click', function(e) {
e.preventDefault();
_this.fire();
return false;
});
dom.addClass(this.__button, 'button');
this.domElement.appendChild(this.__button);
};
FunctionController.superclass = Controller;
common.extend(
FunctionController.prototype,
Controller.prototype,
{
fire: function() {
if (this.__onChange) {
this.__onChange.call(this);
}
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.getValue().call(this.object);
}
}
);
return FunctionController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/controllers/Controller',
'dat/dom/dom',
'dat/color/Color',
'dat/color/interpret',
'dat/utils/common'
], function(Controller, dom, Color, interpret, common) {
var ColorController = function(object, property) {
ColorController.superclass.call(this, object, property);
this.__color = new Color(this.getValue());
this.__temp = new Color(0);
var _this = this;
this.domElement = document.createElement('div');
dom.makeSelectable(this.domElement, false);
this.__selector = document.createElement('div');
this.__selector.className = 'selector';
this.__saturation_field = document.createElement('div');
this.__saturation_field.className = 'saturation-field';
this.__field_knob = document.createElement('div');
this.__field_knob.className = 'field-knob';
this.__field_knob_border = '2px solid ';
this.__hue_knob = document.createElement('div');
this.__hue_knob.className = 'hue-knob';
this.__hue_field = document.createElement('div');
this.__hue_field.className = 'hue-field';
this.__input = document.createElement('input');
this.__input.type = 'text';
this.__input_textShadow = '0 1px 1px ';
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) { // on enter
onBlur.call(this);
}
});
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__selector, 'mousedown', function(e) {
dom
.addClass(this, 'drag')
.bind(window, 'mouseup', function(e) {
dom.removeClass(_this.__selector, 'drag');
});
});
var value_field = document.createElement('div');
common.extend(this.__selector.style, {
width: '122px',
height: '102px',
padding: '3px',
backgroundColor: '#222',
boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
});
common.extend(this.__field_knob.style, {
position: 'absolute',
width: '12px',
height: '12px',
border: this.__field_knob_border + (this.__color.v < .5 ? '#fff' : '#000'),
boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
borderRadius: '12px',
zIndex: 1
});
common.extend(this.__hue_knob.style, {
position: 'absolute',
width: '15px',
height: '2px',
borderRight: '4px solid #fff',
zIndex: 1
});
common.extend(this.__saturation_field.style, {
width: '100px',
height: '100px',
border: '1px solid #555',
marginRight: '3px',
display: 'inline-block',
cursor: 'pointer'
});
common.extend(value_field.style, {
width: '100%',
height: '100%',
background: 'none'
});
linearGradient(value_field, 'top', 'rgba(0,0,0,0)', '#000');
common.extend(this.__hue_field.style, {
width: '15px',
height: '100px',
display: 'inline-block',
border: '1px solid #555',
cursor: 'ns-resize'
});
hueGradient(this.__hue_field);
common.extend(this.__input.style, {
outline: 'none',
// width: '120px',
textAlign: 'center',
// padding: '4px',
// marginBottom: '6px',
color: '#fff',
border: 0,
fontWeight: 'bold',
textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)'
});
dom.bind(this.__saturation_field, 'mousedown', fieldDown);
dom.bind(this.__field_knob, 'mousedown', fieldDown);
dom.bind(this.__hue_field, 'mousedown', function(e) {
setH(e);
dom.bind(window, 'mousemove', setH);
dom.bind(window, 'mouseup', unbindH);
});
function fieldDown(e) {
setSV(e);
// document.body.style.cursor = 'none';
dom.bind(window, 'mousemove', setSV);
dom.bind(window, 'mouseup', unbindSV);
}
function unbindSV() {
dom.unbind(window, 'mousemove', setSV);
dom.unbind(window, 'mouseup', unbindSV);
// document.body.style.cursor = 'default';
}
function onBlur() {
var i = interpret(this.value);
if (i !== false) {
_this.__color.__state = i;
_this.setValue(_this.__color.toOriginal());
} else {
this.value = _this.__color.toString();
}
}
function unbindH() {
dom.unbind(window, 'mousemove', setH);
dom.unbind(window, 'mouseup', unbindH);
}
this.__saturation_field.appendChild(value_field);
this.__selector.appendChild(this.__field_knob);
this.__selector.appendChild(this.__saturation_field);
this.__selector.appendChild(this.__hue_field);
this.__hue_field.appendChild(this.__hue_knob);
this.domElement.appendChild(this.__input);
this.domElement.appendChild(this.__selector);
this.updateDisplay();
function setSV(e) {
e.preventDefault();
var w = dom.getWidth(_this.__saturation_field);
var o = dom.getOffset(_this.__saturation_field);
var s = (e.clientX - o.left + document.body.scrollLeft) / w;
var v = 1 - (e.clientY - o.top + document.body.scrollTop) / w;
if (v > 1) v = 1;
else if (v < 0) v = 0;
if (s > 1) s = 1;
else if (s < 0) s = 0;
_this.__color.v = v;
_this.__color.s = s;
_this.setValue(_this.__color.toOriginal());
return false;
}
function setH(e) {
e.preventDefault();
var s = dom.getHeight(_this.__hue_field);
var o = dom.getOffset(_this.__hue_field);
var h = 1 - (e.clientY - o.top + document.body.scrollTop) / s;
if (h > 1) h = 1;
else if (h < 0) h = 0;
_this.__color.h = h * 360;
_this.setValue(_this.__color.toOriginal());
return false;
}
};
ColorController.superclass = Controller;
common.extend(
ColorController.prototype,
Controller.prototype,
{
updateDisplay: function() {
var i = interpret(this.getValue());
if (i !== false) {
var mismatch = false;
// Check for mismatch on the interpreted value.
common.each(Color.COMPONENTS, function(component) {
if (!common.isUndefined(i[component]) &&
!common.isUndefined(this.__color.__state[component]) &&
i[component] !== this.__color.__state[component]) {
mismatch = true;
return {}; // break
}
}, this);
// If nothing diverges, we keep our previous values
// for statefulness, otherwise we recalculate fresh
if (mismatch) {
common.extend(this.__color.__state, i);
}
}
common.extend(this.__temp.__state, this.__color.__state);
this.__temp.a = 1;
var flip = (this.__color.v < .5 || this.__color.s > .5) ? 255 : 0;
var _flip = 255 - flip;
common.extend(this.__field_knob.style, {
marginLeft: 100 * this.__color.s - 7 + 'px',
marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
backgroundColor: this.__temp.toString(),
border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip +')'
});
this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px'
this.__temp.s = 1;
this.__temp.v = 1;
linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString());
common.extend(this.__input.style, {
backgroundColor: this.__input.value = this.__color.toString(),
color: 'rgb(' + flip + ',' + flip + ',' + flip +')',
textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip +',.7)'
});
}
}
);
var vendors = ['-moz-','-o-','-webkit-','-ms-',''];
function linearGradient(elem, x, a, b) {
elem.style.background = '';
common.each(vendors, function(vendor) {
elem.style.cssText += 'background: ' + vendor + 'linear-gradient('+x+', '+a+' 0%, ' + b + ' 100%); ';
});
}
function hueGradient(elem) {
elem.style.background = '';
elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);'
elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
}
return ColorController;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/dom/dom',
'dat/utils/common'
], function(dom, common) {
var CenteredDiv = function() {
this.backgroundElement = document.createElement('div');
common.extend(this.backgroundElement.style, {
backgroundColor: 'rgba(0,0,0,0.8)',
top: 0,
left: 0,
display: 'none',
zIndex: '1000',
opacity: 0,
WebkitTransition: 'opacity 0.2s linear'
});
dom.makeFullscreen(this.backgroundElement);
this.backgroundElement.style.position = 'fixed';
this.domElement = document.createElement('div');
common.extend(this.domElement.style, {
position: 'fixed',
display: 'none',
zIndex: '1001',
opacity: 0,
WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear'
});
document.body.appendChild(this.backgroundElement);
document.body.appendChild(this.domElement);
var _this = this;
dom.bind(this.backgroundElement, 'click', function() {
_this.hide();
});
};
CenteredDiv.prototype.show = function() {
var _this = this;
this.backgroundElement.style.display = 'block';
this.domElement.style.display = 'block';
this.domElement.style.opacity = 0;
// this.domElement.style.top = '52%';
this.domElement.style.webkitTransform = 'scale(1.1)';
this.layout();
common.defer(function() {
_this.backgroundElement.style.opacity = 1;
_this.domElement.style.opacity = 1;
_this.domElement.style.webkitTransform = 'scale(1)';
});
};
CenteredDiv.prototype.hide = function() {
var _this = this;
var hide = function() {
_this.domElement.style.display = 'none';
_this.backgroundElement.style.display = 'none';
dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
dom.unbind(_this.domElement, 'transitionend', hide);
dom.unbind(_this.domElement, 'oTransitionEnd', hide);
};
dom.bind(this.domElement, 'webkitTransitionEnd', hide);
dom.bind(this.domElement, 'transitionend', hide);
dom.bind(this.domElement, 'oTransitionEnd', hide);
this.backgroundElement.style.opacity = 0;
// this.domElement.style.top = '48%';
this.domElement.style.opacity = 0;
this.domElement.style.webkitTransform = 'scale(1.1)';
};
CenteredDiv.prototype.layout = function() {
this.domElement.style.left = window.innerWidth/2 - dom.getWidth(this.domElement) / 2 + 'px';
this.domElement.style.top = window.innerHeight/2 - dom.getHeight(this.domElement) / 2 + 'px';
};
function lockScroll(e) {
console.log(e);
}
return CenteredDiv;
}); | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
define([
'dat/utils/common'
], function(common) {
var EVENT_MAP = {
'HTMLEvents': ['change'],
'MouseEvents': ['click','mousemove','mousedown','mouseup', 'mouseover'],
'KeyboardEvents': ['keydown']
};
var EVENT_MAP_INV = {};
common.each(EVENT_MAP, function(v, k) {
common.each(v, function(e) {
EVENT_MAP_INV[e] = k;
});
});
var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
function cssValueToPixels(val) {
if (val === '0' || common.isUndefined(val)) return 0;
var match = val.match(CSS_VALUE_PIXELS);
if (!common.isNull(match)) {
return parseFloat(match[1]);
}
// TODO ...ems? %?
return 0;
}
/**
* @namespace
* @member dat.dom
*/
var dom = {
/**
*
* @param elem
* @param selectable
*/
makeSelectable: function(elem, selectable) {
if (elem === undefined || elem.style === undefined) return;
elem.onselectstart = selectable ? function() {
return false;
} : function() {
};
elem.style.MozUserSelect = selectable ? 'auto' : 'none';
elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
elem.unselectable = selectable ? 'on' : 'off';
},
/**
*
* @param elem
* @param horizontal
* @param vertical
*/
makeFullscreen: function(elem, horizontal, vertical) {
if (common.isUndefined(horizontal)) horizontal = true;
if (common.isUndefined(vertical)) vertical = true;
elem.style.position = 'absolute';
if (horizontal) {
elem.style.left = 0;
elem.style.right = 0;
}
if (vertical) {
elem.style.top = 0;
elem.style.bottom = 0;
}
},
/**
*
* @param elem
* @param eventType
* @param params
*/
fakeEvent: function(elem, eventType, params, aux) {
params = params || {};
var className = EVENT_MAP_INV[eventType];
if (!className) {
throw new Error('Event type ' + eventType + ' not supported.');
}
var evt = document.createEvent(className);
switch (className) {
case 'MouseEvents':
var clientX = params.x || params.clientX || 0;
var clientY = params.y || params.clientY || 0;
evt.initMouseEvent(eventType, params.bubbles || false,
params.cancelable || true, window, params.clickCount || 1,
0, //screen X
0, //screen Y
clientX, //client X
clientY, //client Y
false, false, false, false, 0, null);
break;
case 'KeyboardEvents':
var init = evt.initKeyboardEvent || evt.initKeyEvent; // webkit || moz
common.defaults(params, {
cancelable: true,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: undefined,
charCode: undefined
});
init(eventType, params.bubbles || false,
params.cancelable, window,
params.ctrlKey, params.altKey,
params.shiftKey, params.metaKey,
params.keyCode, params.charCode);
break;
default:
evt.initEvent(eventType, params.bubbles || false,
params.cancelable || true);
break;
}
common.defaults(evt, aux);
elem.dispatchEvent(evt);
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
bind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.addEventListener)
elem.addEventListener(event, func, bool);
else if (elem.attachEvent)
elem.attachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
unbind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.removeEventListener)
elem.removeEventListener(event, func, bool);
else if (elem.detachEvent)
elem.detachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param className
*/
addClass: function(elem, className) {
if (elem.className === undefined) {
elem.className = className;
} else if (elem.className !== className) {
var classes = elem.className.split(/ +/);
if (classes.indexOf(className) == -1) {
classes.push(className);
elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
}
}
return dom;
},
/**
*
* @param elem
* @param className
*/
removeClass: function(elem, className) {
if (className) {
if (elem.className === undefined) {
// elem.className = className;
} else if (elem.className === className) {
elem.removeAttribute('class');
} else {
var classes = elem.className.split(/ +/);
var index = classes.indexOf(className);
if (index != -1) {
classes.splice(index, 1);
elem.className = classes.join(' ');
}
}
} else {
elem.className = undefined;
}
return dom;
},
hasClass: function(elem, className) {
return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
},
/**
*
* @param elem
*/
getWidth: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-left-width']) +
cssValueToPixels(style['border-right-width']) +
cssValueToPixels(style['padding-left']) +
cssValueToPixels(style['padding-right']) +
cssValueToPixels(style['width']);
},
/**
*
* @param elem
*/
getHeight: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-top-width']) +
cssValueToPixels(style['border-bottom-width']) +
cssValueToPixels(style['padding-top']) +
cssValueToPixels(style['padding-bottom']) +
cssValueToPixels(style['height']);
},
/**
*
* @param elem
*/
getOffset: function(elem) {
var offset = {left: 0, top:0};
if (elem.offsetParent) {
do {
offset.left += elem.offsetLeft;
offset.top += elem.offsetTop;
} while (elem = elem.offsetParent);
}
return offset;
},
// http://stackoverflow.com/posts/2684561/revisions
/**
*
* @param elem
*/
isActive: function(elem) {
return elem === document.activeElement && ( elem.type || elem.href );
}
};
return dom;
}); | JavaScript |
require('./builder.js').build({
"baseUrl": "../src/",
"main": "dat/color/Color",
"out": "../build/dat.color.js",
"minify": false,
"shortcut": "dat.Color",
"paths": {}
}); | JavaScript |
/// # Google Closure Compiler Service #
/// https://github.com/weaver/scribbles/blob/master/node/google-closure/lib/closure.js
/// Compress javascript with Node.js using the Closure Compiler
/// Service.
var sys = require('sys');
exports.compile = compile;
// Use the Google Closure Compiler Service to compress Javascript
// code.
//
// + code - String of javascript to compress
// + next - Function callback that accepts.
//
// This method will POST the `code` to the compiler service. If an
// error occurs, `next()` will be called with an `Error` object as the
// first argument. Otherwise, the `next()` will be called with `null`
// as the first argument and a String of compressed javascript as the
// second argument.
//
// compile('... javascript ...', function(err, result) {
// if (err) throw err;
//
// ... do something with result ...
// });
//
// Returns nothing.
function compile(code, next) {
try {
var qs = require('querystring'),
http = require('http'),
host = 'closure-compiler.appspot.com',
body = qs.stringify({
js_code: code.toString('utf-8'),
compilation_level: 'SIMPLE_OPTIMIZATIONS',
output_format: 'json',
output_info: 'compiled_code'
}),
client = http.createClient(80, host).on('error', next),
req = client.request('POST', '/compile', {
'Host': host,
'Content-Length': body.length,
'Content-Type': 'application/x-www-form-urlencoded'
});
req.on('error', next).end(body);
req.on('response', function(res) {
if (res.statusCode != 200)
next(new Error('Unexpected HTTP response: ' + res.statusCode));
else
capture(res, 'utf-8', parseResponse);
});
function parseResponse(err, data) {
err ? next(err) : loadJSON(data, function(err, obj) {
var error;
if (err)
next(err);
else if ((error = obj.errors || obj.serverErrors || obj.warnings))
next(new Error('Failed to compile: ' + sys.inspect(error)));
else
next(null, obj.compiledCode);
});
}
} catch (err) {
next(err);
}
}
// Convert a Stream to a String.
//
// + input - Stream object
// + encoding - String input encoding
// + next - Function error/success callback
//
// Returns nothing.
function capture(input, encoding, next) {
var buffer = '';
input.on('data', function(chunk) {
buffer += chunk.toString(encoding);
});
input.on('end', function() {
next(null, buffer);
});
input.on('error', next);
}
// Convert JSON.load() to callback-style.
//
// + data - String value to load
// + next - Function error/success callback
//
// Returns nothing.
function loadJSON(data, next) {
var err, obj;
try {
obj = JSON.parse(data);
} catch (x) {
err = x;
}
next(err, obj);
} | JavaScript |
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* 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
*/
var fs = require('fs'),
closure = require('./closure'),
params,
defined,
third_party,
request_counts,
namespaces,
next_load = '',
next_path = '';
exports.build = build;
exports.file_exists = file_exists;
exports.read_file = read_file;
exports.tab = tab;
exports.license = read_file('license.txt');
function build(_params) {
params = _params;
defined = {};
third_party = {};
request_counts = {};
namespaces = {};
var deps = [];
load_module(params.baseUrl + params.main + '.js', params.main);
for (var i in defined) {
if (params.verbose) console.log('Loaded: ' + defined[i].path);
deps.push(defined[i].path);
if (defined[i].module) {
var namespace = i.substr(0, i.lastIndexOf('/'));
namespaces[namespace] = true;
}
}
var to_write = '';
var ensured = {};
for (var name in params.paths) {
var path = params.baseUrl + params.paths[name] + '.js';
var str = read_file(path);
if (str === false) {
console.log('Failed to locate dependency \'' + name + '\' at ' + path);
fail();
}
third_party[name] = str;
to_write += third_party[name] + "\n\n";
if (params.verbose) console.log('Loaded: ' + path);
//deps.push(path);
}
// Ensure namespaces
for (i in namespaces) {
var split = i.split('/');
for (var j = 0; j < split.length; j++) {
var cur = [];
if (j == 0 && !ensured[split[j]]) {
to_write += '/** @namespace */\n';
to_write += 'var ' + split[j] + ' = ' + split[j] + ' || {};\n\n';
ensured[split[j]] = true;
} else {
for (var k = 0; k <= j; k++) {
cur.push(split[k]);
}
var curn = cur.join('.');
if (!ensured[curn]) {
to_write += '/** @namespace */\n';
to_write += curn + ' = ' + curn + ' || {};\n\n';
}
ensured[curn] = true;
}
}
}
var shared_count = 0;
for (i in request_counts) {
var count = request_counts[i];
if (count > 1) {
if (i in defined) {
var new_shared = i.replace(/\//g, '.');
var v = new_shared + ' = ' + defined[i].getClosure() + ';\n';
to_write += v + "\n\n";
defined[i].shared = new_shared;
shared_count++;
}
}
}
to_write += params.shortcut + ' = ' + params.main.replace(/\//g, '.') + ' = ' + defined[params.main].getClosure() + ';';
if (params.verbose) console.log('Exported: ' + params.main + ' to window.' + params.shortcut);
if (params.minify) {
console.log('Compiling minified source ...');
closure.compile(to_write, function(error, code) {
if (error) {
console.log(error);
} else {
write(exports.license + code);
}
if (params.on_compile) {
params.on_compile();
}
});
} else {
write(exports.license + "\n" + to_write);
}
return deps;
}
function define(deps, callback) {
this.name = next_load;
this.path = next_path;
this.shared = false;
defined[this.name] = this;
if (Array.isArray(deps)) {
this.deps = deps;
this.callback = callback.toString();
this.module = true;
// Simple define call, just an object
} else if (typeof deps === 'object') {
var props = [];
for (var i in deps) {
props.push(i + ':' + deps[i].toString())
}
this.callback = '{' + props.join(',') + '}';
this.module = true;
} else {
this.deps = deps;
this.callback = callback;
}
this.getClosure = function() {
if (this.shared) return this.shared;
if (!this.deps || this.text) return this.callback;
var arg_string = '(';
var args = [];
for (var i in this.deps) {
var dep = this.deps[i];
if (dep in defined) {
var closure = defined[dep].getClosure();
if (!defined[dep].shared && !defined[dep].text) {
closure = defined[dep].name.replace(/\//g, '.') + ' = ' + closure;
}
args.push(closure);
}
}
arg_string += args.join(',\n');
arg_string += ')';
return '(' + this.callback + ')' + arg_string;
};
this.recurseDeps = function() {
if (!this.deps) return;
for (var i in this.deps) {
var dep = this.deps[i];
if (dep in params.paths) continue;
var path = params.baseUrl + dep;
// Define module?
if (file_exists(path + '.js')) {
load_module(path + '.js', dep);
// Text module?
} else if (path.match(/text!/) != null) {
load_text(path.replace('text!', ''), dep);
}
// up the request count
if (dep in request_counts) {
request_counts[dep]++
} else {
request_counts[dep] = 1;
}
}
};
this.recurseDeps();
}
function file_exists(path) {
try {
var stats = fs.lstatSync(path)
return stats.isFile();
} catch (e) {
return false;
}
}
function read_file(path) {
try {
return fs.readFileSync(path).toString();
} catch (e) {
return false;
}
}
function load_module(path, name) {
name = name || path;
if (name in defined) return;
next_load = name;
next_path = path;
eval('new ' + read_file(path));
}
function load_text(path, name) {
name = name || path;
if (name in defined) return;
var text = read_file(path);
text = text.replace(/\r/g, "\\r");
text = text.replace(/\n/g, "\\n");
text = text.replace(/"/g, "\\\"");
next_load = name;
next_path = path;
var d = new define([], '"' + text + '"');
d.text = true;
d.module = false;
}
function tab(str, tabs) {
var lines = str.split("\n");
for (var i in lines) {
lines[i] = tabs + lines[i];
}
return lines.join("\n");
}
function write(str) {
fs.writeFile(params.out, str);
console.log('Saved to ' + params.out);
}
function fail() {
console.log('Build failed.');
process.exit(0);
} | JavaScript |
require('./builder.js').build({
"baseUrl": "../src/",
"main": "dat/gui/GUI",
"out": "../build/dat.gui.js",
"minify": false,
"shortcut": "dat.GUI",
"paths": {}
}); | JavaScript |
/**
* QUnit 1.2.0pre - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2011 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL (GPL-LICENSE.txt) licenses.
*/
(function(window) {
var defined = {
setTimeout: typeof window.setTimeout !== "undefined",
sessionStorage: (function() {
try {
return !!sessionStorage.getItem;
} catch(e) {
return false;
}
})()
};
var testId = 0,
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
this.name = name;
this.testName = testName;
this.expected = expected;
this.testEnvironmentArg = testEnvironmentArg;
this.async = async;
this.callback = callback;
this.assertions = [];
};
Test.prototype = {
init: function() {
var tests = id("qunit-tests");
if (tests) {
var b = document.createElement("strong");
b.innerHTML = "Running " + this.name;
var li = document.createElement("li");
li.appendChild( b );
li.className = "running";
li.id = this.id = "test-output" + testId++;
tests.appendChild( li );
}
},
setup: function() {
if (this.module != config.previousModule) {
if ( config.previousModule ) {
runLoggingCallbacks('moduleDone', QUnit, {
name: config.previousModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
config.previousModule = this.module;
config.moduleStats = { all: 0, bad: 0 };
runLoggingCallbacks( 'moduleStart', QUnit, {
name: this.module
} );
}
config.current = this;
this.testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, this.moduleTestEnvironment);
if (this.testEnvironmentArg) {
extend(this.testEnvironment, this.testEnvironmentArg);
}
runLoggingCallbacks( 'testStart', QUnit, {
name: this.testName,
module: this.module
});
// allow utility functions to access the current test environment
// TODO why??
QUnit.current_testEnvironment = this.testEnvironment;
try {
if ( !config.pollution ) {
saveGlobal();
}
this.testEnvironment.setup.call(this.testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
}
},
run: function() {
config.current = this;
if ( this.async ) {
QUnit.stop();
}
if ( config.notrycatch ) {
this.callback.call(this.testEnvironment);
return;
}
try {
this.callback.call(this.testEnvironment);
} catch(e) {
fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
QUnit.start();
}
}
},
teardown: function() {
config.current = this;
try {
this.testEnvironment.teardown.call(this.testEnvironment);
checkPollution();
} catch(e) {
QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
}
},
finish: function() {
config.current = this;
if ( this.expected != null && this.expected != this.assertions.length ) {
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
for ( var i = 0; i < this.assertions.length; i++ ) {
var assertion = this.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
// store result when possible
if ( QUnit.config.reorder && defined.sessionStorage ) {
if (bad) {
sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
} else {
sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
}
}
if (bad == 0) {
ol.style.display = "none";
}
var b = document.createElement("strong");
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
var a = document.createElement("a");
a.innerHTML = "Rerun";
a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
addEvent(b, "click", function() {
var next = b.nextSibling.nextSibling,
display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = e && e.target ? e.target : window.event.srcElement;
if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
target = target.parentNode;
}
if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
}
});
var li = id(this.id);
li.className = bad ? "fail" : "pass";
li.removeChild( li.firstChild );
li.appendChild( b );
li.appendChild( a );
li.appendChild( ol );
} else {
for ( var i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
try {
QUnit.reset();
} catch(e) {
fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
}
runLoggingCallbacks( 'testDone', QUnit, {
name: this.testName,
module: this.module,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length
} );
},
queue: function() {
var test = this;
synchronize(function() {
test.init();
});
function run() {
// each of these can by async
synchronize(function() {
test.setup();
});
synchronize(function() {
test.run();
});
synchronize(function() {
test.teardown();
});
synchronize(function() {
test.finish();
});
}
// defer when previous test run passed, if storage is available
var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
if (bad) {
run();
} else {
synchronize(run, true);
};
}
};
var QUnit = {
// call on start of module test to prepend name to all tests
module: function(name, testEnvironment) {
config.currentModule = name;
config.currentModuleTestEnviroment = testEnvironment;
},
asyncTest: function(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
QUnit.test(testName, expected, callback, true);
},
test: function(testName, expected, callback, async) {
var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg;
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
// is 2nd argument a testEnvironment?
if ( expected && typeof expected === 'object') {
testEnvironmentArg = expected;
expected = null;
}
if ( config.currentModule ) {
name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
}
if ( !validTest(config.currentModule + ": " + testName) ) {
return;
}
var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
test.module = config.currentModule;
test.moduleTestEnvironment = config.currentModuleTestEnviroment;
test.queue();
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function(asserts) {
config.current.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function(a, msg) {
a = !!a;
var details = {
result: a,
message: msg
};
msg = escapeInnerText(msg);
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equal: function(actual, expected, message) {
QUnit.push(expected == actual, actual, expected, message);
},
notEqual: function(actual, expected, message) {
QUnit.push(expected != actual, actual, expected, message);
},
deepEqual: function(actual, expected, message) {
QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
},
notDeepEqual: function(actual, expected, message) {
QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
},
strictEqual: function(actual, expected, message) {
QUnit.push(expected === actual, actual, expected, message);
},
notStrictEqual: function(actual, expected, message) {
QUnit.push(expected !== actual, actual, expected, message);
},
raises: function(block, expected, message) {
var actual, ok = false;
if (typeof expected === 'string') {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
if (actual) {
// we don't want to validate thrown error
if (!expected) {
ok = true;
// expected is a regexp
} else if (QUnit.objectType(expected) === "regexp") {
ok = expected.test(actual);
// expected is a constructor
} else if (actual instanceof expected) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if (expected.call({}, actual) === true) {
ok = true;
}
}
QUnit.ok(ok, message);
},
start: function(count) {
config.semaphore -= count || 1;
if (config.semaphore > 0) {
// don't start until equal number of stop-calls
return;
}
if (config.semaphore < 0) {
// ignore if start is called more often then stop
config.semaphore = 0;
}
// A slight delay, to avoid any current callbacks
if ( defined.setTimeout ) {
window.setTimeout(function() {
if (config.semaphore > 0) {
return;
}
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process(true);
}, 13);
} else {
config.blocking = false;
process(true);
}
},
stop: function(count) {
config.semaphore += count || 1;
config.blocking = true;
if ( config.testTimeout && defined.setTimeout ) {
clearTimeout(config.timeout);
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
config.semaphore = 1;
QUnit.start();
}, config.testTimeout);
}
}
};
//We want access to the constructor's prototype
(function() {
function F(){};
F.prototype = QUnit;
QUnit = new F();
//Make F QUnit's constructor so that we can add to the prototype later
QUnit.constructor = F;
})();
// Backwards compatibility, deprecated
QUnit.equals = QUnit.equal;
QUnit.same = QUnit.deepEqual;
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true,
// when enabled, show only failing tests
// gets persisted through sessionStorage and can be changed in UI via checkbox
hidepassed: false,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
urlConfig: ['noglobals', 'notrycatch'],
//logging callback queues
begin: [],
done: [],
log: [],
testStart: [],
testDone: [],
moduleStart: [],
moduleDone: []
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
params = location.search.slice( 1 ).split( "&" ),
length = params.length,
urlParams = {},
current;
if ( params[ 0 ] ) {
for ( var i = 0; i < length; i++ ) {
current = params[ i ].split( "=" );
current[ 0 ] = decodeURIComponent( current[ 0 ] );
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
urlParams[ current[ 0 ] ] = current[ 1 ];
}
}
QUnit.urlParams = urlParams;
config.filter = urlParams.filter;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
}
// define these after exposing globals to keep them in these QUnit namespace only
extend(QUnit, {
config: config,
// Initialize the configuration options
init: function() {
extend(config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
filter: "",
queue: [],
semaphore: 0
});
var tests = id( "qunit-tests" ),
banner = id( "qunit-banner" ),
result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = 'Running...<br/> ';
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*
* If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
*/
reset: function() {
if ( window.jQuery ) {
jQuery( "#qunit-fixture" ).html( config.fixture );
} else {
var main = id( 'qunit-fixture' );
if ( main ) {
main.innerHTML = config.fixture;
}
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Safe object type checking
is: function( type, obj ) {
return QUnit.objectType( obj ) == type;
},
objectType: function( obj ) {
if (typeof obj === "undefined") {
return "undefined";
// consider: typeof null === object
}
if (obj === null) {
return "null";
}
var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
switch (type) {
case 'Number':
if (isNaN(obj)) {
return "nan";
} else {
return "number";
}
case 'String':
case 'Boolean':
case 'Array':
case 'Date':
case 'RegExp':
case 'Function':
return type.toLowerCase();
}
if (typeof obj === "object") {
return "object";
}
return undefined;
},
push: function(result, actual, expected, message) {
var details = {
result: result,
message: message,
actual: actual,
expected: expected
};
message = escapeInnerText(message) || (result ? "okay" : "failed");
message = '<span class="test-message">' + message + "</span>";
expected = escapeInnerText(QUnit.jsDump.parse(expected));
actual = escapeInnerText(QUnit.jsDump.parse(actual));
var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
if (actual != expected) {
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
}
if (!result) {
var source = sourceFromStacktrace();
if (source) {
details.source = source;
output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>';
}
}
output += "</table>";
runLoggingCallbacks( 'log', QUnit, details );
config.current.assertions.push({
result: !!result,
message: output
});
},
url: function( params ) {
params = extend( extend( {}, QUnit.urlParams ), params );
var querystring = "?",
key;
for ( key in params ) {
if ( !hasOwn.call( params, key ) ) {
continue;
}
querystring += encodeURIComponent( key ) + "=" +
encodeURIComponent( params[ key ] ) + "&";
}
return window.location.pathname + querystring.slice( 0, -1 );
},
extend: extend,
id: id,
addEvent: addEvent
});
//QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
//Doing this allows us to tell if the following methods have been overwritten on the actual
//QUnit object, which is a deprecated way of using the callbacks.
extend(QUnit.constructor.prototype, {
// Logging callbacks; all receive a single argument with the listed properties
// run test/logs.html for any related changes
begin: registerLoggingCallback('begin'),
// done: { failed, passed, total, runtime }
done: registerLoggingCallback('done'),
// log: { result, actual, expected, message }
log: registerLoggingCallback('log'),
// testStart: { name }
testStart: registerLoggingCallback('testStart'),
// testDone: { name, failed, passed, total }
testDone: registerLoggingCallback('testDone'),
// moduleStart: { name }
moduleStart: registerLoggingCallback('moduleStart'),
// moduleDone: { name, failed, passed, total }
moduleDone: registerLoggingCallback('moduleDone')
});
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
QUnit.load = function() {
runLoggingCallbacks( 'begin', QUnit, {} );
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var urlConfigHtml = '', len = config.urlConfig.length;
for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
config[val] = QUnit.urlParams[val];
urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>';
}
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var banner = id("qunit-header");
if ( banner ) {
banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml;
addEvent( banner, "change", function( event ) {
var params = {};
params[ event.target.name ] = event.target.checked ? true : undefined;
window.location = QUnit.url( params );
});
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
addEvent( filter, "click", function() {
var ol = document.getElementById("qunit-tests");
if ( filter.checked ) {
ol.className = ol.className + " hidepass";
} else {
var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
ol.className = tmp.replace(/ hidepass /, " ");
}
if ( defined.sessionStorage ) {
if (filter.checked) {
sessionStorage.setItem("qunit-filter-passed-tests", "true");
} else {
sessionStorage.removeItem("qunit-filter-passed-tests");
}
}
});
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
filter.checked = true;
var ol = document.getElementById("qunit-tests");
ol.className = ol.className + " hidepass";
}
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "qunit-filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
}
var main = id('qunit-fixture');
if ( main ) {
config.fixture = main.innerHTML;
}
if (config.autostart) {
QUnit.start();
}
};
addEvent(window, "load", QUnit.load);
// addEvent(window, "error") gives us a useless event object
window.onerror = function( message, file, line ) {
if ( QUnit.config.current ) {
ok( false, message + ", " + file + ":" + line );
} else {
test( "global failure", function() {
ok( false, message + ", " + file + ":" + line );
});
}
};
function done() {
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
runLoggingCallbacks( 'moduleDone', QUnit, {
name: config.currentModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
} );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
runtime = +new Date - config.started,
passed = config.stats.all - config.stats.bad,
html = [
'Tests completed in ',
runtime,
' milliseconds.<br/>',
'<span class="passed">',
passed,
'</span> tests of <span class="total">',
config.stats.all,
'</span> passed, <span class="failed">',
config.stats.bad,
'</span> failed.'
].join('');
if ( banner ) {
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
}
if ( tests ) {
id( "qunit-testresult" ).innerHTML = html;
}
if ( config.altertitle && typeof document !== "undefined" && document.title ) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
(config.stats.bad ? "\u2716" : "\u2714"),
document.title.replace(/^[\u2714\u2716] /i, "")
].join(" ");
}
runLoggingCallbacks( 'done', QUnit, {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
} );
}
function validTest( name ) {
var filter = config.filter,
run = false;
if ( !filter ) {
return true;
}
var not = filter.charAt( 0 ) === "!";
if ( not ) {
filter = filter.slice( 1 );
}
if ( name.indexOf( filter ) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
return run;
}
// so far supports only Firefox, Chrome and Opera (buggy)
// could be extended in the future to use something like https://github.com/csnover/TraceKit
function sourceFromStacktrace() {
try {
throw new Error();
} catch ( e ) {
if (e.stacktrace) {
// Opera
return e.stacktrace.split("\n")[6];
} else if (e.stack) {
// Firefox, Chrome
return e.stack.split("\n")[4];
} else if (e.sourceURL) {
// Safari, PhantomJS
// TODO sourceURL points at the 'throw new Error' line above, useless
//return e.sourceURL + ":" + e.line;
}
}
}
function escapeInnerText(s) {
if (!s) {
return "";
}
s = s + "";
return s.replace(/[\&<>]/g, function(s) {
switch(s) {
case "&": return "&";
case "<": return "<";
case ">": return ">";
default: return s;
}
});
}
function synchronize( callback, last ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process(last);
}
}
function process( last ) {
var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()();
} else {
window.setTimeout( function(){
process( last );
}, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
if ( !hasOwn.call( window, key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
}
var deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
if ( b[prop] === undefined ) {
delete a[prop];
// Avoid "Member not found" error in IE8 caused by setting window.constructor
} else if ( prop !== "constructor" || a !== window ) {
a[prop] = b[prop];
}
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
function registerLoggingCallback(key){
return function(callback){
config[key].push( callback );
};
}
// Supports deprecated method of completely overwriting logging callbacks
function runLoggingCallbacks(key, scope, args) {
//debugger;
var callbacks;
if ( QUnit.hasOwnProperty(key) ) {
QUnit[key].call(scope, args);
} else {
callbacks = config[key];
for( var i = 0; i < callbacks.length; i++ ) {
callbacks[i].call( scope, args );
}
}
}
// Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
var parents = []; // stack to avoiding loops from circular referencing
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = QUnit.objectType(o);
if (prop) {
if (QUnit.objectType(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a
// declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string" : useStrictEquality,
"boolean" : useStrictEquality,
"number" : useStrictEquality,
"null" : useStrictEquality,
"undefined" : useStrictEquality,
"nan" : function(b) {
return isNaN(b);
},
"date" : function(b, a) {
return QUnit.objectType(b) === "date"
&& a.valueOf() === b.valueOf();
},
"regexp" : function(b, a) {
return QUnit.objectType(b) === "regexp"
&& a.source === b.source && // the regex itself
a.global === b.global && // and its modifers
// (gmi) ...
a.ignoreCase === b.ignoreCase
&& a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function" : function() {
var caller = callers[callers.length - 1];
return caller !== Object && typeof caller !== "undefined";
},
"array" : function(b, a) {
var i, j, loop;
var len;
// b could be an object literal here
if (!(QUnit.objectType(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
// track reference to avoid circular references
parents.push(a);
for (i = 0; i < len; i++) {
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i]) {
loop = true;// dont rewalk array
}
}
if (!loop && !innerEquiv(a[i], b[i])) {
parents.pop();
return false;
}
}
parents.pop();
return true;
},
"object" : function(b, a) {
var i, j, loop;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of
// strings
// comparing constructors is more strict than using
// instanceof
if (a.constructor !== b.constructor) {
return false;
}
// stack constructor before traversing properties
callers.push(a.constructor);
// track reference to avoid circular references
parents.push(a);
for (i in a) { // be strict: don't ensures hasOwnProperty
// and go deep
loop = false;
for (j = 0; j < parents.length; j++) {
if (parents[j] === a[i])
loop = true; // don't go down the same path
// twice
}
aProperties.push(i); // collect a's properties
if (!loop && !innerEquiv(a[i], b[i])) {
eq = false;
break;
}
}
callers.pop(); // unstack, we are done
parents.pop();
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq
&& innerEquiv(aProperties.sort(), bProperties
.sort());
}
};
}();
innerEquiv = function() { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function(a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined"
|| typeof b === "undefined"
|| QUnit.objectType(a) !== QUnit.objectType(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [ b, a ]);
}
// apply transition with (1..n) arguments
})(args[0], args[1])
&& arguments.callee.apply(this, args.splice(1,
args.length - 1));
};
return innerEquiv;
}();
/**
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
* http://flesler.blogspot.com Licensed under BSD
* (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
*
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr, stack ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] , undefined , stack);
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
stack = stack || [ ];
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
var inStack = inArray(obj, stack);
if (inStack != -1) {
return 'recursion('+(inStack - stack.length)+')';
}
//else
if (type == 'function') {
stack.push(obj);
var res = parser.call( this, obj, stack );
stack.pop();
return res;
}
// else
return (type == 'string') ? parser : this.parsers.error;
},
typeOf:function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (QUnit.is("RegExp", obj)) {
type = "regexp";
} else if (QUnit.is("Date", obj)) {
type = "date";
} else if (QUnit.is("Function", obj)) {
type = "function";
} else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (
// native arrays
toString.call( obj ) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
) {
type = "array";
} else {
type = typeof obj;
}
return type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
'undefined':'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map, stack ) {
var ret = [ ];
QUnit.jsDump.up();
for ( var key in map ) {
var val = map[key];
ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
}
QUnit.jsDump.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = QUnit.jsDump.HTML ? '<' : '<',
close = QUnit.jsDump.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in QUnit.jsDump.DOMAttrs ) {
var val = node[QUnit.jsDump.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
// from Sizzle.js
function getText( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += getText( elem.childNodes );
}
}
return ret;
};
//from jquery.js
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
/*
* Javascript Diff Algorithm
* By John Resig (http://ejohn.org/)
* Modified by Chu Alan "sprite"
*
* Released under the MIT license.
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
*
* Usage: QUnit.diff(expected, actual)
*
* QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
*/
QUnit.diff = (function() {
function diff(o, n) {
var ns = {};
var os = {};
for (var i = 0; i < n.length; i++) {
if (ns[n[i]] == null)
ns[n[i]] = {
rows: [],
o: null
};
ns[n[i]].rows.push(i);
}
for (var i = 0; i < o.length; i++) {
if (os[o[i]] == null)
os[o[i]] = {
rows: [],
n: null
};
os[o[i]].rows.push(i);
}
for (var i in ns) {
if ( !hasOwn.call( ns, i ) ) {
continue;
}
if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
n[ns[i].rows[0]] = {
text: n[ns[i].rows[0]],
row: os[i].rows[0]
};
o[os[i].rows[0]] = {
text: o[os[i].rows[0]],
row: ns[i].rows[0]
};
}
}
for (var i = 0; i < n.length - 1; i++) {
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
n[i + 1] == o[n[i].row + 1]) {
n[i + 1] = {
text: n[i + 1],
row: n[i].row + 1
};
o[n[i].row + 1] = {
text: o[n[i].row + 1],
row: i + 1
};
}
}
for (var i = n.length - 1; i > 0; i--) {
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
n[i - 1] == o[n[i].row - 1]) {
n[i - 1] = {
text: n[i - 1],
row: n[i].row - 1
};
o[n[i].row - 1] = {
text: o[n[i].row - 1],
row: i - 1
};
}
}
return {
o: o,
n: n
};
}
return function(o, n) {
o = o.replace(/\s+$/, '');
n = n.replace(/\s+$/, '');
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
var str = "";
var oSpace = o.match(/\s+/g);
if (oSpace == null) {
oSpace = [" "];
}
else {
oSpace.push(" ");
}
var nSpace = n.match(/\s+/g);
if (nSpace == null) {
nSpace = [" "];
}
else {
nSpace.push(" ");
}
if (out.n.length == 0) {
for (var i = 0; i < out.o.length; i++) {
str += '<del>' + out.o[i] + oSpace[i] + "</del>";
}
}
else {
if (out.n[0].text == null) {
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
str += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
}
for (var i = 0; i < out.n.length; i++) {
if (out.n[i].text == null) {
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
}
else {
var pre = "";
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
};
})();
})(this);
| JavaScript |
/*
* autoscroll.js widget with jquery event(s)
* Copyright 2011 Michael Whitford <michael@alwandassociates.com>
* License: BSD
*/
// toggle - id of the toggle element for the click event
// textarea - id of the textarea to autoscroll
var toggleAutoScroll = function (toggle, textarea) {
var autoScrollDebug = false;
var state = toggle + 'interval';
var scrollOn = function() {
if (autoScrollDebug) { console.log('on:', toggle, textarea); }
var onAnimation = function(name, target) {
jQuery('#' + name).unbind().click(function() {
toggleAutoScroll(name, target);
}).fadeTo(350, 1);
};
// uses obj attached to window for state
window[state] = {};
window[state].name = toggle;
window[state].target = textarea;
// get a handle to the textarea el
var area = jQuery('#' + textarea);
// set the interval
window[state].interval = setInterval(function() {
// ui hack? needs more testing
area[0].scrollTop = area[0].scrollHeight;
}, 2500); // 2.5 seconds
onAnimation(toggle, textarea);
};
var scrollOff = function() {
if (autoScrollDebug) { console.log('off:', toggle, textarea); }
var offAnimation = function(name, target) {
jQuery('#' + name).unbind().click(function() {
toggleAutoScroll(name, target);
}).fadeTo(350, 0.55);
};
offAnimation(toggle, textarea);
clearInterval(window[state].interval);
window[state] = undefined;
};
if (arguments.length == 2) {
if (typeof window[state] === 'undefined') {
scrollOn();
} else {
scrollOff();
}
}
return;
};
// jquery onready
jQuery(document).ready(function () {
// turn it on by default
toggleAutoScroll('autoscroll', 'output');
});
// todo: some key - toggle off
// todo: drag scrollbar up - toggle off
// todo: drag scrollbar to bottom - toggle off
| JavaScript |
/*! Javascript plotting library for jQuery, v. 0.7.
*
* Released under the MIT license by IOLA, December 2007.
*
*/
// first an inline dependency, jquery.colorhelpers.js, we inline it here
// for convenience
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
// the actual Flot code
(function($) {
function Plot(placeholder, data_, options_, plugins) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
var series = [],
options = {
// the color theme used for graphs
colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#ccc", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: 5, // distance from grid edge to default legend container within plot
backgroundColor: null, // null means auto-detect
backgroundOpacity: 0.85 // set to 0 to avoid background
},
xaxis: {
show: null, // null = auto-detect, true = always, false = never
position: "bottom", // or "top"
mode: null, // null or "time"
color: null, // base color, labels, ticks
tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
transform: null, // null or f: number -> number to transform axis
inverseTransform: null, // if transform is set, this should be the inverse function
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
reserveSpace: null, // whether to reserve space even if axis isn't shown
tickLength: null, // size in pixels of ticks, or "full" for whole line
alignTicksWithAxis: null, // axis number or null for no sync
// mode specific options
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null, // number or [number, "unit"]
monthNames: null, // list of names of months
timeformat: null, // format string to use
twelveHourClock: false // 12 or 24 time in time mode
},
yaxis: {
autoscaleMargin: 0.02,
position: "left" // or "right"
},
xaxes: [],
yaxes: [],
series: {
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff",
symbol: "circle" // or callback
},
lines: {
// we don't put in show: false so we can see
// whether lines were actively disabled
lineWidth: 2, // in pixels
fill: false,
fillColor: null,
steps: false
},
bars: {
show: false,
lineWidth: 2, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: null,
align: "left", // or "center"
horizontal: false
},
shadowSize: 3
},
grid: {
show: true,
aboveData: false,
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
borderColor: null, // set if different from the grid color
tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
labelMargin: 5, // in pixels
axisMargin: 8, // in pixels
borderWidth: 2, // in pixels
minBorderMargin: null, // in pixels, null means taken from points radius
markings: null, // array of ranges or fn: axes -> array of ranges
markingsColor: "#f4f4f4",
markingsLineWidth: 2,
// interactive stuff
clickable: false,
hoverable: false,
autoHighlight: true, // highlight in case mouse is near
mouseActiveRadius: 10 // how far the mouse can be away to activate an item
},
hooks: {}
},
canvas = null, // the canvas for the plot itself
overlay = null, // canvas for interactive stuff on top of plot
eventHolder = null, // jQuery object that events should be bound to
ctx = null, octx = null,
xaxes = [], yaxes = [],
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
canvasWidth = 0, canvasHeight = 0,
plotWidth = 0, plotHeight = 0,
hooks = {
processOptions: [],
processRawData: [],
processDatapoints: [],
drawSeries: [],
draw: [],
bindEvents: [],
drawOverlay: [],
shutdown: []
},
plot = this;
// public functions
plot.setData = setData;
plot.setupGrid = setupGrid;
plot.draw = draw;
plot.getPlaceholder = function() { return placeholder; };
plot.getCanvas = function() { return canvas; };
plot.getPlotOffset = function() { return plotOffset; };
plot.width = function () { return plotWidth; };
plot.height = function () { return plotHeight; };
plot.offset = function () {
var o = eventHolder.offset();
o.left += plotOffset.left;
o.top += plotOffset.top;
return o;
};
plot.getData = function () { return series; };
plot.getAxes = function () {
var res = {}, i;
$.each(xaxes.concat(yaxes), function (_, axis) {
if (axis)
res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
});
return res;
};
plot.getXAxes = function () { return xaxes; };
plot.getYAxes = function () { return yaxes; };
plot.c2p = canvasToAxisCoords;
plot.p2c = axisToCanvasCoords;
plot.getOptions = function () { return options; };
plot.highlight = highlight;
plot.unhighlight = unhighlight;
plot.triggerRedrawOverlay = triggerRedrawOverlay;
plot.pointOffset = function(point) {
return {
left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left),
top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top)
};
};
plot.shutdown = shutdown;
plot.resize = function () {
getCanvasDimensions();
resizeCanvas(canvas);
resizeCanvas(overlay);
};
// public attributes
plot.hooks = hooks;
// initialize
initPlugins(plot);
parseOptions(options_);
setupCanvases();
setData(data_);
setupGrid();
draw();
bindEvents();
function executeHooks(hook, args) {
args = [plot].concat(args);
for (var i = 0; i < hook.length; ++i)
hook[i].apply(this, args);
}
function initPlugins() {
for (var i = 0; i < plugins.length; ++i) {
var p = plugins[i];
p.init(plot);
if (p.options)
$.extend(true, options, p.options);
}
}
function parseOptions(opts) {
var i;
$.extend(true, options, opts);
if (options.xaxis.color == null)
options.xaxis.color = options.grid.color;
if (options.yaxis.color == null)
options.yaxis.color = options.grid.color;
if (options.xaxis.tickColor == null) // backwards-compatibility
options.xaxis.tickColor = options.grid.tickColor;
if (options.yaxis.tickColor == null) // backwards-compatibility
options.yaxis.tickColor = options.grid.tickColor;
if (options.grid.borderColor == null)
options.grid.borderColor = options.grid.color;
if (options.grid.tickColor == null)
options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
// fill in defaults in axes, copy at least always the
// first as the rest of the code assumes it'll be there
for (i = 0; i < Math.max(1, options.xaxes.length); ++i)
options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]);
for (i = 0; i < Math.max(1, options.yaxes.length); ++i)
options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]);
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
if (options.x2axis) {
options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
options.xaxes[1].position = "top";
}
if (options.y2axis) {
options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
options.yaxes[1].position = "right";
}
if (options.grid.coloredAreas)
options.grid.markings = options.grid.coloredAreas;
if (options.grid.coloredAreasColor)
options.grid.markingsColor = options.grid.coloredAreasColor;
if (options.lines)
$.extend(true, options.series.lines, options.lines);
if (options.points)
$.extend(true, options.series.points, options.points);
if (options.bars)
$.extend(true, options.series.bars, options.bars);
if (options.shadowSize != null)
options.series.shadowSize = options.shadowSize;
// save options on axes for future reference
for (i = 0; i < options.xaxes.length; ++i)
getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
for (i = 0; i < options.yaxes.length; ++i)
getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
// add hooks from options
for (var n in hooks)
if (options.hooks[n] && options.hooks[n].length)
hooks[n] = hooks[n].concat(options.hooks[n]);
executeHooks(hooks.processOptions, [options]);
}
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s = $.extend(true, {}, options.series);
if (d[i].data != null) {
s.data = d[i].data; // move the data instead of deep-copy
delete d[i].data;
$.extend(true, s, d[i]);
d[i].data = s.data;
}
else
s.data = d[i];
res.push(s);
}
return res;
}
function axisNumber(obj, coord) {
var a = obj[coord + "axis"];
if (typeof a == "object") // if we got a real axis, extract number
a = a.n;
if (typeof a != "number")
a = 1; // default to first axis
return a;
}
function allAxes() {
// return flat array without annoying null entries
return $.grep(xaxes.concat(yaxes), function (a) { return a; });
}
function canvasToAxisCoords(pos) {
// return an object with x/y corresponding to all used axes
var res = {}, i, axis;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used)
res["x" + axis.n] = axis.c2p(pos.left);
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used)
res["y" + axis.n] = axis.c2p(pos.top);
}
if (res.x1 !== undefined)
res.x = res.x1;
if (res.y1 !== undefined)
res.y = res.y1;
return res;
}
function axisToCanvasCoords(pos) {
// get canvas coords from the first pair of x/y found in pos
var res = {}, i, axis, key;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used) {
key = "x" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "x";
if (pos[key] != null) {
res.left = axis.p2c(pos[key]);
break;
}
}
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used) {
key = "y" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "y";
if (pos[key] != null) {
res.top = axis.p2c(pos[key]);
break;
}
}
}
return res;
}
function getOrCreateAxis(axes, number) {
if (!axes[number - 1])
axes[number - 1] = {
n: number, // save the number for future reference
direction: axes == xaxes ? "x" : "y",
options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
};
return axes[number - 1];
}
function fillInSeriesOptions() {
var i;
// collect what we already got of colors
var neededColors = series.length,
usedColors = [],
assignedColors = [];
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
--neededColors;
if (typeof sc == "number")
assignedColors.push(sc);
else
usedColors.push($.color.parse(series[i].color));
}
}
// we might need to generate more colors if higher indices
// are assigned
for (i = 0; i < assignedColors.length; ++i) {
neededColors = Math.max(neededColors, assignedColors[i] + 1);
}
// produce colors as needed
var colors = [], variation = 0;
i = 0;
while (colors.length < neededColors) {
var c;
if (options.colors.length == i) // check degenerate case
c = $.color.make(100, 100, 100);
else
c = $.color.parse(options.colors[i]);
// vary color if needed
var sign = variation % 2 == 1 ? -1 : 1;
c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2)
// FIXME: if we're getting to close to something else,
// we should probably skip this one
colors.push(c);
++i;
if (i >= options.colors.length) {
i = 0;
++variation;
}
}
// fill in the options
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// turn on lines automatically in case nothing is set
if (s.lines.show == null) {
var v, show = true;
for (v in s)
if (s[v] && s[v].show) {
show = false;
break;
}
if (show)
s.lines.show = true;
}
// setup axes
s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
}
}
function processData() {
var topSentry = Number.POSITIVE_INFINITY,
bottomSentry = Number.NEGATIVE_INFINITY,
fakeInfinity = Number.MAX_VALUE,
i, j, k, m, length,
s, points, ps, x, y, axis, val, f, p;
function updateAxis(axis, min, max) {
if (min < axis.datamin && min != -fakeInfinity)
axis.datamin = min;
if (max > axis.datamax && max != fakeInfinity)
axis.datamax = max;
}
$.each(allAxes(), function (_, axis) {
// init axis
axis.datamin = topSentry;
axis.datamax = bottomSentry;
axis.used = false;
});
for (i = 0; i < series.length; ++i) {
s = series[i];
s.datapoints = { points: [] };
executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
}
// first pass: clean and copy data
for (i = 0; i < series.length; ++i) {
s = series[i];
var data = s.data, format = s.datapoints.format;
if (!format) {
format = [];
// find out how to copy
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
format.push({ y: true, number: true, required: false, defaultValue: 0 });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
s.datapoints.format = format;
}
if (s.datapoints.pointsize != null)
continue; // already filled in
s.datapoints.pointsize = format.length;
ps = s.datapoints.pointsize;
points = s.datapoints.points;
insertSteps = s.lines.show && s.lines.steps;
s.xaxis.used = s.yaxis.used = true;
for (j = k = 0; j < data.length; ++j, k += ps) {
p = data[j];
var nullify = p == null;
if (!nullify) {
for (m = 0; m < ps; ++m) {
val = p[m];
f = format[m];
if (f) {
if (f.number && val != null) {
val = +val; // convert to number
if (isNaN(val))
val = null;
else if (val == Infinity)
val = fakeInfinity;
else if (val == -Infinity)
val = -fakeInfinity;
}
if (val == null) {
if (f.required)
nullify = true;
if (f.defaultValue != null)
val = f.defaultValue;
}
}
points[k + m] = val;
}
}
if (nullify) {
for (m = 0; m < ps; ++m) {
val = points[k + m];
if (val != null) {
f = format[m];
// extract min/max info
if (f.x)
updateAxis(s.xaxis, val, val);
if (f.y)
updateAxis(s.yaxis, val, val);
}
points[k + m] = null;
}
}
else {
// a little bit of line specific stuff that
// perhaps shouldn't be here, but lacking
// better means...
if (insertSteps && k > 0
&& points[k - ps] != null
&& points[k - ps] != points[k]
&& points[k - ps + 1] != points[k + 1]) {
// copy the point to make room for a middle point
for (m = 0; m < ps; ++m)
points[k + ps + m] = points[k + m];
// middle point has same y
points[k + 1] = points[k - ps + 1];
// we've added a point, better reflect that
k += ps;
}
}
}
}
// give the hooks a chance to run
for (i = 0; i < series.length; ++i) {
s = series[i];
executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
}
// second pass: find datamax/datamin for auto-scaling
for (i = 0; i < series.length; ++i) {
s = series[i];
points = s.datapoints.points,
ps = s.datapoints.pointsize;
var xmin = topSentry, ymin = topSentry,
xmax = bottomSentry, ymax = bottomSentry;
for (j = 0; j < points.length; j += ps) {
if (points[j] == null)
continue;
for (m = 0; m < ps; ++m) {
val = points[j + m];
f = format[m];
if (!f || val == fakeInfinity || val == -fakeInfinity)
continue;
if (f.x) {
if (val < xmin)
xmin = val;
if (val > xmax)
xmax = val;
}
if (f.y) {
if (val < ymin)
ymin = val;
if (val > ymax)
ymax = val;
}
}
}
if (s.bars.show) {
// make sure we got room for the bar on the dancing floor
var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2;
if (s.bars.horizontal) {
ymin += delta;
ymax += delta + s.bars.barWidth;
}
else {
xmin += delta;
xmax += delta + s.bars.barWidth;
}
}
updateAxis(s.xaxis, xmin, xmax);
updateAxis(s.yaxis, ymin, ymax);
}
$.each(allAxes(), function (_, axis) {
if (axis.datamin == topSentry)
axis.datamin = null;
if (axis.datamax == bottomSentry)
axis.datamax = null;
});
}
function makeCanvas(skipPositioning, cls) {
var c = document.createElement('canvas');
c.className = cls;
c.width = canvasWidth;
c.height = canvasHeight;
if (!skipPositioning)
$(c).css({ position: 'absolute', left: 0, top: 0 });
$(c).appendTo(placeholder);
if (!c.getContext) // excanvas hack
c = window.G_vmlCanvasManager.initElement(c);
// used for resetting in case we get replotted
c.getContext("2d").save();
return c;
}
function getCanvasDimensions() {
canvasWidth = placeholder.width();
canvasHeight = placeholder.height();
if (canvasWidth <= 0 || canvasHeight <= 0)
throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
}
function resizeCanvas(c) {
// resizing should reset the state (excanvas seems to be
// buggy though)
if (c.width != canvasWidth)
c.width = canvasWidth;
if (c.height != canvasHeight)
c.height = canvasHeight;
// so try to get back to the initial state (even if it's
// gone now, this should be safe according to the spec)
var cctx = c.getContext("2d");
cctx.restore();
// and save again
cctx.save();
}
function setupCanvases() {
var reused,
existingCanvas = placeholder.children("canvas.base"),
existingOverlay = placeholder.children("canvas.overlay");
if (existingCanvas.length == 0 || existingOverlay == 0) {
// init everything
placeholder.html(""); // make sure placeholder is clear
placeholder.css({ padding: 0 }); // padding messes up the positioning
if (placeholder.css("position") == 'static')
placeholder.css("position", "relative"); // for positioning labels and overlay
getCanvasDimensions();
canvas = makeCanvas(true, "base");
overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features
reused = false;
}
else {
// reuse existing elements
canvas = existingCanvas.get(0);
overlay = existingOverlay.get(0);
reused = true;
}
ctx = canvas.getContext("2d");
octx = overlay.getContext("2d");
// we include the canvas in the event holder too, because IE 7
// sometimes has trouble with the stacking order
eventHolder = $([overlay, canvas]);
if (reused) {
// run shutdown in the old plot object
placeholder.data("plot").shutdown();
// reset reused canvases
plot.resize();
// make sure overlay pixels are cleared (canvas is cleared when we redraw)
octx.clearRect(0, 0, canvasWidth, canvasHeight);
// then whack any remaining obvious garbage left
eventHolder.unbind();
placeholder.children().not([canvas, overlay]).remove();
}
// save in case we get replotted
placeholder.data("plot", plot);
}
function bindEvents() {
// bind events
if (options.grid.hoverable) {
eventHolder.mousemove(onMouseMove);
eventHolder.mouseleave(onMouseLeave);
}
if (options.grid.clickable)
eventHolder.click(onClick);
executeHooks(hooks.bindEvents, [eventHolder]);
}
function shutdown() {
if (redrawTimeout)
clearTimeout(redrawTimeout);
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mouseleave", onMouseLeave);
eventHolder.unbind("click", onClick);
executeHooks(hooks.shutdown, [eventHolder]);
}
function setTransformationHelpers(axis) {
// set helper functions on the axis, assumes plot area
// has been computed already
function identity(x) { return x; }
var s, m, t = axis.options.transform || identity,
it = axis.options.inverseTransform;
// precompute how much the axis is scaling a point
// in canvas space
if (axis.direction == "x") {
s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
m = Math.min(t(axis.max), t(axis.min));
}
else {
s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
s = -s;
m = Math.max(t(axis.max), t(axis.min));
}
// data point to canvas coordinate
if (t == identity) // slight optimization
axis.p2c = function (p) { return (p - m) * s; };
else
axis.p2c = function (p) { return (t(p) - m) * s; };
// canvas coordinate to data point
if (!it)
axis.c2p = function (c) { return m + c / s; };
else
axis.c2p = function (c) { return it(m + c / s); };
}
function measureTickLabels(axis) {
var opts = axis.options, i, ticks = axis.ticks || [], labels = [],
l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv;
function makeDummyDiv(labels, width) {
return $('<div style="position:absolute;top:-10000px;' + width + 'font-size:smaller">' +
'<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis">'
+ labels.join("") + '</div></div>')
.appendTo(placeholder);
}
if (axis.direction == "x") {
// to avoid measuring the widths of the labels (it's slow), we
// construct fixed-size boxes and put the labels inside
// them, we don't need the exact figures and the
// fixed-size box content is easy to center
if (w == null)
w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1));
// measure x label heights
if (h == null) {
labels = [];
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel" style="float:left;width:' + w + 'px">' + l + '</div>');
}
if (labels.length > 0) {
// stick them all in the same div and measure
// collective height
labels.push('<div style="clear:left"></div>');
dummyDiv = makeDummyDiv(labels, "width:10000px;");
h = dummyDiv.height();
dummyDiv.remove();
}
}
}
else if (w == null || h == null) {
// calculate y label dimensions
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel">' + l + '</div>');
}
if (labels.length > 0) {
dummyDiv = makeDummyDiv(labels, "");
if (w == null)
w = dummyDiv.children().width();
if (h == null)
h = dummyDiv.find("div.tickLabel").height();
dummyDiv.remove();
}
}
if (w == null)
w = 0;
if (h == null)
h = 0;
axis.labelWidth = w;
axis.labelHeight = h;
}
function allocateAxisBoxFirstPhase(axis) {
// find the bounding box of the axis by looking at label
// widths/heights and ticks, make room by diminishing the
// plotOffset
var lw = axis.labelWidth,
lh = axis.labelHeight,
pos = axis.options.position,
tickLength = axis.options.tickLength,
axismargin = options.grid.axisMargin,
padding = options.grid.labelMargin,
all = axis.direction == "x" ? xaxes : yaxes,
index;
// determine axis margin
var samePosition = $.grep(all, function (a) {
return a && a.options.position == pos && a.reserveSpace;
});
if ($.inArray(axis, samePosition) == samePosition.length - 1)
axismargin = 0; // outermost
// determine tick length - if we're innermost, we can use "full"
if (tickLength == null)
tickLength = "full";
var sameDirection = $.grep(all, function (a) {
return a && a.reserveSpace;
});
var innermost = $.inArray(axis, sameDirection) == 0;
if (!innermost && tickLength == "full")
tickLength = 5;
if (!isNaN(+tickLength))
padding += +tickLength;
// compute box
if (axis.direction == "x") {
lh += padding;
if (pos == "bottom") {
plotOffset.bottom += lh + axismargin;
axis.box = { top: canvasHeight - plotOffset.bottom, height: lh };
}
else {
axis.box = { top: plotOffset.top + axismargin, height: lh };
plotOffset.top += lh + axismargin;
}
}
else {
lw += padding;
if (pos == "left") {
axis.box = { left: plotOffset.left + axismargin, width: lw };
plotOffset.left += lw + axismargin;
}
else {
plotOffset.right += lw + axismargin;
axis.box = { left: canvasWidth - plotOffset.right, width: lw };
}
}
// save for future reference
axis.position = pos;
axis.tickLength = tickLength;
axis.box.padding = padding;
axis.innermost = innermost;
}
function allocateAxisBoxSecondPhase(axis) {
// set remaining bounding box coordinates
if (axis.direction == "x") {
axis.box.left = plotOffset.left;
axis.box.width = plotWidth;
}
else {
axis.box.top = plotOffset.top;
axis.box.height = plotHeight;
}
}
function setupGrid() {
var i, axes = allAxes();
// first calculate the plot and axis box dimensions
$.each(axes, function (_, axis) {
axis.show = axis.options.show;
if (axis.show == null)
axis.show = axis.used; // by default an axis is visible if it's got data
axis.reserveSpace = axis.show || axis.options.reserveSpace;
setRange(axis);
});
allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0;
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
// make the ticks
setupTickGeneration(axis);
setTicks(axis);
snapRangeToTicks(axis, axis.ticks);
// find labelWidth/Height for axis
measureTickLabels(axis);
});
// with all dimensions in house, we can compute the
// axis boxes, start from the outside (reverse order)
for (i = allocatedAxes.length - 1; i >= 0; --i)
allocateAxisBoxFirstPhase(allocatedAxes[i]);
// make sure we've got enough space for things that
// might stick out
var minMargin = options.grid.minBorderMargin;
if (minMargin == null) {
minMargin = 0;
for (i = 0; i < series.length; ++i)
minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2);
}
for (var a in plotOffset) {
plotOffset[a] += options.grid.borderWidth;
plotOffset[a] = Math.max(minMargin, plotOffset[a]);
}
}
plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
// now we got the proper plotWidth/Height, we can compute the scaling
$.each(axes, function (_, axis) {
setTransformationHelpers(axis);
});
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
allocateAxisBoxSecondPhase(axis);
});
insertAxisLabels();
}
insertLegend();
}
function setRange(axis) {
var opts = axis.options,
min = +(opts.min != null ? opts.min : axis.datamin),
max = +(opts.max != null ? opts.max : axis.datamax),
delta = max - min;
if (delta == 0.0) {
// degenerate case
var widen = max == 0 ? 1 : 0.01;
if (opts.min == null)
min -= widen;
// always widen max if we couldn't widen min to ensure we
// don't fall into min == max which doesn't work
if (opts.max == null || opts.min != null)
max += widen;
}
else {
// consider autoscaling
var margin = opts.autoscaleMargin;
if (margin != null) {
if (opts.min == null) {
min -= delta * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin != null && axis.datamin >= 0)
min = 0;
}
if (opts.max == null) {
max += delta * margin;
if (max > 0 && axis.datamax != null && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function setupTickGeneration(axis) {
var opts = axis.options;
// estimate number of ticks
var noTicks;
if (typeof opts.ticks == "number" && opts.ticks > 0)
noTicks = opts.ticks;
else
// heuristic based on the model a*sqrt(x) fitted to
// some data points that seemed reasonable
noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight);
var delta = (axis.max - axis.min) / noTicks,
size, generator, unit, formatter, i, magn, norm;
if (opts.mode == "time") {
// pretty handling of time
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var spec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"], [3, "month"], [6, "month"],
[1, "year"]
];
var minSize = 0;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number")
minSize = opts.tickSize;
else
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
for (var i = 0; i < spec.length - 1; ++i)
if (delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize)
break;
size = spec[i][0];
unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10));
norm = (delta / timeUnitSize.year) / magn;
if (norm < 1.5)
size = 1;
else if (norm < 3)
size = 2;
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
}
axis.tickSize = opts.tickSize || [size, unit];
generator = function(axis) {
var ticks = [],
tickSize = axis.tickSize[0], unit = axis.tickSize[1],
d = new Date(axis.min);
var step = tickSize * timeUnitSize[unit];
if (unit == "second")
d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
if (unit == "minute")
d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
if (unit == "hour")
d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
if (unit == "month")
d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
if (unit == "year")
d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
// reset smaller components
d.setUTCMilliseconds(0);
if (step >= timeUnitSize.minute)
d.setUTCSeconds(0);
if (step >= timeUnitSize.hour)
d.setUTCMinutes(0);
if (step >= timeUnitSize.day)
d.setUTCHours(0);
if (step >= timeUnitSize.day * 4)
d.setUTCDate(1);
if (step >= timeUnitSize.year)
d.setUTCMonth(0);
var carry = 0, v = Number.NaN, prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month") {
if (tickSize < 1) {
// a bit complicated - we'll divide the month
// up but we need to take care of fractions
// so we don't end up in the middle of a day
d.setUTCDate(1);
var start = d.getTime();
d.setUTCMonth(d.getUTCMonth() + 1);
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getUTCHours();
d.setUTCHours(0);
}
else
d.setUTCMonth(d.getUTCMonth() + tickSize);
}
else if (unit == "year") {
d.setUTCFullYear(d.getUTCFullYear() + tickSize);
}
else
d.setTime(v + step);
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
var d = new Date(v);
// first check global format
if (opts.timeformat != null)
return $.plot.formatDate(d, opts.timeformat, opts.monthNames);
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
if (t < timeUnitSize.minute)
fmt = "%h:%M:%S" + suffix;
else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day)
fmt = "%h:%M" + suffix;
else
fmt = "%b %d %h:%M" + suffix;
}
else if (t < timeUnitSize.month)
fmt = "%b %d";
else if (t < timeUnitSize.year) {
if (span < timeUnitSize.year)
fmt = "%b";
else
fmt = "%b %y";
}
else
fmt = "%y";
return $.plot.formatDate(d, fmt, opts.monthNames);
};
}
else {
// pretty rounding of base-10 numbers
var maxDec = opts.tickDecimals;
var dec = -Math.floor(Math.log(delta) / Math.LN10);
if (maxDec != null && dec > maxDec)
dec = maxDec;
magn = Math.pow(10, -dec);
norm = delta / magn; // norm is between 1.0 and 10.0
if (norm < 1.5)
size = 1;
else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
}
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
if (opts.minTickSize != null && size < opts.minTickSize)
size = opts.minTickSize;
axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
axis.tickSize = opts.tickSize || size;
generator = function (axis) {
var ticks = [];
// spew out all possible ticks
var start = floorInBase(axis.min, axis.tickSize),
i = 0, v = Number.NaN, prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
return v.toFixed(axis.tickDecimals);
};
}
if (opts.alignTicksWithAxis != null) {
var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
if (otherAxis && otherAxis.used && otherAxis != axis) {
// consider snapping min/max to outermost nice ticks
var niceTicks = generator(axis);
if (niceTicks.length > 0) {
if (opts.min == null)
axis.min = Math.min(axis.min, niceTicks[0]);
if (opts.max == null && niceTicks.length > 1)
axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
}
generator = function (axis) {
// copy ticks, scaled to this axis
var ticks = [], v, i;
for (i = 0; i < otherAxis.ticks.length; ++i) {
v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
v = axis.min + v * (axis.max - axis.min);
ticks.push(v);
}
return ticks;
};
// we might need an extra decimal since forced
// ticks don't necessarily fit naturally
if (axis.mode != "time" && opts.tickDecimals == null) {
var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1),
ts = generator(axis);
// only proceed if the tick interval rounded
// with an extra decimal doesn't give us a
// zero at end
if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
axis.tickDecimals = extraDec;
}
}
}
axis.tickGenerator = generator;
if ($.isFunction(opts.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
else
axis.tickFormatter = formatter;
}
function setTicks(axis) {
var oticks = axis.options.ticks, ticks = [];
if (oticks == null || (typeof oticks == "number" && oticks > 0))
ticks = axis.tickGenerator(axis);
else if (oticks) {
if ($.isFunction(oticks))
// generate the ticks
ticks = oticks({ min: axis.min, max: axis.max });
else
ticks = oticks;
}
// clean up/labelify the supplied ticks, copy them over
var i, v;
axis.ticks = [];
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = +t[0];
if (t.length > 1)
label = t[1];
}
else
v = +t;
if (label == null)
label = axis.tickFormatter(v, axis);
if (!isNaN(v))
axis.ticks.push({ v: v, label: label });
}
}
function snapRangeToTicks(axis, ticks) {
if (axis.options.autoscaleMargin && ticks.length > 0) {
// snap to ticks
if (axis.options.min == null)
axis.min = Math.min(axis.min, ticks[0].v);
if (axis.options.max == null && ticks.length > 1)
axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
}
}
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
var grid = options.grid;
// draw background, if any
if (grid.show && grid.backgroundColor)
drawBackground();
if (grid.show && !grid.aboveData)
drawGrid();
for (var i = 0; i < series.length; ++i) {
executeHooks(hooks.drawSeries, [ctx, series[i]]);
drawSeries(series[i]);
}
executeHooks(hooks.draw, [ctx]);
if (grid.show && grid.aboveData)
drawGrid();
}
function extractRange(ranges, coord) {
var axis, from, to, key, axes = allAxes();
for (i = 0; i < axes.length; ++i) {
axis = axes[i];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? xaxes[0] : yaxes[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function drawBackground() {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
ctx.fillRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
function drawGrid() {
var i;
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// draw markings
var markings = options.grid.markings;
if (markings) {
if ($.isFunction(markings)) {
var axes = plot.getAxes();
// xmin etc. is backwards compatibility, to be
// removed in the future
axes.xmin = axes.xaxis.min;
axes.xmax = axes.xaxis.max;
axes.ymin = axes.yaxis.min;
axes.ymax = axes.yaxis.max;
markings = markings(axes);
}
for (i = 0; i < markings.length; ++i) {
var m = markings[i],
xrange = extractRange(m, "x"),
yrange = extractRange(m, "y");
// fill in missing
if (xrange.from == null)
xrange.from = xrange.axis.min;
if (xrange.to == null)
xrange.to = xrange.axis.max;
if (yrange.from == null)
yrange.from = yrange.axis.min;
if (yrange.to == null)
yrange.to = yrange.axis.max;
// clip
if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
continue;
xrange.from = Math.max(xrange.from, xrange.axis.min);
xrange.to = Math.min(xrange.to, xrange.axis.max);
yrange.from = Math.max(yrange.from, yrange.axis.min);
yrange.to = Math.min(yrange.to, yrange.axis.max);
if (xrange.from == xrange.to && yrange.from == yrange.to)
continue;
// then draw
xrange.from = xrange.axis.p2c(xrange.from);
xrange.to = xrange.axis.p2c(xrange.to);
yrange.from = yrange.axis.p2c(yrange.from);
yrange.to = yrange.axis.p2c(yrange.to);
if (xrange.from == xrange.to || yrange.from == yrange.to) {
// draw line
ctx.beginPath();
ctx.strokeStyle = m.color || options.grid.markingsColor;
ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
ctx.moveTo(xrange.from, yrange.from);
ctx.lineTo(xrange.to, yrange.to);
ctx.stroke();
}
else {
// fill area
ctx.fillStyle = m.color || options.grid.markingsColor;
ctx.fillRect(xrange.from, yrange.to,
xrange.to - xrange.from,
yrange.from - yrange.to);
}
}
}
// draw the ticks
var axes = allAxes(), bw = options.grid.borderWidth;
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box,
t = axis.tickLength, x, y, xoff, yoff;
if (!axis.show || axis.ticks.length == 0)
continue
ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString();
ctx.lineWidth = 1;
// find the edges
if (axis.direction == "x") {
x = 0;
if (t == "full")
y = (axis.position == "top" ? 0 : plotHeight);
else
y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
}
else {
y = 0;
if (t == "full")
x = (axis.position == "left" ? 0 : plotWidth);
else
x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
}
// draw tick bar
if (!axis.innermost) {
ctx.beginPath();
xoff = yoff = 0;
if (axis.direction == "x")
xoff = plotWidth;
else
yoff = plotHeight;
if (ctx.lineWidth == 1) {
x = Math.floor(x) + 0.5;
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
ctx.stroke();
}
// draw ticks
ctx.beginPath();
for (i = 0; i < axis.ticks.length; ++i) {
var v = axis.ticks[i].v;
xoff = yoff = 0;
if (v < axis.min || v > axis.max
// skip those lying on the axes if we got a border
|| (t == "full" && bw > 0
&& (v == axis.min || v == axis.max)))
continue;
if (axis.direction == "x") {
x = axis.p2c(v);
yoff = t == "full" ? -plotHeight : t;
if (axis.position == "top")
yoff = -yoff;
}
else {
y = axis.p2c(v);
xoff = t == "full" ? -plotWidth : t;
if (axis.position == "left")
xoff = -xoff;
}
if (ctx.lineWidth == 1) {
if (axis.direction == "x")
x = Math.floor(x) + 0.5;
else
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
}
ctx.stroke();
}
// draw border
if (bw) {
ctx.lineWidth = bw;
ctx.strokeStyle = options.grid.borderColor;
ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
}
ctx.restore();
}
function insertAxisLabels() {
placeholder.find(".tickLabels").remove();
var html = ['<div class="tickLabels" style="font-size:smaller">'];
var axes = allAxes();
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box;
if (!axis.show)
continue;
//debug: html.push('<div style="position:absolute;opacity:0.10;background-color:red;left:' + box.left + 'px;top:' + box.top + 'px;width:' + box.width + 'px;height:' + box.height + 'px"></div>')
html.push('<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis" style="color:' + axis.options.color + '">');
for (var i = 0; i < axis.ticks.length; ++i) {
var tick = axis.ticks[i];
if (!tick.label || tick.v < axis.min || tick.v > axis.max)
continue;
var pos = {}, align;
if (axis.direction == "x") {
align = "center";
pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2);
if (axis.position == "bottom")
pos.top = box.top + box.padding;
else
pos.bottom = canvasHeight - (box.top + box.height - box.padding);
}
else {
pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2);
if (axis.position == "left") {
pos.right = canvasWidth - (box.left + box.width - box.padding)
align = "right";
}
else {
pos.left = box.left + box.padding;
align = "left";
}
}
pos.width = axis.labelWidth;
var style = ["position:absolute", "text-align:" + align ];
for (var a in pos)
style.push(a + ":" + pos[a] + "px")
html.push('<div class="tickLabel" style="' + style.join(';') + '">' + tick.label + '</div>');
}
html.push('</div>');
}
html.push('</div>');
placeholder.append(html.join(""));
}
function drawSeries(series) {
if (series.lines.show)
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
prevx = null, prevy = null;
ctx.beginPath();
for (var i = ps; i < points.length; i += ps) {
var x1 = points[i - ps], y1 = points[i - ps + 1],
x2 = points[i], y2 = points[i + 1];
if (x1 == null || x2 == null)
continue;
// clip with ymin
if (y1 <= y2 && y1 < axisy.min) {
if (y2 < axisy.min)
continue; // line segment is outside
// compute new intersection point
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min) {
if (y1 < axisy.min)
continue;
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max) {
if (y2 > axisy.max)
continue;
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max) {
if (y1 > axisy.max)
continue;
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (x1 != prevx || y1 != prevy)
ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
prevx = x2;
prevy = y2;
ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
}
ctx.stroke();
}
function plotLineArea(datapoints, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
bottom = Math.min(Math.max(0, axisy.min), axisy.max),
i = 0, top, areaOpen = false,
ypos = 1, segmentStart = 0, segmentEnd = 0;
// we process each segment in two turns, first forward
// direction to sketch out top, then once we hit the
// end we go backwards to sketch the bottom
while (true) {
if (ps > 0 && i > points.length + ps)
break;
i += ps; // ps is negative if going backwards
var x1 = points[i - ps],
y1 = points[i - ps + ypos],
x2 = points[i], y2 = points[i + ypos];
if (areaOpen) {
if (ps > 0 && x1 != null && x2 == null) {
// at turning point
segmentEnd = i;
ps = -ps;
ypos = 2;
continue;
}
if (ps < 0 && i == segmentStart + ps) {
// done with the reverse sweep
ctx.fill();
areaOpen = false;
ps = -ps;
ypos = 1;
i = segmentStart = segmentEnd + ps;
continue;
}
}
if (x1 == null || x2 == null)
continue;
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= axisy.max && y2 >= axisy.max) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
continue;
}
else if (y1 <= axisy.min && y2 <= axisy.min) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
continue;
}
// else it's a bit more complicated, there might
// be a flat maxed out rectangle first, then a
// triangular cutout or reverse; to find these
// keep track of the current x values
var x1old = x1, x2old = x2;
// clip the y values, without shortcutting, we
// go through all cases in turn
// clip with ymin
if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
// it goes to (x1, y1), but we fill that below
}
// fill triangular section, this sometimes result
// in redundant points if (x1, y1) hasn't changed
// from previous line to, but we just ignore that
ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth,
sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (lw > 0 && sw > 0) {
// draw shadow as a thick and thin line with transparency
ctx.lineWidth = sw;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
// position shadow at angle from the mid of line
var angle = Math.PI/18;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
ctx.lineWidth = sw/2;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
if (fillStyle) {
ctx.fillStyle = fillStyle;
plotLineArea(series.datapoints, series.xaxis, series.yaxis);
}
if (lw > 0)
plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var x = points[i], y = points[i + 1];
if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
continue;
ctx.beginPath();
x = axisx.p2c(x);
y = axisy.p2c(y) + offset;
if (symbol == "circle")
ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
else
symbol(ctx, x, y, radius, shadow);
ctx.closePath();
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.points.lineWidth,
sw = series.shadowSize,
radius = series.points.radius,
symbol = series.points.symbol;
if (lw > 0 && sw > 0) {
// draw shadow in two steps
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPoints(series.datapoints, radius, null, w + w/2, true,
series.xaxis, series.yaxis, symbol);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPoints(series.datapoints, radius, null, w/2, true,
series.xaxis, series.yaxis, symbol);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
plotPoints(series.datapoints, radius,
getFillStyle(series.points, series.color), 0, false,
series.xaxis, series.yaxis, symbol);
ctx.restore();
}
function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
var left, right, bottom, top,
drawLeft, drawRight, drawTop, drawBottom,
tmp;
// in horizontal mode, we start the bar from the left
// instead of from the bottom so it appears to be
// horizontal rather than vertical
if (horizontal) {
drawBottom = drawRight = drawTop = true;
drawLeft = false;
left = b;
right = x;
top = y + barLeft;
bottom = y + barRight;
// account for negative bars
if (right < left) {
tmp = right;
right = left;
left = tmp;
drawLeft = true;
drawRight = false;
}
}
else {
drawLeft = drawRight = drawTop = true;
drawBottom = false;
left = x + barLeft;
right = x + barRight;
bottom = b;
top = y;
// account for negative bars
if (top < bottom) {
tmp = top;
top = bottom;
bottom = tmp;
drawBottom = true;
drawTop = false;
}
}
// clip
if (right < axisx.min || left > axisx.max ||
top < axisy.min || bottom > axisy.max)
return;
if (left < axisx.min) {
left = axisx.min;
drawLeft = false;
}
if (right > axisx.max) {
right = axisx.max;
drawRight = false;
}
if (bottom < axisy.min) {
bottom = axisy.min;
drawBottom = false;
}
if (top > axisy.max) {
top = axisy.max;
drawTop = false;
}
left = axisx.p2c(left);
bottom = axisy.p2c(bottom);
right = axisx.p2c(right);
top = axisy.p2c(top);
// fill the bar
if (fillStyleCallback) {
c.beginPath();
c.moveTo(left, bottom);
c.lineTo(left, top);
c.lineTo(right, top);
c.lineTo(right, bottom);
c.fillStyle = fillStyleCallback(bottom, top);
c.fill();
}
// draw outline
if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
c.beginPath();
// FIXME: inline moveTo is buggy with excanvas
c.moveTo(left, bottom + offset);
if (drawLeft)
c.lineTo(left, top + offset);
else
c.moveTo(left, top + offset);
if (drawTop)
c.lineTo(right, top + offset);
else
c.moveTo(right, top + offset);
if (drawRight)
c.lineTo(right, bottom + offset);
else
c.moveTo(right, bottom + offset);
if (drawBottom)
c.lineTo(left, bottom + offset);
else
c.moveTo(left, bottom + offset);
c.stroke();
}
}
function drawSeriesBars(series) {
function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// FIXME: figure out a way to add shadows (for instance along the right edge)
ctx.lineWidth = series.bars.lineWidth;
ctx.strokeStyle = series.color;
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis);
ctx.restore();
}
function getFillStyle(filloptions, seriesColor, bottom, top) {
var fill = filloptions.fill;
if (!fill)
return null;
if (filloptions.fillColor)
return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
var c = $.color.parse(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
return c.toString();
}
function insertLegend() {
placeholder.find(".legend").remove();
if (!options.legend.show)
return;
var fragments = [], rowStarted = false,
lf = options.legend.labelFormatter, s, label;
for (var i = 0; i < series.length; ++i) {
s = series[i];
label = s.label;
if (!label)
continue;
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
if (lf)
label = lf(label, s);
fragments.push(
'<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + s.color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel">' + label + '</td>');
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length == 0)
return;
var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
$(options.legend.container).html(table);
else {
var pos = "",
p = options.legend.position,
m = options.legend.margin;
if (m[0] == null)
m = [m, m];
if (p.charAt(0) == "n")
pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
c = options.grid.backgroundColor;
if (c && typeof c == "string")
c = $.color.parse(c);
else
c = $.color.extract(legend, 'background-color');
c.a = 1;
c = c.toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
// interactive features
var highlights = [],
redrawTimeout = null;
// returns the data item the mouse is over, or null if none is found
function findNearbyItem(mouseX, mouseY, seriesFilter) {
var maxDistance = options.grid.mouseActiveRadius,
smallestDistance = maxDistance * maxDistance + 1,
item = null, foundPoint = false, i, j;
for (i = series.length - 1; i >= 0; --i) {
if (!seriesFilter(series[i]))
continue;
var s = series[i],
axisx = s.xaxis,
axisy = s.yaxis,
points = s.datapoints.points,
ps = s.datapoints.pointsize,
mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
my = axisy.c2p(mouseY),
maxx = maxDistance / axisx.scale,
maxy = maxDistance / axisy.scale;
// with inverse transforms, we can't use the maxx/maxy
// optimization, sadly
if (axisx.options.inverseTransform)
maxx = Number.MAX_VALUE;
if (axisy.options.inverseTransform)
maxy = Number.MAX_VALUE;
if (s.lines.show || s.points.show) {
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1];
if (x == null)
continue;
// For points and lines, the cursor must be within a
// certain distance to the data point
if (x - mx > maxx || x - mx < -maxx ||
y - my > maxy || y - my < -maxy)
continue;
// We have to calculate distances in pixels, not in
// data units, because the scales of the axes may be different
var dx = Math.abs(axisx.p2c(x) - mouseX),
dy = Math.abs(axisy.p2c(y) - mouseY),
dist = dx * dx + dy * dy; // we save the sqrt
// use <= to ensure last point takes precedence
// (last generally means on top of)
if (dist < smallestDistance) {
smallestDistance = dist;
item = [i, j / ps];
}
}
}
if (s.bars.show && !item) { // no other point can be nearby
var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2,
barRight = barLeft + s.bars.barWidth;
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1], b = points[j + 2];
if (x == null)
continue;
// for a bar graph, the cursor must be inside the bar
if (series[i].bars.horizontal ?
(mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
my >= y + barLeft && my <= y + barRight) :
(mx >= x + barLeft && mx <= x + barRight &&
my >= Math.min(b, y) && my <= Math.max(b, y)))
item = [i, j / ps];
}
}
}
if (item) {
i = item[0];
j = item[1];
ps = series[i].datapoints.pointsize;
return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
dataIndex: j,
series: series[i],
seriesIndex: i };
}
return null;
}
function onMouseMove(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return s["hoverable"] != false; });
}
function onMouseLeave(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return false; });
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters
// so we share their code)
function triggerClickHoverEvent(eventname, event, seriesFilter) {
var offset = eventHolder.offset(),
canvasX = event.pageX - offset.left - plotOffset.left,
canvasY = event.pageY - offset.top - plotOffset.top,
pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
pos.pageX = event.pageX;
pos.pageY = event.pageY;
var item = findNearbyItem(canvasX, canvasY, seriesFilter);
if (item) {
// fill in mouse pos for any listeners out there
item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left);
item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top);
}
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname &&
!(item && h.series == item.series &&
h.point[0] == item.datapoint[0] &&
h.point[1] == item.datapoint[1]))
unhighlight(h.series, h.point);
}
if (item)
highlight(item.series, item.datapoint, eventname);
}
placeholder.trigger(eventname, [ pos, item ]);
}
function triggerRedrawOverlay() {
if (!redrawTimeout)
redrawTimeout = setTimeout(drawOverlay, 30);
}
function drawOverlay() {
redrawTimeout = null;
// draw highlights
octx.save();
octx.clearRect(0, 0, canvasWidth, canvasHeight);
octx.translate(plotOffset.left, plotOffset.top);
var i, hi;
for (i = 0; i < highlights.length; ++i) {
hi = highlights[i];
if (hi.series.bars.show)
drawBarHighlight(hi.series, hi.point);
else
drawPointHighlight(hi.series, hi.point);
}
octx.restore();
executeHooks(hooks.drawOverlay, [octx]);
}
function highlight(s, point, auto) {
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i == -1) {
highlights.push({ series: s, point: point, auto: auto });
triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s, point) {
if (s == null && point == null) {
highlights = [];
triggerRedrawOverlay();
}
if (typeof s == "number")
s = series[s];
if (typeof point == "number")
point = s.data[point];
var i = indexOfHighlight(s, point);
if (i != -1) {
highlights.splice(i, 1);
triggerRedrawOverlay();
}
}
function indexOfHighlight(s, p) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s && h.point[0] == p[0]
&& h.point[1] == p[1])
return i;
}
return -1;
}
function drawPointHighlight(series, point) {
var x = point[0], y = point[1],
axisx = series.xaxis, axisy = series.yaxis;
if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
return;
var pointRadius = series.points.radius + series.points.lineWidth / 2;
octx.lineWidth = pointRadius;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var radius = 1.5 * pointRadius,
x = axisx.p2c(x),
y = axisy.p2c(y);
octx.beginPath();
if (series.points.symbol == "circle")
octx.arc(x, y, radius, 0, 2 * Math.PI, false);
else
series.points.symbol(octx, x, y, radius, false);
octx.closePath();
octx.stroke();
}
function drawBarHighlight(series, point) {
octx.lineWidth = series.bars.lineWidth;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
}
function getColorOrGradient(spec, bottom, top, defaultColor) {
if (typeof spec == "string")
return spec;
else {
// assume this is a gradient spec; IE currently only
// supports a simple vertical gradient properly, so that's
// what we support too
var gradient = ctx.createLinearGradient(0, top, 0, bottom);
for (var i = 0, l = spec.colors.length; i < l; ++i) {
var c = spec.colors[i];
if (typeof c != "string") {
var co = $.color.parse(defaultColor);
if (c.brightness != null)
co = co.scale('rgb', c.brightness)
if (c.opacity != null)
co.a *= c.opacity;
c = co.toString();
}
gradient.addColorStop(i / (l - 1), c);
}
return gradient;
}
}
}
$.plot = function(placeholder, data, options) {
//var t0 = new Date();
var plot = new Plot($(placeholder), data, options, $.plot.plugins);
//(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
return plot;
};
$.plot.version = "0.7";
$.plot.plugins = [];
// returns a string with the date d formatted according to fmt
$.plot.formatDate = function(d, fmt, monthNames) {
var leftPad = function(n) {
n = "" + n;
return n.length == 1 ? "0" + n : n;
};
var r = [];
var escape = false, padNext = false;
var hours = d.getUTCHours();
var isAM = hours < 12;
if (monthNames == null)
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
if (fmt.search(/%p|%P/) != -1) {
if (hours > 12) {
hours = hours - 12;
} else if (hours == 0) {
hours = 12;
}
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'h': c = "" + hours; break;
case 'H': c = leftPad(hours); break;
case 'M': c = leftPad(d.getUTCMinutes()); break;
case 'S': c = leftPad(d.getUTCSeconds()); break;
case 'd': c = "" + d.getUTCDate(); break;
case 'm': c = "" + (d.getUTCMonth() + 1); break;
case 'y': c = "" + d.getUTCFullYear(); break;
case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case '0': c = ""; padNext = true; break;
}
if (c && padNext) {
c = leftPad(c);
padNext = false;
}
r.push(c);
if (!padNext)
escape = false;
}
else {
if (c == "%")
escape = true;
else
r.push(c);
}
}
return r.join("");
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
})(jQuery);
| JavaScript |
// this code improves bootstrap menus and adds dropdown support
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(jQuery(this).parent().find('ul').length)
jQuery(this).attr({'class':'dropdown-toggle','data-toggle':'dropdown'}).append('<b class="caret"></b>');
});
jQuery('.nav li li').each(function(){
if(jQuery(this).find('ul').length)
jQuery(this).addClass('dropdown-submenu');
});
function adjust_height_of_collapsed_nav() {
var cn = jQuery('div.collapse');
if (cn.get(0)) {
var cnh = cn.get(0).style.height;
if (cnh>'0px'){
cn.css('height','auto');
}
}
}
function hoverMenu(){
jQuery('ul.nav a.dropdown-toggle').parent().hover(function(){
adjust_height_of_collapsed_nav();
mi = jQuery(this).addClass('open');
mi.children('.dropdown-menu').stop(true, true).delay(200).fadeIn(400);
}, function(){
mi = jQuery(this);
mi.children('.dropdown-menu').stop(true, true).delay(200).fadeOut(function(){mi.removeClass('open')});
});
}
hoverMenu(); // first page load
jQuery(window).resize(hoverMenu); // on resize event
jQuery('ul.nav li.dropdown a').click(function(){window.location=jQuery(this).attr('href');});
// make all buttons bootstrap buttons
jQuery('button, form input[type="submit"], form input[type="button"]').addClass('btn');
}); | JavaScript |
function prepareDataForSave(name,data) {
var obj = new Object();
obj.Name = name;
obj.Data = data;
return obj;
}
function prepareMultiPartPOST(data) {
// var boundary = 'sPlItME' + Math.floor(Math.random()*10000);
var boundary = '' + Math.floor(Math.random()*10000);
var reqdata = '--' + boundary + '\r\n';
//console.log(data.length);
for (var i=0;i < data.length;i++) {
reqdata += 'content-disposition: form-data; name="';
reqdata += data[i].Name + '"';
reqdata += "\r\n\r\n" ;
reqdata += data[i].Data;
reqdata += "\r\n" ;
reqdata += '--' + boundary + '\r\n';
}
return new Array(reqdata,boundary);
}
function on_error() {
jQuery("input[name='saved_on']").attr('style','background-color:red');
jQuery("input[name='saved_on']").val('communication error');
}
function getData() {
if (window.ace_editor) {
var data = window.ace_editor.getSession().getValue();
} else if (window.mirror) {
var data = window.mirror.getValue();
} else if (window.eamy) {
var data = window.eamy.instances[0].getText();
} else if (window.textarea) {
var data = textarea.value;
}
return data;
}
function doHighlight(highlight) {
if (window.ace_editor) {
window.ace_editor.gotoLine(highlight.lineno);
} else if (window.mirror) {
// Put the cursor at the offending line:
window.mirror.setCursor({line:highlight.lineno-1,
ch:highlight.offset+1});
} else if (window.eamy) {
// not implemented
} else if (window.textarea) {
editAreaLoader.setSelectionRange('body', highlight.start, highlight.end);
}
}
function doClickSave() {
var data = getData();
var dataForPost = prepareMultiPartPOST(new Array(
prepareDataForSave('data', data),
prepareDataForSave('file_hash',
jQuery("input[name='file_hash']").val()),
prepareDataForSave('saved_on',
jQuery("input[name='saved_on']").val()),
prepareDataForSave('saved_on',
jQuery("input[name='saved_on']").val()),
prepareDataForSave('from_ajax','true')));
// console.info(area.textarea.value);
jQuery("input[name='saved_on']").attr('style',
'background-color:yellow');
jQuery("input[name='saved_on']").val('saving now...')
jQuery.ajax({
type: "POST",
contentType: 'multipart/form-data;boundary="'
+ dataForPost[1] + '"',
url: self.location.href,
dataType: "json",
data: dataForPost[0],
timeout: 5000,
beforeSend: function(xhr) {
xhr.setRequestHeader('web2py-component-location',
document.location);
xhr.setRequestHeader('web2py-component-element',
'doClickSave');
},
success: function(json,text,xhr){
// show flash message (if any)
var flash=xhr.getResponseHeader('web2py-component-flash');
if (flash) {
var flashhtml = decodeURIComponent(flash);
jQuery('.flash').html(flashhtml).slideDown();
} else jQuery('.flash').hide();
// reenable disabled submit button
var t=jQuery("input[name='save']");
t.attr('class','');
t.attr('disabled','');
try {
if (json.error) {
window.location.href=json.redirect;
} else {
// console.info( json.file_hash );
jQuery("input[name='file_hash']").val(json.file_hash);
jQuery("input[name='saved_on']").val(json.saved_on);
if (json.highlight) {
doHighlight(json.highlight);
} else {
jQuery("input[name='saved_on']").attr('style','background-color:#99FF99');
//jQuery(".flash").delay(1000).fadeOut('slow');
}
// console.info(jQuery("input[name='file_hash']").val());
var output = '<b>exposes:</b> ';
for ( var i in json.functions) {
output += ' <a href="/' + json.application + '/' + json.controller + '/' + json.functions[i] + '">' + json.functions[i] + '</a>,';
}
if(output!='<b>exposes:</b> ') {
jQuery("#exposed").html( output.substring(0, output.length-1));
}
}
} catch(e) { on_error();}
},
error: function(json) { on_error(); }
});
return false;
}
function getSelectionRange() {
var sel;
if (window.ace_editor) {
sel = {};
range = window.ace_editor.getSelectionRange();
// passing the line number directly, no need to read the text
sel['start'] = range.start.row;
sel['end'] = range.end.row;
sel['data'] = '';
} else if (window.mirror) {
sel = {};
sel['start'] = window.mirror.getCursor(true).line;
sel['end'] = window.mirror.getCursor(false).line;
sel['data'] = '';
} else if (window.eamy) {
sel = {};
// not implemented
} else if (window.textarea) {
// passing offset, needs the text to calculate the line:
sel = editAreaLoader.getSelectionRange('body');
sel['data'] = getData();
}
return sel;
}
function doToggleBreakpoint(filename, url, sel) {
if (sel==null) {
// use cursor position to determine the breakpoint line
// (gutter already tell us the selected line)
sel = getSelectionRange();
}
var dataForPost = prepareMultiPartPOST(new Array(
prepareDataForSave('filename', filename),
prepareDataForSave('sel_start', sel["start"]),
prepareDataForSave('sel_end', sel["end"]),
prepareDataForSave('data', sel['data'])));
jQuery.ajax({
type: "POST",
contentType: 'multipart/form-data;boundary="'+dataForPost[1]+'"',
url: url,
dataType: "json",
data: dataForPost[0],
timeout: 5000,
beforeSend: function(xhr) {
xhr.setRequestHeader('web2py-component-location',
document.location);
xhr.setRequestHeader('web2py-component-element',
'doSetBreakpoint');},
success: function(json,text,xhr){
// show flash message (if any)
var flash=xhr.getResponseHeader('web2py-component-flash');
if (flash) {
jQuery('.flash').html(decodeURIComponent(flash))
.append('<a href="#" class="close">×</a>')
.slideDown();
}
else jQuery('.flash').hide();
try {
if (json.error) {
window.location.href=json.redirect;
} else {
if (json.ok==true && window.mirror) {
// mark the breakpoint if ok=True
editor.setMarker(json.lineno-1,
"<span style='color: red'>●</span> %N%")
} else if (json.ok==false && window.mirror) {
// remove mark if ok=False
editor.setMarker(json.lineno-1, "%N%")
} else {
// do nothing if ok = null
}
// alert(json.ok + json.lineno);
}
} catch(e) { on_error(); }
},
error: function(json) { on_error(); }
});
return false;
}
// on load, update all breakpoints markers:
function doListBreakpoints(filename, url) {
var dataForPost = prepareMultiPartPOST(new Array(
prepareDataForSave('filename', filename)
));
jQuery.ajax({
type: "POST",
contentType: 'multipart/form-data;boundary="'+dataForPost[1]+'"',
url: url,
dataType: "json",
data: dataForPost[0],
timeout: 5000,
beforeSend: function(xhr) {
xhr.setRequestHeader('web2py-component-location',
document.location);
xhr.setRequestHeader('web2py-component-element',
'doListBreakpoints');},
success: function(json,text,xhr){
try {
if (json.error) {
window.location.href=json.redirect;
} else {
if (window.mirror) {
for (i in json.breakpoints) {
lineno = json.breakpoints[i];
// mark the breakpoint if ok=True
editor.setMarker(lineno-1,
"<span style='color: red'>●</span> %N%");
}
}
}
} catch(e) { on_error(); }
},
error: function(json) { on_error(); }
});
return false;
}
function keepalive(url) {
jQuery.ajax({
type: "GET",
url: url,
timeout: 1000,
success: function(){},
error: function(x) { on_error(); } });
}
| JavaScript |
/*
Flot plugin for automatically redrawing plots when the placeholder
size changes, e.g. on window resizes.
It works by listening for changes on the placeholder div (through the
jQuery resize event plugin) - if the size changes, it will redraw the
plot.
There are no options. If you need to disable the plugin for some
plots, you can just fix the size of their placeholders.
*/
/* Inline dependency:
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this);
(function ($) {
var options = { }; // no options
function init(plot) {
function onResize() {
var placeholder = plot.getPlaceholder();
// somebody might have hidden us and we can't plot
// when we don't have the dimensions
if (placeholder.width() == 0 || placeholder.height() == 0)
return;
plot.resize();
plot.setupGrid();
plot.draw();
}
function bindEvents(plot, eventHolder) {
plot.getPlaceholder().resize(onResize);
}
function shutdown(plot, eventHolder) {
plot.getPlaceholder().unbind("resize", onResize);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'resize',
version: '1.0'
});
})(jQuery);
| JavaScript |
function popup(url) {
newwindow=window.open(url,'name','height=400,width=600');
if (window.focus) newwindow.focus();
return false;
}
function collapse(id) { jQuery('#'+id).slideToggle(); }
function fade(id,value) { if(value>0) jQuery('#'+id).hide().fadeIn('slow'); else jQuery('#'+id).show().fadeOut('slow'); }
function ajax(u,s,t) {
query = '';
if (typeof s == "string") {
d = jQuery(s).serialize();
if(d){ query = d; }
} else {
pcs = [];
if (s != null && s != undefined) for(i=0; i<s.length; i++) {
q = jQuery("[name="+s[i]+"]").serialize();
if(q){pcs.push(q);}
}
if (pcs.length>0){query = pcs.join("&");}
}
jQuery.ajax({type: "POST", url: u, data: query, success: function(msg) { if(t) { if(t==':eval') eval(msg); else if(typeof t=='string') jQuery("#"+t).html(msg); else t(msg); } } });
}
String.prototype.reverse = function () { return this.split('').reverse().join('');};
function web2py_ajax_fields(target) {
var date_format = (typeof w2p_ajax_date_format != 'undefined') ? w2p_ajax_date_format : "%Y-%m-%d";
var datetime_format = (typeof w2p_ajax_datetime_format != 'undefined') ? w2p_ajax_datetime_format : "%Y-%m-%d %H:%M:%S";
jQuery("input.date",target).each(function() {Calendar.setup({inputField:this, ifFormat:date_format, showsTime:false });});
jQuery("input.datetime",target).each(function() {Calendar.setup({inputField:this, ifFormat:datetime_format, showsTime: true, timeFormat: "24" });});
jQuery("input.time",target).each(function(){jQuery(this).timeEntry();});
};
function web2py_ajax_init(target) {
jQuery('.hidden', target).hide();
jQuery('.error', target).hide().slideDown('slow');
web2py_ajax_fields(target);
};
function web2py_event_handlers() {
var doc = jQuery(document)
doc.on('click', '.flash', function(e){var t=jQuery(this); if(t.css('top')=='0px') t.slideUp('slow'); else t.fadeOut(); e.preventDefault();});
doc.on('keyup', 'input.integer', function(){this.value=this.value.reverse().replace(/[^0-9\-]|\-(?=.)/g,'').reverse();});
doc.on('keyup', 'input.double, input.decimal', function(){this.value=this.value.reverse().replace(/[^0-9\-\.,]|[\-](?=.)|[\.,](?=[0-9]*[\.,])/g,'').reverse();});
var confirm_message = (typeof w2p_ajax_confirm_message != 'undefined') ? w2p_ajax_confirm_message : "Are you sure you want to delete this object?";
doc.on('click', "input[type='checkbox'].delete", function(){if(this.checked) if(!confirm(confirm_message)) this.checked=false;});
doc.ajaxSuccess(function(e, xhr) {
var redirect=xhr.getResponseHeader('web2py-redirect-location');
var command=xhr.getResponseHeader('web2py-component-command');
var flash=xhr.getResponseHeader('web2py-component-flash');
if (redirect !== null) {
window.location = redirect;
};
if(command !== null){
eval(decodeURIComponent(command));
}
if(flash) {
jQuery('.flash')
.html(decodeURIComponent(flash))
.append('<span id="closeflash">×</span>')
.slideDown();
}
});
doc.ajaxError(function(e, xhr, settings, exception) {
doc.off('click', '.flash')
switch(xhr.status){
case 500:
$('.flash').html(ajax_error_500).slideDown();
}
});
};
jQuery(function() {
var flash = jQuery('.flash');
flash.hide();
if(flash.html()) flash.append('<span id="closeflash">×</span>').slideDown();
web2py_ajax_init(document);
web2py_event_handlers();
});
function web2py_trap_form(action,target) {
jQuery('#'+target+' form').each(function(i){
var form=jQuery(this);
if(!form.hasClass('no_trap'))
form.submit(function(e){
jQuery('.flash').hide().html('');
web2py_ajax_page('post',action,form.serialize(),target);
e.preventDefault();
});
});
}
function web2py_trap_link(target) {
jQuery('#'+target+' a.w2p_trap').each(function(i){
var link=jQuery(this);
link.click(function(e) {
jQuery('.flash').hide().html('');
web2py_ajax_page('get',link.attr('href'),[],target);
e.preventDefault();
});
});
}
function web2py_ajax_page(method, action, data, target) {
jQuery.ajax({'type':method, 'url':action, 'data':data,
'beforeSend':function(xhr) {
xhr.setRequestHeader('web2py-component-location', document.location);
xhr.setRequestHeader('web2py-component-element', target);},
'complete':function(xhr,text){
var html=xhr.responseText;
var content=xhr.getResponseHeader('web2py-component-content');
var t = jQuery('#'+target);
if(content=='prepend') t.prepend(html);
else if(content=='append') t.append(html);
else if(content!='hide') t.html(html);
web2py_trap_form(action,target);
web2py_trap_link(target);
web2py_ajax_init('#'+target);
}
});
}
function web2py_component(action, target, timeout, times){
jQuery(function(){
var jelement = jQuery("#" + target);
var element = jelement.get(0);
var statement = "jQuery('#" + target + "').get(0).reload();";
element.reload = function (){
// Continue if times is Infinity or
// the times limit is not reached
if (this.reload_check()){
web2py_ajax_page('get', action, null, target);} }; // reload
// Method to check timing limit
element.reload_check = function (){
if (jelement.hasClass('w2p_component_stop')) {clearInterval(this.timing);return false;}
if (this.reload_counter == Infinity){return true;}
else {
if (!isNaN(this.reload_counter)){
this.reload_counter -= 1;
if (this.reload_counter < 0){
if (!this.run_once){
clearInterval(this.timing);
return false;
}
}
else{return true;}
} }
return false;}; // reload check
if (!isNaN(timeout)){
element.timeout = timeout;
element.reload_counter = times;
if (times > 1){
// Multiple or infinite reload
// Run first iteration
web2py_ajax_page('get', action, null, target);
element.run_once = false;
element.timing = setInterval(statement, timeout);
element.reload_counter -= 1;
}
else if (times == 1) {
// Run once with timeout
element.run_once = true;
element.setTimeout = setTimeout;
element.timing = setTimeout(statement, timeout);
}
} else {
// run once (no timeout specified)
element.reload_counter = Infinity;
web2py_ajax_page('get', action, null, target);
} }); }
function web2py_websocket(url,onmessage,onopen,onclose) {
if ("WebSocket" in window) {
var ws = new WebSocket(url);
ws.onopen = onopen?onopen:(function(){});
ws.onmessage = onmessage;
ws.onclose = onclose?onclose:(function(){});
return true; // supported
} else return false; // not supported
}
function web2py_calc_entropy(mystring) {
//calculate a simple entropy for a given string
var csets = new Array(
'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'0123456789', '!@#$\%^&*()', '~`-_=+[]{}\|;:\'",.<>?/',
'0123456789abcdefghijklmnopqrstuvwxyz');
var score = 0, other = {}, seen = {}, lastset = null, mystringlist = mystring.split('');
for (var i=0;i<mystringlist.length;i++) { // classify this character
var c = mystringlist[i], inset=5;
for(var j = 0; j<csets.length; j++)
if (csets[j].indexOf(c) != -1) {inset = j; break;}
//calculate effect of character on alphabet size
if(!(inset in seen)) {seen[inset] = 1;score += csets[inset].length;}
else if (!(c in other)) {score += 1;other[c] = 1;}
if (inset != lastset) {score += 1;lastset = inset;}
}
var entropy = mystring.length*Math.log(score)/0.6931471805599453;
return Math.round(entropy*100)/100
}
function web2py_validate_entropy(myfield, req_entropy) {
var validator = function () {
var v = (web2py_calc_entropy(myfield.val())||0)/req_entropy;
var r=0,g=0,b=0,rs=function(x){return Math.round(x*15).toString(16)};
if(v<=0.5) {r=1.0; g=2.0*v;}
else {r=(1.0-2.0*(Math.max(v,0)-0.5)); g=1.0;}
var color = '#'+rs(r)+rs(g)+rs(b);
myfield.css('background-color',color);
entropy_callback = myfield.data('entropy_callback');
if(entropy_callback) entropy_callback(v);
}
if(!myfield.hasClass('entropy_check')) myfield.on('keyup', validator).on('keydown', validator).addClass('entropy_check');
}
| JavaScript |
/*
(c) Copyrights 2007 - 2008
Original idea by by Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/
jQuery Plugin by Tzury Bar Yochay
tzury.by@gmail.com
http://evalinux.wordpress.com
http://facebook.com/profile.php?id=513676303
Project's sites:
http://code.google.com/p/js-hotkeys/
http://github.com/tzuryby/hotkeys/tree/master
License: same as jQuery license.
USAGE:
// simple usage
$(document).bind('keydown', 'Ctrl+c', function(){ alert('copy anyone?');});
// special options such as disableInIput
$(document).bind('keydown', {combi:'Ctrl+x', disableInInput: true} , function() {});
Note:
This plugin wraps the following jQuery methods: $.fn.find, $.fn.bind and $.fn.unbind
*/
(function (jQuery){
// keep reference to the original $.fn.bind and $.fn.unbind
jQuery.fn.__bind__ = jQuery.fn.bind;
jQuery.fn.__unbind__ = jQuery.fn.unbind;
jQuery.fn.__find__ = jQuery.fn.find;
var hotkeys = {
version: '0.7.8',
override: /keydown|keypress|keyup/g,
triggersMap: {},
specialKeys: { 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' },
shiftNums: { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&",
"8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<",
".":">", "/":"?", "\\":"|" },
newTrigger: function (type, combi, callback) {
// i.e. {'keyup': {'ctrl': {cb: callback, disableInInput: false}}}
var result = {};
result[type] = {};
result[type][combi] = {cb: callback, disableInInput: false};
return result;
}
};
// add firefox num pad char codes
if (jQuery.browser.mozilla){
hotkeys.specialKeys = jQuery.extend(hotkeys.specialKeys, { 96: '0', 97:'1', 98: '2', 99:
'3', 100: '4', 101: '5', 102: '6', 103: '7', 104: '8', 105: '9' });
}
// a wrapper around of $.fn.find
// see more at: http://groups.google.com/group/jquery-en/browse_thread/thread/18f9825e8d22f18d
jQuery.fn.find = function( selector ) {
this.query=selector;
return jQuery.fn.__find__.apply(this, arguments);
};
jQuery.fn.unbind = function (type, combi, fn){
if (jQuery.isFunction(combi)){
fn = combi;
combi = null;
}
if (combi && typeof combi === 'string'){
var selectorId = ((this.prevObject && this.prevObject.query) || (this[0].id && this[0].id) || this[0]).toString();
var hkTypes = type.split(' ');
for (var x=0; x<hkTypes.length; x++){
delete hotkeys.triggersMap[selectorId][hkTypes[x]][combi];
}
}
// call jQuery original unbind
return this.__unbind__(type, fn);
};
jQuery.fn.bind = function(type, data, fn){
// grab keyup,keydown,keypress
var handle = type.match(hotkeys.override);
if (jQuery.isFunction(data) || !handle){
// call jQuery.bind only
return this.__bind__(type, data, fn);
}
else{
// split the job
var result = null,
// pass the rest to the original $.fn.bind
pass2jq = jQuery.trim(type.replace(hotkeys.override, ''));
// see if there are other types, pass them to the original $.fn.bind
if (pass2jq){
// call original jQuery.bind()
result = this.__bind__(pass2jq, data, fn);
}
if (typeof data === "string"){
data = {'combi': data};
}
if(data.combi){
for (var x=0; x < handle.length; x++){
var eventType = handle[x];
var combi = data.combi.toLowerCase(),
trigger = hotkeys.newTrigger(eventType, combi, fn),
selectorId = ((this.prevObject && this.prevObject.query) || (this[0].id && this[0].id) || this[0]).toString();
//trigger[eventType][combi].propagate = data.propagate;
trigger[eventType][combi].disableInInput = data.disableInInput;
// first time selector is bounded
if (!hotkeys.triggersMap[selectorId]) {
hotkeys.triggersMap[selectorId] = trigger;
}
// first time selector is bounded with this type
else if (!hotkeys.triggersMap[selectorId][eventType]) {
hotkeys.triggersMap[selectorId][eventType] = trigger[eventType];
}
// make trigger point as array so more than one handler can be bound
var mapPoint = hotkeys.triggersMap[selectorId][eventType][combi];
if (!mapPoint){
hotkeys.triggersMap[selectorId][eventType][combi] = [trigger[eventType][combi]];
}
else if (mapPoint.constructor !== Array){
hotkeys.triggersMap[selectorId][eventType][combi] = [mapPoint];
}
else {
hotkeys.triggersMap[selectorId][eventType][combi][mapPoint.length] = trigger[eventType][combi];
}
// add attribute and call $.event.add per matched element
this.each(function(){
// jQuery wrapper for the current element
var jqElem = jQuery(this);
// element already associated with another collection
if (jqElem.attr('hkId') && jqElem.attr('hkId') !== selectorId){
selectorId = jqElem.attr('hkId') + ";" + selectorId;
}
jqElem.attr('hkId', selectorId);
});
result = this.__bind__(handle.join(' '), data, hotkeys.handler)
}
}
return result;
}
};
// work-around for opera and safari where (sometimes) the target is the element which was last
// clicked with the mouse and not the document event it would make sense to get the document
hotkeys.findElement = function (elem){
if (!jQuery(elem).attr('hkId')){
if (jQuery.browser.opera || jQuery.browser.safari){
while (!jQuery(elem).attr('hkId') && elem.parentNode){
elem = elem.parentNode;
}
}
}
return elem;
};
// the event handler
hotkeys.handler = function(event) {
var target = hotkeys.findElement(event.currentTarget),
jTarget = jQuery(target),
ids = jTarget.attr('hkId');
if(ids){
ids = ids.split(';');
var code = event.which,
type = event.type,
special = hotkeys.specialKeys[code],
// prevent f5 overlapping with 't' (or f4 with 's', etc.)
character = !special && String.fromCharCode(code).toLowerCase(),
shift = event.shiftKey,
ctrl = event.ctrlKey,
// patch for jquery 1.2.5 && 1.2.6 see more at:
// http://groups.google.com/group/jquery-en/browse_thread/thread/83e10b3bb1f1c32b
alt = event.altKey || event.originalEvent.altKey,
mapPoint = null;
for (var x=0; x < ids.length; x++){
if (hotkeys.triggersMap[ids[x]][type]){
mapPoint = hotkeys.triggersMap[ids[x]][type];
break;
}
}
//find by: id.type.combi.options
if (mapPoint){
var trigger;
// event type is associated with the hkId
if(!shift && !ctrl && !alt) { // No Modifiers
trigger = mapPoint[special] || (character && mapPoint[character]);
}
else{
// check combinations (alt|ctrl|shift+anything)
var modif = '';
if(alt) modif +='alt+';
if(ctrl) modif+= 'ctrl+';
if(shift) modif += 'shift+';
// modifiers + special keys or modifiers + character or modifiers + shift character or just shift character
trigger = mapPoint[modif+special];
if (!trigger){
if (character){
trigger = mapPoint[modif+character]
|| mapPoint[modif+hotkeys.shiftNums[character]]
// '$' can be triggered as 'Shift+4' or 'Shift+$' or just '$'
|| (modif === 'shift+' && mapPoint[hotkeys.shiftNums[character]]);
}
}
}
if (trigger){
var result = false;
for (var x=0; x < trigger.length; x++){
if(trigger[x].disableInInput){
// double check event.currentTarget and event.target
var elem = jQuery(event.target);
if (jTarget.is("input") || jTarget.is("textarea")
|| elem.is("input") || elem.is("textarea")) {
return true;
}
}
// call the registered callback function
result = result || trigger[x].cb.apply(this, [event]);
}
return result;
}
}
}
};
// place it under window so it can be extended and overridden by others
window.hotkeys = hotkeys;
return jQuery;
})(jQuery);
| JavaScript |
/**
Created and copyrighted by Massimo Di Pierro <massimo.dipierro@gmail.com>
(MIT license)
Example:
<script src="share.js"></script>
**/
jQuery(function(){
var script_source = jQuery('script[src*="share.js"]').attr('src');
var params = function(name,default_value) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(script_source);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '))||default_value;
}
var path = params('static','social');
var url = encodeURIComponent(window.location.href);
var host = window.location.hostname;
var title = escape(jQuery('title').text());
var twit = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var gplus = 'https://plus.google.com/share?url='+url;
var tbar = '<div id="socialdrawer"><span>Share<br/></span><div id="sicons"><a href="'+twit+'" id="twit" title="Share on twitter"><img src="'+path+'/twitter.png" alt="Share on Twitter" width="32" height="32" /></a><a href="'+facebook+'" id="facebook" title="Share on Facebook"><img src="'+path+'/facebook.png" alt="Share on facebook" width="32" height="32" /></a><a href="'+gplus+'" id="gplus" title="Share on Google Plus"><img src="'+path+'/gplus-32.png" alt="Share on Google Plus" width="32" height="32" /></a></div></div>';
// Add the share tool bar.
jQuery('body').append(tbar);
var st = jQuery('#socialdrawer');
st.css({'opacity':'.7','z-index':'3000','background':'#FFF','border':'solid 1px #666','border-width':' 1px 0 0 1px','height':'20px','width':'40px','position':'fixed','bottom':'0','right':'0','padding':'2px 5px','overflow':'hidden','-webkit-border-top-left-radius':' 12px','-moz-border-radius-topleft':' 12px','border-top-left-radius':' 12px','-moz-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','-webkit-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)'});
jQuery('#socialdrawer a').css({'float':'left','width':'32px','margin':'3px 2px 2px 2px','padding':'0','cursor':'pointer'});
jQuery('#socialdrawer span').css({'float':'left','margin':'2px 3px','text-shadow':' 1px 1px 1px #FFF','color':'#444','font-size':'12px','line-height':'1em'});
jQuery('#socialdrawer img').hide();
// hover
st.click(function(){
jQuery(this).animate({height:'40px', width:'160px', opacity: 0.95}, 300);
jQuery('#socialdrawer img').show();
});
//leave
st.mouseleave(function(){
st.animate({height:'20px', width: '40px', opacity: .7}, 300);
jQuery('#socialdrawer img').hide();
return false;
} );
});
| JavaScript |
/*
* MultiSelect v0.8
* Copyright (c) 2012 Louis Cuny
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
(function($){
var msMethods = {
'init' : function(options){
this.settings = {
disabledClass : 'disabled',
selectCallbackOnInit: false,
keepOrder : false
};
if(options) {
this.settings = $.extend(this.settings, options);
}
var multiSelects = this;
multiSelects.css('position', 'absolute').css('left', '-9999px');
return multiSelects.each(function(){
var ms = $(this);
if (ms.next('.ms-container').length == 0){
ms.attr('id', ms.attr('id') ? ms.attr('id') : 'ms-'+Math.ceil(Math.random()*1000));
var container = $('<div id="ms-'+ms.attr('id')+'" class="ms-container"></div>'),
selectableContainer = $('<div class="ms-selectable"></div>'),
selectedContainer = $('<div class="ms-selection"></div>'),
selectableUl = $('<ul class="ms-list"></ul>'),
selectedUl = $('<ul class="ms-list"></ul>');
ms.data('settings', multiSelects.settings);
var optgroupLabel = null,
optgroupId = null,
optgroupCpt = 0,
scroll = 0;
ms.find('optgroup,option').each(function(){
if ($(this).is('optgroup')){
optgroupLabel = $(this).attr('label');
optgroupId = 'ms-'+ms.attr('id')+'-optgroup-'+optgroupCpt;
selectableUl.append($('<li class="ms-optgroup-container" id="'+
optgroupId+'"><ul class="ms-optgroup"><li class="ms-optgroup-label">'+
optgroupLabel+'</li></ul></li>'));
optgroupCpt++;
} else {
var klass = $(this).attr('class') ? ' '+$(this).attr('class') : '';
var selectableLi = $('<li class="ms-elem-selectable'+klass+'" ms-value="'+$(this).val()+'">'+$(this).text()+'</li>');
if ($(this).attr('title'))
selectableLi.attr('title', $(this).attr('title'));
if ($(this).attr('disabled') || ms.attr('disabled')){
selectableLi.attr('disabled', 'disabled');
selectableLi.addClass(multiSelects.settings.disabledClass);
}
selectableLi.click(function(){
ms.multiSelect('select', $(this).attr('ms-value'));
});
var container = optgroupId ? selectableUl.children('#'+optgroupId).find('ul').first() : selectableUl;
container.append(selectableLi);
}
});
if (multiSelects.settings.selectableHeader){
selectableContainer.append(multiSelects.settings.selectableHeader);
}
selectableContainer.append(selectableUl);
if (multiSelects.settings.selectedHeader){
selectedContainer.append(multiSelects.settings.selectedHeader);
}
selectedContainer.append(selectedUl);
container.append(selectableContainer);
container.append(selectedContainer);
ms.after(container);
ms.find('option:selected').each(function(){
ms.multiSelect('select', $(this).val(), 'init');
});
$('.ms-elem-selectable', selectableUl).on('mouseenter', function(){
$('li', container).removeClass('ms-hover');
$(this).addClass('ms-hover');
}).on('mouseout', function(){
$('li', container).removeClass('ms-hover');
});
selectableUl.on('focusin', function(){
$(this).addClass('ms-focus');
selectedUl.focusout();
}).on('focusout', function(){
$(this).removeClass('ms-focus');
$('li', container).removeClass('ms-hover');
});
selectedUl.on('focusin', function(){
$(this).addClass('ms-focus');
}).on('focusout', function(){
$(this).removeClass('ms-focus');
$('li', container).removeClass('ms-hover');
});
ms.on('focusin', function(){
selectableUl.focus();
}).on('focusout', function(){
selectableUl.removeClass('ms-focus');
selectedUl.removeClass('ms-focus');
});
ms.onKeyDown = function(e, keyContainer){
var selectables = $('.'+keyContainer+' li:visible:not(.ms-optgroup-label, .ms-optgroup-container)', container),
selectablesLength = selectables.length,
selectableFocused = $('.'+keyContainer+' li.ms-hover', container),
selectableFocusedIndex = $('.'+keyContainer+' li:visible:not(.ms-optgroup-label, .ms-optgroup-container)', container).index(selectableFocused),
liHeight = selectables.first().outerHeight(),
numberOfItemsDisplayed = Math.ceil(container.outerHeight()/liHeight),
scrollStart = Math.ceil(numberOfItemsDisplayed/4);
selectables.removeClass('ms-hover');
if (e.keyCode == 32){ // space
var method = keyContainer == 'ms-selectable' ? 'select' : 'deselect';
ms.multiSelect(method, selectableFocused.first().attr('ms-value'));
} else if (e.keyCode == 40){ // Down
var nextIndex = (selectableFocusedIndex+1 != selectablesLength) ? selectableFocusedIndex+1 : 0,
nextSelectableLi = selectables.eq(nextIndex);
nextSelectableLi.addClass('ms-hover');
if (nextIndex > scrollStart){
scroll += liHeight;
} else if (nextIndex == 0){
scroll = 0;
}
$('.'+keyContainer+' ul', container).scrollTop(scroll);
} else if (e.keyCode == 38){ // Up
var prevIndex = (selectableFocusedIndex-1 >= 0) ? selectableFocusedIndex-1 : selectablesLength-1,
prevSelectableLi = selectables.eq(prevIndex);
selectables.removeClass('ms-hover');
prevSelectableLi.addClass('ms-hover');
if (selectablesLength-prevIndex+1 < scrollStart){
scroll = liHeight*(selectablesLength-scrollStart);
} else {
scroll -= liHeight;
}
$('.'+keyContainer+' ul', container).scrollTop(scroll);
} else if (e.keyCode == 37 || e.keyCode == 39){ // Right and Left
if (selectableUl.hasClass('ms-focus')){
selectableUl.focusout();
selectedUl.focusin();
} else {
selectableUl.focusin();
selectedUl.focusout();
}
}
}
ms.on('keydown', function(e){
if (ms.is(':focus')){
var keyContainer = selectableUl.hasClass('ms-focus') ? 'ms-selectable' : 'ms-selection';
ms.onKeyDown(e, keyContainer);
}
});
}
});
},
'refresh' : function() {
$("#ms-"+$(this).attr("id")).remove();
$(this).multiSelect("init", $(this).data("settings"));
},
'select' : function(value, method){
var ms = this,
selectedOption = ms.find('option[value="'+value +'"]'),
text = selectedOption.text(),
klass = selectedOption.attr('class'),
titleAttr = selectedOption.attr('title');
var selectedLi = $('<li class="ms-elem-selected'+(klass ? ' '+klass : '')+'" ms-value="'+value+'">'+text+'</li>'),
selectableUl = $('#ms-'+ms.attr('id')+' .ms-selectable ul'),
selectedUl = $('#ms-'+ms.attr('id')+' .ms-selection ul'),
selectableLi = selectableUl.children('li[ms-value="'+value+'"]'),
haveToSelect = null;
if (method == 'init'){
haveToSelect = !selectableLi.hasClass(ms.data('settings').disabledClass) && selectedOption.prop('selected');
} else {
haveToSelect = !selectableLi.hasClass(ms.data('settings').disabledClass);
ms.focus();
}
if (haveToSelect && selectedUl.children('li[ms-value="'+value+'"]').length == 0){
var parentOptgroup = selectableLi.parent('.ms-optgroup');
if (parentOptgroup.length > 0)
if (parentOptgroup.children('.ms-elem-selectable:not(:hidden)').length == 1)
parentOptgroup.children('.ms-optgroup-label').hide();
selectableLi.addClass('ms-selected');
selectableLi.hide();
selectedOption.prop('selected', true);
if(titleAttr){
selectedLi.attr('title', titleAttr)
}
if (selectableLi.hasClass(ms.data('settings').disabledClass)){
selectedLi.addClass(ms.data('settings').disabledClass);
} else {
selectedLi.click(function(){
ms.multiSelect('deselect', $(this).attr('ms-value'));
});
}
var selectedUlLis = selectedUl.children('.ms-elem-selected');
if (method != 'init' && ms.data('settings').keepOrder && selectedUlLis.length > 0) {
var getIndexOf = function(value) {
elems = selectableUl.children('.ms-elem-selectable');
return(elems.index(elems.closest('[ms-value="'+value+'"]')));
}
var index = getIndexOf(selectedLi.attr('ms-value'));
if (index == 0)
selectedUl.prepend(selectedLi);
else {
for (i = index - 1; i >= 0; i--){
if (selectedUlLis[i] && getIndexOf($(selectedUlLis[i]).attr('ms-value')) < index) {
$(selectedUlLis[i]).after(selectedLi);
break;
} else if (i == 0) {
$(selectedUlLis[i]).before(selectedLi);
}
}
}
} else {
selectedUl.append(selectedLi);
}
selectedLi.on('mouseenter', function(){
$('li', selectedUl).removeClass('ms-hover');
$(this).addClass('ms-hover');
}).on('mouseout', function(){
$('li', selectedUl).removeClass('ms-hover');
});
if (method == "select_all" && parentOptgroup.children('.ms-elem-selectable').length > 0){
parentOptgroup.children('.ms-optgroup-label').hide();
}
if(method != 'init' || ms.data('settings').selectCallbackOnInit){
ms.trigger('change');
selectedUl.trigger('change');
selectableUl.trigger('change');
if (typeof ms.data('settings').afterSelect == 'function' &&
(method != 'init' || ms.data('settings').selectCallbackOnInit)) {
ms.data('settings').afterSelect.call(this, value, text);
}
}
}
},
'deselect' : function(value){
var ms = this,
selectedUl = $('#ms-'+ms.attr('id')+' .ms-selection ul'),
selectedOption = ms.find('option[value="'+value +'"]'),
selectedLi = selectedUl.children('li[ms-value="'+value+'"]');
if(selectedLi){
selectedUl.focusin();
var selectableUl = $('#ms-'+ms.attr('id')+' .ms-selectable ul'),
selectedUl = $('#ms-'+ms.attr('id')+' .ms-selection ul'),
selectableLi = selectableUl.children('li[ms-value="'+value+'"]'),
selectedLi = selectedUl.children('li[ms-value="'+value+'"]');
var parentOptgroup = selectableLi.parent('.ms-optgroup');
if (parentOptgroup.length > 0){
parentOptgroup.children('.ms-optgroup-label').addClass('ms-collapse').show();
parentOptgroup.children('.ms-elem-selectable:not(.ms-selected)').show();
}
selectedOption.prop('selected', false);
selectableLi.show();
selectableLi.removeClass('ms-selected');
selectedLi.remove();
selectedUl.trigger('change');
selectableUl.trigger('change');
ms.trigger('change');
if (typeof ms.data('settings').afterDeselect == 'function') {
ms.data('settings').afterDeselect.call(this, value, selectedLi.text());
}
}
},
'select_all' : function(visible){
var ms = this,
selectableUl = $('#ms-'+ms.attr('id')+' .ms-selectable ul');
ms.find("option:not(:selected)").each(function(){
var value = $(this).val();
if (visible){
var selectableLi = selectableUl.children('li[ms-value="'+value+'"]');
if (selectableLi.filter(':visible').length > 0){
ms.multiSelect('select', value, 'select_all');
}
} else {
ms.multiSelect('select', value, 'select_all');
}
});
},
'deselect_all' : function(){
var ms = this,
selectedUl = $('#ms-'+ms.attr('id')+' .ms-selection ul');
ms.find("option:selected").each(function(){
ms.multiSelect('deselect', $(this).val(), 'deselect_all');
});
}
};
$.fn.multiSelect = function(method){
if ( msMethods[method] ) {
return msMethods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return msMethods.init.apply( this, arguments );
} else {
if(console.log) console.log( 'Method ' + method + ' does not exist on jquery.multiSelect' );
}
return false;
};
})(jQuery);
| JavaScript |
// this code improves bootstrap menus and adds dropdown support
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(jQuery(this).parent().find('ul').length)
jQuery(this).attr({'class':'dropdown-toggle','data-toggle':'dropdown'}).append('<b class="caret"></b>');
});
jQuery('.nav li li').each(function(){
if(jQuery(this).find('ul').length)
jQuery(this).addClass('dropdown-submenu');
});
function adjust_height_of_collapsed_nav() {
var cn = jQuery('div.collapse');
if (cn.get(0)) {
var cnh = cn.get(0).style.height;
if (cnh>'0px'){
cn.css('height','auto');
}
}
}
function hoverMenu(){
jQuery('ul.nav a.dropdown-toggle').parent().hover(function(){
adjust_height_of_collapsed_nav();
mi = jQuery(this).addClass('open');
mi.children('.dropdown-menu').stop(true, true).delay(200).fadeIn(400);
}, function(){
mi = jQuery(this);
mi.children('.dropdown-menu').stop(true, true).delay(200).fadeOut(function(){mi.removeClass('open')});
});
}
hoverMenu(); // first page load
jQuery(window).resize(hoverMenu); // on resize event
jQuery('ul.nav li.dropdown a').click(function(){window.location=jQuery(this).attr('href');});
// make all buttons bootstrap buttons
jQuery('button, form input[type="submit"], form input[type="button"]').addClass('btn');
}); | JavaScript |
function popup(url) {
newwindow=window.open(url,'name','height=400,width=600');
if (window.focus) newwindow.focus();
return false;
}
function collapse(id) { jQuery('#'+id).slideToggle(); }
function fade(id,value) { if(value>0) jQuery('#'+id).hide().fadeIn('slow'); else jQuery('#'+id).show().fadeOut('slow'); }
function ajax(u,s,t) {
query = '';
if (typeof s == "string") {
d = jQuery(s).serialize();
if(d){ query = d; }
} else {
pcs = [];
if (s != null && s != undefined) for(i=0; i<s.length; i++) {
q = jQuery("[name="+s[i]+"]").serialize();
if(q){pcs.push(q);}
}
if (pcs.length>0){query = pcs.join("&");}
}
jQuery.ajax({type: "POST", url: u, data: query, success: function(msg) { if(t) { if(t==':eval') eval(msg); else if(typeof t=='string') jQuery("#"+t).html(msg); else t(msg); } } });
}
String.prototype.reverse = function () { return this.split('').reverse().join('');};
function web2py_ajax_fields(target) {
var date_format = (typeof w2p_ajax_date_format != 'undefined') ? w2p_ajax_date_format : "%Y-%m-%d";
var datetime_format = (typeof w2p_ajax_datetime_format != 'undefined') ? w2p_ajax_datetime_format : "%Y-%m-%d %H:%M:%S";
jQuery("input.date",target).each(function() {Calendar.setup({inputField:this, ifFormat:date_format, showsTime:false });});
jQuery("input.datetime",target).each(function() {Calendar.setup({inputField:this, ifFormat:datetime_format, showsTime: true, timeFormat: "24" });});
jQuery("input.time",target).each(function(){jQuery(this).timeEntry();});
};
function web2py_ajax_init(target) {
jQuery('.hidden', target).hide();
jQuery('.error', target).hide().slideDown('slow');
web2py_ajax_fields(target);
};
function web2py_event_handlers() {
var doc = jQuery(document)
doc.on('click', '.flash', function(e){var t=jQuery(this); if(t.css('top')=='0px') t.slideUp('slow'); else t.fadeOut(); e.preventDefault();});
doc.on('keyup', 'input.integer', function(){this.value=this.value.reverse().replace(/[^0-9\-]|\-(?=.)/g,'').reverse();});
doc.on('keyup', 'input.double, input.decimal', function(){this.value=this.value.reverse().replace(/[^0-9\-\.,]|[\-](?=.)|[\.,](?=[0-9]*[\.,])/g,'').reverse();});
var confirm_message = (typeof w2p_ajax_confirm_message != 'undefined') ? w2p_ajax_confirm_message : "Are you sure you want to delete this object?";
doc.on('click', "input[type='checkbox'].delete", function(){if(this.checked) if(!confirm(confirm_message)) this.checked=false;});
doc.ajaxSuccess(function(e, xhr) {
var redirect=xhr.getResponseHeader('web2py-redirect-location');
var command=xhr.getResponseHeader('web2py-component-command');
var flash=xhr.getResponseHeader('web2py-component-flash');
if (redirect !== null) {
window.location = redirect;
};
if(command !== null){
eval(decodeURIComponent(command));
}
if(flash) {
jQuery('.flash')
.html(decodeURIComponent(flash))
.append('<span id="closeflash">×</span>')
.slideDown();
}
});
doc.ajaxError(function(e, xhr, settings, exception) {
doc.off('click', '.flash')
switch(xhr.status){
case 500:
$('.flash').html(ajax_error_500).slideDown();
}
});
};
jQuery(function() {
var flash = jQuery('.flash');
flash.hide();
if(flash.html()) flash.append('<span id="closeflash">×</span>').slideDown();
web2py_ajax_init(document);
web2py_event_handlers();
});
function web2py_trap_form(action,target) {
jQuery('#'+target+' form').each(function(i){
var form=jQuery(this);
if(!form.hasClass('no_trap'))
form.submit(function(e){
jQuery('.flash').hide().html('');
web2py_ajax_page('post',action,form.serialize(),target);
e.preventDefault();
});
});
}
function web2py_trap_link(target) {
jQuery('#'+target+' a.w2p_trap').each(function(i){
var link=jQuery(this);
link.click(function(e) {
jQuery('.flash').hide().html('');
web2py_ajax_page('get',link.attr('href'),[],target);
e.preventDefault();
});
});
}
function web2py_ajax_page(method, action, data, target) {
jQuery.ajax({'type':method, 'url':action, 'data':data,
'beforeSend':function(xhr) {
xhr.setRequestHeader('web2py-component-location', document.location);
xhr.setRequestHeader('web2py-component-element', target);},
'complete':function(xhr,text){
var html=xhr.responseText;
var content=xhr.getResponseHeader('web2py-component-content');
var t = jQuery('#'+target);
if(content=='prepend') t.prepend(html);
else if(content=='append') t.append(html);
else if(content!='hide') t.html(html);
web2py_trap_form(action,target);
web2py_trap_link(target);
web2py_ajax_init('#'+target);
}
});
}
function web2py_component(action, target, timeout, times){
jQuery(function(){
var jelement = jQuery("#" + target);
var element = jelement.get(0);
var statement = "jQuery('#" + target + "').get(0).reload();";
element.reload = function (){
// Continue if times is Infinity or
// the times limit is not reached
if (this.reload_check()){
web2py_ajax_page('get', action, null, target);} }; // reload
// Method to check timing limit
element.reload_check = function (){
if (jelement.hasClass('w2p_component_stop')) {clearInterval(this.timing);return false;}
if (this.reload_counter == Infinity){return true;}
else {
if (!isNaN(this.reload_counter)){
this.reload_counter -= 1;
if (this.reload_counter < 0){
if (!this.run_once){
clearInterval(this.timing);
return false;
}
}
else{return true;}
} }
return false;}; // reload check
if (!isNaN(timeout)){
element.timeout = timeout;
element.reload_counter = times;
if (times > 1){
// Multiple or infinite reload
// Run first iteration
web2py_ajax_page('get', action, null, target);
element.run_once = false;
element.timing = setInterval(statement, timeout);
element.reload_counter -= 1;
}
else if (times == 1) {
// Run once with timeout
element.run_once = true;
element.setTimeout = setTimeout;
element.timing = setTimeout(statement, timeout);
}
} else {
// run once (no timeout specified)
element.reload_counter = Infinity;
web2py_ajax_page('get', action, null, target);
} }); }
function web2py_websocket(url,onmessage,onopen,onclose) {
if ("WebSocket" in window) {
var ws = new WebSocket(url);
ws.onopen = onopen?onopen:(function(){});
ws.onmessage = onmessage;
ws.onclose = onclose?onclose:(function(){});
return true; // supported
} else return false; // not supported
}
function web2py_calc_entropy(mystring) {
//calculate a simple entropy for a given string
var csets = new Array(
'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'0123456789', '!@#$\%^&*()', '~`-_=+[]{}\|;:\'",.<>?/',
'0123456789abcdefghijklmnopqrstuvwxyz');
var score = 0, other = {}, seen = {}, lastset = null, mystringlist = mystring.split('');
for (var i=0;i<mystringlist.length;i++) { // classify this character
var c = mystringlist[i], inset=5;
for(var j = 0; j<csets.length; j++)
if (csets[j].indexOf(c) != -1) {inset = j; break;}
//calculate effect of character on alphabet size
if(!(inset in seen)) {seen[inset] = 1;score += csets[inset].length;}
else if (!(c in other)) {score += 1;other[c] = 1;}
if (inset != lastset) {score += 1;lastset = inset;}
}
var entropy = mystring.length*Math.log(score)/0.6931471805599453;
return Math.round(entropy*100)/100
}
function web2py_validate_entropy(myfield, req_entropy) {
var validator = function () {
var v = (web2py_calc_entropy(myfield.val())||0)/req_entropy;
var r=0,g=0,b=0,rs=function(x){return Math.round(x*15).toString(16)};
if(v<=0.5) {r=1.0; g=2.0*v;}
else {r=(1.0-2.0*(Math.max(v,0)-0.5)); g=1.0;}
var color = '#'+rs(r)+rs(g)+rs(b);
myfield.css('background-color',color);
entropy_callback = myfield.data('entropy_callback');
if(entropy_callback) entropy_callback(v);
}
if(!myfield.hasClass('entropy_check')) myfield.on('keyup', validator).on('keydown', validator).addClass('entropy_check');
}
| JavaScript |
/**
Created and copyrighted by Massimo Di Pierro <massimo.dipierro@gmail.com>
(MIT license)
Example:
<script src="share.js"></script>
**/
jQuery(function(){
var script_source = jQuery('script[src*="share.js"]').attr('src');
var params = function(name,default_value) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(script_source);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '))||default_value;
}
var path = params('static','social');
var url = encodeURIComponent(window.location.href);
var host = window.location.hostname;
var title = escape(jQuery('title').text());
var twit = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var gplus = 'https://plus.google.com/share?url='+url;
var tbar = '<div id="socialdrawer"><span>Share<br/></span><div id="sicons"><a href="'+twit+'" id="twit" title="Share on twitter"><img src="'+path+'/twitter.png" alt="Share on Twitter" width="32" height="32" /></a><a href="'+facebook+'" id="facebook" title="Share on Facebook"><img src="'+path+'/facebook.png" alt="Share on facebook" width="32" height="32" /></a><a href="'+gplus+'" id="gplus" title="Share on Google Plus"><img src="'+path+'/gplus-32.png" alt="Share on Google Plus" width="32" height="32" /></a></div></div>';
// Add the share tool bar.
jQuery('body').append(tbar);
var st = jQuery('#socialdrawer');
st.css({'opacity':'.7','z-index':'3000','background':'#FFF','border':'solid 1px #666','border-width':' 1px 0 0 1px','height':'20px','width':'40px','position':'fixed','bottom':'0','right':'0','padding':'2px 5px','overflow':'hidden','-webkit-border-top-left-radius':' 12px','-moz-border-radius-topleft':' 12px','border-top-left-radius':' 12px','-moz-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','-webkit-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)'});
jQuery('#socialdrawer a').css({'float':'left','width':'32px','margin':'3px 2px 2px 2px','padding':'0','cursor':'pointer'});
jQuery('#socialdrawer span').css({'float':'left','margin':'2px 3px','text-shadow':' 1px 1px 1px #FFF','color':'#444','font-size':'12px','line-height':'1em'});
jQuery('#socialdrawer img').hide();
// hover
st.click(function(){
jQuery(this).animate({height:'40px', width:'160px', opacity: 0.95}, 300);
jQuery('#socialdrawer img').show();
});
//leave
st.mouseleave(function(){
st.animate({height:'20px', width: '40px', opacity: .7}, 300);
jQuery('#socialdrawer img').hide();
return false;
} );
});
| JavaScript |
// this code improves bootstrap menus and adds dropdown support
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(jQuery(this).parent().find('ul').length)
jQuery(this).attr({'class':'dropdown-toggle','data-toggle':'dropdown'}).append('<b class="caret"></b>');
});
jQuery('.nav li li').each(function(){
if(jQuery(this).find('ul').length)
jQuery(this).addClass('dropdown-submenu');
});
function adjust_height_of_collapsed_nav() {
var cn = jQuery('div.collapse');
if (cn.get(0)) {
var cnh = cn.get(0).style.height;
if (cnh>'0px'){
cn.css('height','auto');
}
}
}
function hoverMenu(){
jQuery('ul.nav a.dropdown-toggle').parent().hover(function(){
adjust_height_of_collapsed_nav();
mi = jQuery(this).addClass('open');
mi.children('.dropdown-menu').stop(true, true).delay(200).fadeIn(400);
}, function(){
mi = jQuery(this);
mi.children('.dropdown-menu').stop(true, true).delay(200).fadeOut(function(){mi.removeClass('open')});
});
}
hoverMenu(); // first page load
jQuery(window).resize(hoverMenu); // on resize event
jQuery('ul.nav li.dropdown a').click(function(){window.location=jQuery(this).attr('href');});
// make all buttons bootstrap buttons
jQuery('button, form input[type="submit"], form input[type="button"]').addClass('btn');
}); | JavaScript |
function popup(url) {
newwindow=window.open(url,'name','height=400,width=600');
if (window.focus) newwindow.focus();
return false;
}
function collapse(id) { jQuery('#'+id).slideToggle(); }
function fade(id,value) { if(value>0) jQuery('#'+id).hide().fadeIn('slow'); else jQuery('#'+id).show().fadeOut('slow'); }
function ajax(u,s,t) {
query = '';
if (typeof s == "string") {
d = jQuery(s).serialize();
if(d){ query = d; }
} else {
pcs = [];
if (s != null && s != undefined) for(i=0; i<s.length; i++) {
q = jQuery("[name="+s[i]+"]").serialize();
if(q){pcs.push(q);}
}
if (pcs.length>0){query = pcs.join("&");}
}
jQuery.ajax({type: "POST", url: u, data: query, success: function(msg) { if(t) { if(t==':eval') eval(msg); else if(typeof t=='string') jQuery("#"+t).html(msg); else t(msg); } } });
}
String.prototype.reverse = function () { return this.split('').reverse().join('');};
function web2py_ajax_fields(target) {
var date_format = (typeof w2p_ajax_date_format != 'undefined') ? w2p_ajax_date_format : "%Y-%m-%d";
var datetime_format = (typeof w2p_ajax_datetime_format != 'undefined') ? w2p_ajax_datetime_format : "%Y-%m-%d %H:%M:%S";
jQuery("input.date",target).each(function() {Calendar.setup({inputField:this, ifFormat:date_format, showsTime:false });});
jQuery("input.datetime",target).each(function() {Calendar.setup({inputField:this, ifFormat:datetime_format, showsTime: true, timeFormat: "24" });});
jQuery("input.time",target).each(function(){jQuery(this).timeEntry();});
};
function web2py_ajax_init(target) {
jQuery('.hidden', target).hide();
jQuery('.error', target).hide().slideDown('slow');
web2py_ajax_fields(target);
};
function web2py_event_handlers() {
var doc = jQuery(document)
doc.on('click', '.flash', function(e){var t=jQuery(this); if(t.css('top')=='0px') t.slideUp('slow'); else t.fadeOut(); e.preventDefault();});
doc.on('keyup', 'input.integer', function(){this.value=this.value.reverse().replace(/[^0-9\-]|\-(?=.)/g,'').reverse();});
doc.on('keyup', 'input.double, input.decimal', function(){this.value=this.value.reverse().replace(/[^0-9\-\.,]|[\-](?=.)|[\.,](?=[0-9]*[\.,])/g,'').reverse();});
var confirm_message = (typeof w2p_ajax_confirm_message != 'undefined') ? w2p_ajax_confirm_message : "Are you sure you want to delete this object?";
doc.on('click', "input[type='checkbox'].delete", function(){if(this.checked) if(!confirm(confirm_message)) this.checked=false;});
doc.ajaxSuccess(function(e, xhr) {
var redirect=xhr.getResponseHeader('web2py-redirect-location');
var command=xhr.getResponseHeader('web2py-component-command');
var flash=xhr.getResponseHeader('web2py-component-flash');
if (redirect !== null) {
window.location = redirect;
};
if(command !== null){
eval(decodeURIComponent(command));
}
if(flash) {
jQuery('.flash')
.html(decodeURIComponent(flash))
.append('<span id="closeflash">×</span>')
.slideDown();
}
});
doc.ajaxError(function(e, xhr, settings, exception) {
doc.off('click', '.flash')
switch(xhr.status){
case 500:
$('.flash').html(ajax_error_500).slideDown();
}
});
};
jQuery(function() {
var flash = jQuery('.flash');
flash.hide();
if(flash.html()) flash.append('<span id="closeflash">×</span>').slideDown();
web2py_ajax_init(document);
web2py_event_handlers();
});
function web2py_trap_form(action,target) {
jQuery('#'+target+' form').each(function(i){
var form=jQuery(this);
if(!form.hasClass('no_trap'))
form.submit(function(e){
jQuery('.flash').hide().html('');
web2py_ajax_page('post',action,form.serialize(),target);
e.preventDefault();
});
});
}
function web2py_trap_link(target) {
jQuery('#'+target+' a.w2p_trap').each(function(i){
var link=jQuery(this);
link.click(function(e) {
jQuery('.flash').hide().html('');
web2py_ajax_page('get',link.attr('href'),[],target);
e.preventDefault();
});
});
}
function web2py_ajax_page(method, action, data, target) {
jQuery.ajax({'type':method, 'url':action, 'data':data,
'beforeSend':function(xhr) {
xhr.setRequestHeader('web2py-component-location', document.location);
xhr.setRequestHeader('web2py-component-element', target);},
'complete':function(xhr,text){
var html=xhr.responseText;
var content=xhr.getResponseHeader('web2py-component-content');
var t = jQuery('#'+target);
if(content=='prepend') t.prepend(html);
else if(content=='append') t.append(html);
else if(content!='hide') t.html(html);
web2py_trap_form(action,target);
web2py_trap_link(target);
web2py_ajax_init('#'+target);
}
});
}
function web2py_component(action, target, timeout, times){
jQuery(function(){
var jelement = jQuery("#" + target);
var element = jelement.get(0);
var statement = "jQuery('#" + target + "').get(0).reload();";
element.reload = function (){
// Continue if times is Infinity or
// the times limit is not reached
if (this.reload_check()){
web2py_ajax_page('get', action, null, target);} }; // reload
// Method to check timing limit
element.reload_check = function (){
if (jelement.hasClass('w2p_component_stop')) {clearInterval(this.timing);return false;}
if (this.reload_counter == Infinity){return true;}
else {
if (!isNaN(this.reload_counter)){
this.reload_counter -= 1;
if (this.reload_counter < 0){
if (!this.run_once){
clearInterval(this.timing);
return false;
}
}
else{return true;}
} }
return false;}; // reload check
if (!isNaN(timeout)){
element.timeout = timeout;
element.reload_counter = times;
if (times > 1){
// Multiple or infinite reload
// Run first iteration
web2py_ajax_page('get', action, null, target);
element.run_once = false;
element.timing = setInterval(statement, timeout);
element.reload_counter -= 1;
}
else if (times == 1) {
// Run once with timeout
element.run_once = true;
element.setTimeout = setTimeout;
element.timing = setTimeout(statement, timeout);
}
} else {
// run once (no timeout specified)
element.reload_counter = Infinity;
web2py_ajax_page('get', action, null, target);
} }); }
function web2py_websocket(url,onmessage,onopen,onclose) {
if ("WebSocket" in window) {
var ws = new WebSocket(url);
ws.onopen = onopen?onopen:(function(){});
ws.onmessage = onmessage;
ws.onclose = onclose?onclose:(function(){});
return true; // supported
} else return false; // not supported
}
function web2py_calc_entropy(mystring) {
//calculate a simple entropy for a given string
var csets = new Array(
'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'0123456789', '!@#$\%^&*()', '~`-_=+[]{}\|;:\'",.<>?/',
'0123456789abcdefghijklmnopqrstuvwxyz');
var score = 0, other = {}, seen = {}, lastset = null, mystringlist = mystring.split('');
for (var i=0;i<mystringlist.length;i++) { // classify this character
var c = mystringlist[i], inset=5;
for(var j = 0; j<csets.length; j++)
if (csets[j].indexOf(c) != -1) {inset = j; break;}
//calculate effect of character on alphabet size
if(!(inset in seen)) {seen[inset] = 1;score += csets[inset].length;}
else if (!(c in other)) {score += 1;other[c] = 1;}
if (inset != lastset) {score += 1;lastset = inset;}
}
var entropy = mystring.length*Math.log(score)/0.6931471805599453;
return Math.round(entropy*100)/100
}
function web2py_validate_entropy(myfield, req_entropy) {
var validator = function () {
var v = (web2py_calc_entropy(myfield.val())||0)/req_entropy;
var r=0,g=0,b=0,rs=function(x){return Math.round(x*15).toString(16)};
if(v<=0.5) {r=1.0; g=2.0*v;}
else {r=(1.0-2.0*(Math.max(v,0)-0.5)); g=1.0;}
var color = '#'+rs(r)+rs(g)+rs(b);
myfield.css('background-color',color);
entropy_callback = myfield.data('entropy_callback');
if(entropy_callback) entropy_callback(v);
}
if(!myfield.hasClass('entropy_check')) myfield.on('keyup', validator).on('keydown', validator).addClass('entropy_check');
}
| JavaScript |
/**
Created and copyrighted by Massimo Di Pierro <massimo.dipierro@gmail.com>
(MIT license)
Example:
<script src="share.js"></script>
**/
jQuery(function(){
var script_source = jQuery('script[src*="share.js"]').attr('src');
var params = function(name,default_value) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(script_source);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '))||default_value;
}
var path = params('static','social');
var url = encodeURIComponent(window.location.href);
var host = window.location.hostname;
var title = escape(jQuery('title').text());
var twit = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var gplus = 'https://plus.google.com/share?url='+url;
var tbar = '<div id="socialdrawer"><span>Share<br/></span><div id="sicons"><a href="'+twit+'" id="twit" title="Share on twitter"><img src="'+path+'/twitter.png" alt="Share on Twitter" width="32" height="32" /></a><a href="'+facebook+'" id="facebook" title="Share on Facebook"><img src="'+path+'/facebook.png" alt="Share on facebook" width="32" height="32" /></a><a href="'+gplus+'" id="gplus" title="Share on Google Plus"><img src="'+path+'/gplus-32.png" alt="Share on Google Plus" width="32" height="32" /></a></div></div>';
// Add the share tool bar.
jQuery('body').append(tbar);
var st = jQuery('#socialdrawer');
st.css({'opacity':'.7','z-index':'3000','background':'#FFF','border':'solid 1px #666','border-width':' 1px 0 0 1px','height':'20px','width':'40px','position':'fixed','bottom':'0','right':'0','padding':'2px 5px','overflow':'hidden','-webkit-border-top-left-radius':' 12px','-moz-border-radius-topleft':' 12px','border-top-left-radius':' 12px','-moz-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','-webkit-box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)','box-shadow':' -3px -3px 3px rgba(0,0,0,0.5)'});
jQuery('#socialdrawer a').css({'float':'left','width':'32px','margin':'3px 2px 2px 2px','padding':'0','cursor':'pointer'});
jQuery('#socialdrawer span').css({'float':'left','margin':'2px 3px','text-shadow':' 1px 1px 1px #FFF','color':'#444','font-size':'12px','line-height':'1em'});
jQuery('#socialdrawer img').hide();
// hover
st.click(function(){
jQuery(this).animate({height:'40px', width:'160px', opacity: 0.95}, 300);
jQuery('#socialdrawer img').show();
});
//leave
st.mouseleave(function(){
st.animate({height:'20px', width: '40px', opacity: .7}, 300);
jQuery('#socialdrawer img').hide();
return false;
} );
});
| JavaScript |
/**
* Initialize tinymce plugin
*/
// define base options for init tinymce
var tinymce_options = {
script_url : base_url + 'vendors/tiny_mce/tiny_mce.js',
plugins: 'table,advimage,advlink,insertdatetime,paste,noneditable,nonbreaking',
theme: 'advanced',
theme_advanced_toolbar_location: 'top',
theme_advanced_toolbar_align: 'left',
theme_advanced_buttons1: 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,cut,copy,paste,pastetext,pasteword,|,removeformat,|,link,unlink,image',
theme_advanced_buttons2: 'undo,redo,|,forecolor,backcolor,|,search,replace,|,bullist,numlist,|,outdent,indent,|,tablecontrols,|,sub,sup,charmap',
theme_advanced_buttons3: '',
theme_advanced_resizing: false,
forced_root_block: false,
force_p_newlines: false,
remove_linebreaks: false,
force_br_newlines: true,
remove_trailing_nbsp: false,
verify_html: true,
invalid_elements: 'script',
width: '100%',
convert_urls: false,
relative_urls: false,
language:"en",
compress: true,
media_strict: false,
entity_encoding:'raw'
};
$().ready(function(){
$('textarea.tinymce').tinymce(tinymce_options);
});
| JavaScript |
/**
* Uni-Form jQuery Plugin with Validation
*
* Provides form actions for use with the Uni-Form markup style
* This version adds additional support for client side validation
*
* Author: Ilija Studen for the purposes of Uni-Form
*
* Modified by Aris Karageorgos to use the parents function
*
* Modified by Toni Karlheinz to support input fields' text
* coloring and removal of their initial values on focus
*
* Modified by Jason Brumwell for optimization, addition
* of valid and invalid states and default data attribues
*
* Modified by LearningStation to add support for client
* side validation routines. The validation routines based on an
* open source library of unknown authorship.
*
* @see http://sprawsm.com/uni-form/
* @license MIT http://www.opensource.org/licenses/mit-license.php
*/
jQuery.fn.uniform = function(extended_settings) {
/**
* Self reference for closures
*
* @var object
*/
var self = this;
/**
* Object extending the defaults object
*
* @var object
*/
var settings = jQuery.extend(
jQuery.fn.uniform.defaults,
extended_settings
);
/**
* Language abstration string
*
* to extend, use a script tag to include a file from the localization folder
*
* @var object
*/
var i18n_strings = jQuery.fn.uniform.language;
/**
* Supported validators
*
* @var Object
*/
this.validators = {
/**
* Get the value for a validator that takes parameters
*
* @param string name
* @param string all classes on element
*
* @return mixed || null
*/
get_val : function(name, classes, default_value) {
var value = default_value;
classes = classes.split(' ');
for(var i = 0; i < classes.length; i++) {
if(classes[i] == name) {
if((classes[i + 1] != 'undefined') && ('val-' === classes[i + 1].substr(0,4))) {
value = parseInt(classes[i + 1].substr(4),10);
return value;
}
}
}
return value;
},
/**
* Value of field is not empty, whitespace will be counted as empty
*
* @param jQuery field
* @param string caption
*/
required : function(field, caption) {
if(field.is(':radio')) {
var name = field.attr('name');
if($("input[name=" + name + "]:checked").length) {
return true;
}
return i18n('req_radio', caption);
}
if(field.is(':checkbox')) {
var name = field.attr('name');
if(field.is(":checked")) {
return true;
}
return i18n('req_checkbox', caption);
}
if(jQuery.trim(field.val()) == '') {
return i18n('required', caption);
}
return true;
},
/**
* Value is shorter than allowed
*
* @param jQuery field
* @param sting caption
*/
validateMinLength : function(field, caption) {
var min_length = this.get_val('validateMinLength', field.attr('class'), 0);
if((min_length > 0) && (field.val().length < min_length)) {
return i18n('minlength', caption, min_length);
}
return true;
},
/**
* Value is less than min
*
* @param jQuery field
* @param sting caption
*/
validateMin : function(field, caption) {
var min_val = this.get_val('validateMin', field.attr('class'), 0);
if((parseInt(field.val(),10) < min_val)) {
return i18n('min', caption, min_val);
}
return true;
},
/**
* Value is longer than allowed
*
* @param jQuery field
* @param string caption
*/
validateMaxLength : function(field, caption) {
var max_length = this.get_val('validateMaxLength', field.attr('class'), 0);
if((max_length > 0) && (field.val().length > max_length)) {
return i18n('maxlength', caption, max_length);
}
return true;
},
/**
* Value is greater than max
*
* @param jQuery field
* @param sting caption
*/
validateMax : function(field, caption) {
var max_val = this.get_val('validateMax', field.attr('class'), 0);
if((parseInt(field.val(),10) > max_val)) {
return i18n('max', caption, max_val);
}
return true;
},
/**
* Element has same value as that of the target Element
*
* This does not use the val-{name} format, and instead
* is only the name of the element
*
* class="validateSameAs field_id"
*
* @param jQuery field
* @param string caption
*/
validateSameAs : function(field, caption) {
var classes = field.attr('class').split(' ');
var target_field_name = '';
for(var i = 0; i < classes.length; i++) {
if(classes[i] == 'validateSameAs') {
if(classes[i + 1] != 'undefined') {
target_field_name = classes[i + 1];
break;
}
}
}
if(target_field_name) {
var target_field = jQuery('input[name="' + target_field_name + '"]');
if(target_field.length > 0) {
if(target_field.val() != field.val()) {
var target_field_caption = target_field.closest('div.'+settings.holder_class).find('label').text().replace('*','');
return i18n('same_as', caption, target_field_caption);
}
}
}
return true;
},
/**
* Valid email address
*
* @param jQuery field
* @param string caption
*/
validateEmail : function(field, caption) {
if(field.val().match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
return true;
} else {
return i18n('email', caption);
}
},
/**
* Valid URL (http://,https://,ftp://)
*
* @param jQuery field
* @param string caption
*/
validateUrl : function(field, caption) {
if(field.val().match(/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i)) {
return true;
}
return i18n('url', caption);
},
/**
* Number is only valid value (integers and floats)
*
* @param jQuery field
* @param string caption
*/
validateNumber : function(field, caption) {
if(field.val().match(/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/) || field.val() == '') {
return true;
}
return i18n('number', caption);
},
/**
* Whole numbers are allowed
*
* @param jQuery field
* @param string caption
*/
validateInteger : function(field, caption) {
if(field.val().match(/(^-?\d\d*$)/) || field.val() == '') {
return true;
}
return i18n('integer', caption);
},
/**
* Letters only
*
* @param jQuery field
* @param string caption
*/
validateAlpha : function(field, caption) {
if(field.val().match(/^[a-zA-Z]+$/)) {
return true;
}
return i18n('alpha', caption);
},
/**
* Letters and numbers
*
* @param jQuery field
* @param string caption
*/
validateAlphaNum : function(field, caption) {
if(field.val().match(/\W/)) {
return i18n('alphanum', caption);
}
return true;
},
/**
* Simple phrases
*
* @param jQuery field
* @param string caption
*/
validatePhrase : function(field, caption) {
if((field.val() == '') || field.val().match(/^[\w\d\.\-_\(\)\*'# :,]+$/i)) {
return true;
}
return i18n('phrase', caption);
},
/**
* Phone number
*
* @param jQuery field
* @param string caption
*/
validatePhone : function(field, caption) {
phoneNumber = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
if(phoneNumber.test(field.val())) {
return true;
}
return i18n('phone', caption);
},
/**
* Date in MM/DD/YYYY format
*
* @param jQuery field
* @param string caption
*/
validateDate : function(field, caption) {
if(field.val().match('(1[0-9]|[1-9])/([1-3][0-9]|[1-9])/((19|20)[0-9][0-9]|[0-9][0-9])')) {
return true;
}
return i18n('date', caption);
},
/**
* Callback validator
*
* Lets you define your own validators. Usage:
*
* <input name="myinput" class="validateCallback my_callback" />
*
* This will result in UniForm searching for window.my_callback funciton and
* executing it with field and caption arguments. Sample implementation:
*
* window.my_callback = function(field, caption) {
* if(field.val() == '34') {
* return true;
* } else {
* return caption + ' value should be "34"';
* }
* }
*
* @param jQuery field
* @param caption
*/
validateCallback : function(field, caption) {
var classes = field.attr('class').split(' ');
var callback_function = '';
for(var i = 0; i < classes.length; i++) {
if(classes[i] == 'validateCallback') {
if(classes[i + 1] != 'undefined') {
callback_function = classes[i + 1];
break;
}
}
}
if(window[callback_function] != 'undefined' && (typeof window[callback_function] == 'function')) {
return window[callback_function](field, caption);
}
return i18n('callback', caption, callback_function);
}
};
/**
* Simple replacement for i18n + sprintf
*
* @param string language for for the local i18n object
* @param mixed substitution vars
*
* @return internationalized string
*/
var i18n = function(lang_key) {
var lang_string = i18n_strings[lang_key];
var bits = lang_string.split('%');
var out = bits[0];
var re = /^([ds])(.*)$/;
for (var i=1; i<bits.length; i++) {
p = re.exec(bits[i]);
if (!p || arguments[i] == null) continue;
if (p[1] == 'd') {
out += parseInt(arguments[i], 10);
} else if (p[1] == 's') {
out += arguments[i];
}
out += p[2];
}
return out;
};
/**
* Uni-Form form validation error
*
* @param string title of the form error
* @param array list of error messages to show
*
* @return false
*/
var showFormError = function(form, title, messages) {
if($('#errorMsg').length) {
$('#errorMsg').remove();
}
$message =
$('<div />')
.attr('id','errorMsg')
.html("<h3>" + title + "</h3>");
if(messages.length) {
$message.append($('<ol />'));
for(m in messages) {
$('ol', $message).append(
$('<li />').text(messages[m])
);
}
}
form.prepend($message);
$('html, body').animate({
scrollTop: form.offset().top
}, 500);
$('#errorMsg').slideDown();
return false;
};
var showFormSuccess = function(form, title) {
if($('#okMsg').length) {
$('#okMsg').remove();
}
$message =
$('<div />')
.attr('id','okMsg')
.html("<h3>" + title + "</h3>");
form.prepend($message);
$('html, body').animate({
scrollTop: form.offset().top
}, 500);
$('#okMsg').slideDown();
return false;
};
return this.each(function() {
var form = jQuery(this);
/**
* Set the results of form validation on the form element
*
* @param object $input jQuery form element
* @param bool valid true if the form value passed all validation
* @param string text validation error message to display
*
* @return null
*/
var validate = function($input,valid,text) {
var $p = $input.closest('div.' + settings.holder_class)
.andSelf()
.toggleClass(settings.invalid_class, !valid)
.toggleClass(settings.error_class, !valid)
.toggleClass(settings.valid_class, valid)
.find('p.formHint');
if (! valid && ! $p.data('info-text')) {
$p.data('info-text', $p.html());
}
else if (valid) {
text = $p.data('info-text');
}
if (text) {
$p.html(text);
}
};
/**
* Select form fields and attach the higlighter functionality
*
*/
form.find(settings.field_selector).each(function(){
var $input = $(this),
value = $input.val();
$input.data('default-color',$input.css('color'));
if (value === $input.data('default-value') || ! value) {
$input.not('select').css("color", settings.default_value_color);
$input.val($input.data('default-value'));
}
});
/**
* If we've set ask_on_leave we'll register a handler here
*
* We need to seriaze the form data, wait for a beforeunload,
* then serialize and compare for changes
*
* If they changed things, and haven't submitted, we'll let them
* know about it
*
*/
if(settings.ask_on_leave || form.hasClass('askOnLeave')) {
var initial_values = form.serialize();
$(window).bind("beforeunload", function(e) {
if((initial_values != form.serialize())
&& (settings.ask_on_leave || form.hasClass('askOnLeave'))
) {
return ($.isFunction(settings.on_leave_callback))
? settings.on_leave_callback(form)
: confirm(i18n('on_leave'));
}
});
}
/**
* Handle the submission of the form
*
* Tasks
* * Remove any default values from the form
* * If prevent_submit is set true, return false if
* there are outstanding errors in the form
*
* Todo
* * it would be novel to use prevent_submit to disable
* the submit button in the blur handler
*
* @return bool
*/
form.submit(function(){
// in the case of a previously failed submit, we'll remove our marker
form.removeClass('failedSubmit');
// remove the default values from the val() where they were being displayed
form.find(settings.field_selector).each(function(){
if($(this).val() === $(this).data('default-value')) { $(this).val(""); }
});
// traverse and revalidate making sure that we haven't missed any fields
// perhaps if a field was filled in before uniform was initialized
// or if blur failed to fire correctly
if(settings.prevent_submit || form.hasClass('preventSubmit')) {
// use blur to run the validators on each field
form.find(settings.field_selector).each(function(){
$(this).blur();
});
if (form
.find('.' + settings.invalid_class)
.add('.' + settings.error_class).length
) {
form.addClass('failedSubmit');
return ($.isFunction(settings.prevent_submit_callback))
? settings.prevent_submit_callback(form)
: showFormError(form, i18n('submit_msg'), [i18n('submit_help')]);
}
settings.ask_on_leave = false;
form.removeClass('askOnLeave');
return true;
}
// qUnit needs to run this function, and still prevent the submit
if(form.parents('#qunit-fixture').length) {
return false;
}
settings.ask_on_leave = false;
form.removeClass('askOnLeave');
return true;
});
/**
* Set the form focus class
*
* Remove any classes other than the focus class and hide the default label text
*
*/
form.delegate(settings.field_selector, 'focus', function() {
form.find('.' + settings.focused_class).removeClass(settings.focused_class);
var $input = $(this);
$input.parents().filter('.'+settings.holder_class+':first').addClass(settings.focused_class);
if($input.val() === $input.data('default-value')){
$input.val("");
}
$input.not('select').css('color',$input.data('default-color'));
});
/**
* Validate a form field on the blur event
*
* Search the classnames on the element for the names of
* validators, and run them as we find them
*
* If the validators fail, we trigger either 'success' or 'error' events
*
*/
form.delegate(settings.field_selector, 'blur', function() {
var $input = $(this);
var label = $(this)
.closest('div.' + settings.holder_class)
.find('label').text().replace('*','');
// remove focus from form element
form.find('.' + settings.focused_class).removeClass(settings.focused_class);
// (if empty or equal to default value) AND not required
if(($input.val() === "" || $input.val() === $input.data('default-value'))
&& !$input.hasClass('required')
){
$input.not('select').css("color",settings.default_value_color);
$input.val($input.data('default-value'));
return;
}
// run the validation and if they all pass, we mark the color and move on
var has_validation = false;
for(validator in self.validators) {
if($input.hasClass(validator)){
has_validation = true;
var validation_result = self.validators[validator]($input, label);
if(typeof(validation_result) == 'string') {
$input.trigger('error', validation_result);
return;
}
}
}
// if it had validation and we didn't return above,
// then all validation passed
if (has_validation) {
$input.trigger('success');
}
// return the color to the default
$input.css('color', $input.data('default-color'));
return;
});
/**
* Handle a validation error in the form element
*
* This will set the field to have the error marker
* and update the warning text
*
* @param event e
* @param string validation message
*/
form.delegate(settings.field_selector,'error',function(e,text) {
validate($(this), false, text);
});
/**
* Handle a succesful validation in the form element
*
* Remove any error messages and set the validation
* marker to be success
*
* @param event e
* @param string unused
*/
form.delegate(settings.field_selector,'success',function(e,text) {
validate($(this), true);
});
});
};
/**
* Internationalized language strings for validation messages
*/
jQuery.fn.uniform.language = {
required : '%s is required',
req_radio : 'Please make a selection',
req_checkbox : 'You must select this checkbox to continue',
minlength : '%s should be at least %d characters long',
min : '%s should be greater than or equal to %d',
maxlength : '%s should not be longer than %d characters',
max : '%s should be less than or equal to %d',
same_as : '%s is expected to be same as %s',
email : '%s is not a valid email address',
url : '%s is not a valid URL',
number : '%s needs to be a number',
integer : '%s needs to be a whole number',
alpha : '%s should contain only letters (without special characters or numbers)',
alphanum : '%s should contain only numbers and letters (without special characters)',
phrase : '%s should contain only alphabetic characters, numbers, spaces, and the following: . , - _ () * # :',
phone : '%s should be a phone number',
date : '%s should be a date (mm/dd/yyyy)',
callback : 'Failed to validate %s field. Validator function (%s) is not defined!',
on_leave : 'Are you sure you want to leave this page without saving this form?',
submit_msg : 'Sorry, this form needs corrections.',
submit_help : 'Please see the items marked below.',
submit_success: 'Thank you, this form has been sent.'
};
/**
* See the validation.md file for more information about these options
*/
jQuery.fn.uniform.defaults = {
prevent_submit : false,
prevent_submit_callback : false,
ask_on_leave : false,
on_leave_callback : false,
valid_class : 'valid',
invalid_class : 'invalid',
error_class : 'error',
focused_class : 'focused',
holder_class : 'ctrlHolder',
field_selector : 'input, textarea, select',
default_value_color : "#AFAFAF"
};
| JavaScript |
/*
* jQuery Nivo Slider v2.5.2
* http://nivo.dev7studios.com
*
* Copyright 2011, Gilbert Pellegrom
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* March 2010
*/
(function($) {
var NivoSlider = function(element, options){
//Defaults are below
var settings = $.extend({}, $.fn.nivoSlider.defaults, options);
//Useful variables. Play carefully.
var vars = {
currentSlide: 0,
currentImage: '',
totalSlides: 0,
randAnim: '',
running: false,
paused: false,
stop: false
};
//Get this slider
var slider = $(element);
slider.data('nivo:vars', vars);
slider.css('position','relative');
slider.addClass('nivoSlider');
//Find our slider children
var kids = slider.children();
kids.each(function() {
var child = $(this);
var link = '';
if(!child.is('img')){
if(child.is('a')){
child.addClass('nivo-imageLink');
link = child;
}
child = child.find('img:first');
}
//Get img width & height
var childWidth = child.width();
if(childWidth == 0) childWidth = child.attr('width');
var childHeight = child.height();
if(childHeight == 0) childHeight = child.attr('height');
//Resize the slider
if(childWidth > slider.width()){
slider.width(childWidth);
}
if(childHeight > slider.height()){
slider.height(childHeight);
}
if(link != ''){
link.css('display','none');
}
child.css('display','none');
vars.totalSlides++;
});
//Set startSlide
if(settings.startSlide > 0){
if(settings.startSlide >= vars.totalSlides) settings.startSlide = vars.totalSlides - 1;
vars.currentSlide = settings.startSlide;
}
//Get initial image
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
//Show initial link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
//Set first background
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
//Create caption
slider.append(
$('<div class="nivo-caption"><p></p></div>').css({ display:'none', opacity:settings.captionOpacity })
);
// Process caption function
var processCaption = function(settings){
var nivoCaption = $('.nivo-caption', slider);
if(vars.currentImage.attr('title') != '' && vars.currentImage.attr('title') != undefined){
var title = vars.currentImage.attr('title');
if(title.substr(0,1) == '#') title = $(title).html();
if(nivoCaption.css('display') == 'block'){
nivoCaption.find('p').fadeOut(settings.animSpeed, function(){
$(this).html(title);
$(this).fadeIn(settings.animSpeed);
});
} else {
nivoCaption.find('p').html(title);
}
nivoCaption.fadeIn(settings.animSpeed);
} else {
nivoCaption.fadeOut(settings.animSpeed);
}
}
//Process initial caption
processCaption(settings);
//In the words of Super Mario "let's a go!"
var timer = 0;
if(!settings.manualAdvance && kids.length > 1){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
//Add Direction nav
if(settings.directionNav){
slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+ settings.prevText +'</a><a class="nivo-nextNav">'+ settings.nextText +'</a></div>');
//Hide Direction nav
if(settings.directionNavHide){
$('.nivo-directionNav', slider).hide();
slider.hover(function(){
$('.nivo-directionNav', slider).show();
}, function(){
$('.nivo-directionNav', slider).hide();
});
}
$('a.nivo-prevNav', slider).live('click', function(){
if(vars.running) return false;
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
$('a.nivo-nextNav', slider).live('click', function(){
if(vars.running) return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
});
}
//Add Control nav
if(settings.controlNav){
var nivoControl = $('<div class="nivo-controlNav"></div>');
slider.append(nivoControl);
for(var i = 0; i < kids.length; i++){
if(settings.controlNavThumbs){
var child = kids.eq(i);
if(!child.is('img')){
child = child.find('img:first');
}
if (settings.controlNavThumbsFromRel) {
nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('rel') + '" alt="" /></a>');
} else {
nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('src').replace(settings.controlNavThumbsSearch, settings.controlNavThumbsReplace) +'" alt="" /></a>');
}
} else {
nivoControl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>');
}
}
//Set initial active link
$('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active');
$('.nivo-controlNav a', slider).live('click', function(){
if(vars.running) return false;
if($(this).hasClass('active')) return false;
clearInterval(timer);
timer = '';
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
vars.currentSlide = $(this).attr('rel') - 1;
nivoRun(slider, kids, settings, 'control');
});
}
//Keyboard Navigation
if(settings.keyboardNav){
$(window).keypress(function(event){
//Left
if(event.keyCode == '37'){
if(vars.running) return false;
clearInterval(timer);
timer = '';
vars.currentSlide-=2;
nivoRun(slider, kids, settings, 'prev');
}
//Right
if(event.keyCode == '39'){
if(vars.running) return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
}
});
}
//For pauseOnHover setting
if(settings.pauseOnHover){
slider.hover(function(){
vars.paused = true;
clearInterval(timer);
timer = '';
}, function(){
vars.paused = false;
//Restart the timer
if(timer == '' && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
});
}
//Event when Animation finishes
slider.bind('nivo:animFinished', function(){
vars.running = false;
//Hide child links
$(kids).each(function(){
if($(this).is('a')){
$(this).css('display','none');
}
});
//Show current link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
//Restart the timer
if(timer == '' && !vars.paused && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
//Trigger the afterChange callback
settings.afterChange.call(this);
});
// Add slices for slice animations
var createSlices = function(slider, settings, vars){
for(var i = 0; i < settings.slices; i++){
var sliceWidth = Math.round(slider.width()/settings.slices);
if(i == settings.slices-1){
slider.append(
$('<div class="nivo-slice"></div>').css({
left:(sliceWidth*i)+'px', width:(slider.width()-(sliceWidth*i))+'px',
height:'0px',
opacity:'0',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px 0%'
})
);
} else {
slider.append(
$('<div class="nivo-slice"></div>').css({
left:(sliceWidth*i)+'px', width:sliceWidth+'px',
height:'0px',
opacity:'0',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px 0%'
})
);
}
}
}
// Add boxes for box animations
var createBoxes = function(slider, settings, vars){
var boxWidth = Math.round(slider.width()/settings.boxCols);
var boxHeight = Math.round(slider.height()/settings.boxRows);
for(var rows = 0; rows < settings.boxRows; rows++){
for(var cols = 0; cols < settings.boxCols; cols++){
if(cols == settings.boxCols-1){
slider.append(
$('<div class="nivo-box"></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:(slider.width()-(boxWidth*cols))+'px',
height:boxHeight+'px',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((boxWidth + (cols * boxWidth)) - boxWidth) +'px -'+ ((boxHeight + (rows * boxHeight)) - boxHeight) +'px'
})
);
} else {
slider.append(
$('<div class="nivo-box"></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:boxWidth+'px',
height:boxHeight+'px',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((boxWidth + (cols * boxWidth)) - boxWidth) +'px -'+ ((boxHeight + (rows * boxHeight)) - boxHeight) +'px'
})
);
}
}
}
}
// Private run method
var nivoRun = function(slider, kids, settings, nudge){
//Get our vars
var vars = slider.data('nivo:vars');
//Trigger the lastSlide callback
if(vars && (vars.currentSlide == vars.totalSlides - 1)){
settings.lastSlide.call(this);
}
// Stop
if((!vars || vars.stop) && !nudge) return false;
//Trigger the beforeChange callback
settings.beforeChange.call(this);
//Set current background before change
if(!nudge){
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
} else {
if(nudge == 'prev'){
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
}
if(nudge == 'next'){
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
}
}
vars.currentSlide++;
//Trigger the slideshowEnd callback
if(vars.currentSlide == vars.totalSlides){
vars.currentSlide = 0;
settings.slideshowEnd.call(this);
}
if(vars.currentSlide < 0) vars.currentSlide = (vars.totalSlides - 1);
//Set vars.currentImage
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
//Set active links
if(settings.controlNav){
$('.nivo-controlNav a', slider).removeClass('active');
$('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active');
}
//Process caption
processCaption(settings);
// Remove any slices from last transition
$('.nivo-slice', slider).remove();
// Remove any boxes from last transition
$('.nivo-box', slider).remove();
if(settings.effect == 'random'){
var anims = new Array('sliceDownRight','sliceDownLeft','sliceUpRight','sliceUpLeft','sliceUpDown','sliceUpDownLeft','fold','fade',
'boxRandom','boxRain','boxRainReverse','boxRainGrow','boxRainGrowReverse');
vars.randAnim = anims[Math.floor(Math.random()*(anims.length + 1))];
if(vars.randAnim == undefined) vars.randAnim = 'fade';
}
//Run random effect from specified set (eg: effect:'fold,fade')
if(settings.effect.indexOf(',') != -1){
var anims = settings.effect.split(',');
vars.randAnim = anims[Math.floor(Math.random()*(anims.length))];
if(vars.randAnim == undefined) vars.randAnim = 'fade';
}
//Run effects
vars.running = true;
if(settings.effect == 'sliceDown' || settings.effect == 'sliceDownRight' || vars.randAnim == 'sliceDownRight' ||
settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if(settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft') slices = $('.nivo-slice', slider)._reverse();
slices.each(function(){
var slice = $(this);
slice.css({ 'top': '0px' });
if(i == settings.slices-1){
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
}
else if(settings.effect == 'sliceUp' || settings.effect == 'sliceUpRight' || vars.randAnim == 'sliceUpRight' ||
settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if(settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft') slices = $('.nivo-slice', slider)._reverse();
slices.each(function(){
var slice = $(this);
slice.css({ 'bottom': '0px' });
if(i == settings.slices-1){
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
}
else if(settings.effect == 'sliceUpDown' || settings.effect == 'sliceUpDownRight' || vars.randAnim == 'sliceUpDown' ||
settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var v = 0;
var slices = $('.nivo-slice', slider);
if(settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft') slices = $('.nivo-slice', slider)._reverse();
slices.each(function(){
var slice = $(this);
if(i == 0){
slice.css('top','0px');
i++;
} else {
slice.css('bottom','0px');
i = 0;
}
if(v == settings.slices-1){
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
v++;
});
}
else if(settings.effect == 'fold' || vars.randAnim == 'fold'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
$('.nivo-slice', slider).each(function(){
var slice = $(this);
var origWidth = slice.width();
slice.css({ top:'0px', height:'100%', width:'0px' });
if(i == settings.slices-1){
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
}
else if(settings.effect == 'fade' || vars.randAnim == 'fade'){
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height': '100%',
'width': slider.width() + 'px'
});
firstSlice.animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
}
else if(settings.effect == 'slideInRight' || vars.randAnim == 'slideInRight'){
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height': '100%',
'width': '0px',
'opacity': '1'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
}
else if(settings.effect == 'slideInLeft' || vars.randAnim == 'slideInLeft'){
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height': '100%',
'width': '0px',
'opacity': '1',
'left': '',
'right': '0px'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){
// Reset positioning
firstSlice.css({
'left': '0px',
'right': ''
});
slider.trigger('nivo:animFinished');
});
}
else if(settings.effect == 'boxRandom' || vars.randAnim == 'boxRandom'){
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
var boxes = shuffle($('.nivo-box', slider));
boxes.each(function(){
var box = $(this);
if(i == totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 20;
i++;
});
}
else if(settings.effect == 'boxRain' || vars.randAnim == 'boxRain' || settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' ||
settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse'){
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
// Split boxes into 2D array
var rowIndex = 0;
var colIndex = 0;
var box2Darr = new Array();
box2Darr[rowIndex] = new Array();
var boxes = $('.nivo-box', slider);
if(settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' ||
settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse'){
boxes = $('.nivo-box', slider)._reverse();
}
boxes.each(function(){
box2Darr[rowIndex][colIndex] = $(this);
colIndex++;
if(colIndex == settings.boxCols){
rowIndex++;
colIndex = 0;
box2Darr[rowIndex] = new Array();
}
});
// Run animation
for(var cols = 0; cols < (settings.boxCols * 2); cols++){
var prevCol = cols;
for(var rows = 0; rows < settings.boxRows; rows++){
if(prevCol >= 0 && prevCol < settings.boxCols){
/* Due to some weird JS bug with loop vars
being used in setTimeout, this is wrapped
with an anonymous function call */
(function(row, col, time, i, totalBoxes) {
var box = $(box2Darr[row][col]);
var w = box.width();
var h = box.height();
if(settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' ||
settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse'){
box.width(0).height(0);
}
if(i == totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + time));
} else {
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3);
}, (100 + time));
}
})(rows, prevCol, timeBuff, i, totalBoxes);
i++;
}
prevCol--;
}
timeBuff += 100;
}
}
}
// Shuffle an array
var shuffle = function(arr){
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
// For debugging
var trace = function(msg){
if (this.console && typeof console.log != "undefined")
console.log(msg);
}
// Start / Stop
this.stop = function(){
if(!$(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = true;
trace('Stop Slider');
}
}
this.start = function(){
if($(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = false;
trace('Start Slider');
}
}
//Trigger the afterLoad callback
settings.afterLoad.call(this);
return this;
};
$.fn.nivoSlider = function(options) {
return this.each(function(key, value){
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('nivoslider')) return element.data('nivoslider');
// Pass options to plugin constructor
var nivoslider = new NivoSlider(this, options);
// Store plugin object in this element's data
element.data('nivoslider', nivoslider);
});
};
//Default settings
$.fn.nivoSlider.defaults = {
effect: 'random',
slices: 15,
boxCols: 8,
boxRows: 4,
animSpeed: 500,
pauseTime: 3000,
startSlide: 0,
directionNav: true,
directionNavHide: true,
controlNav: true,
controlNavThumbs: false,
controlNavThumbsFromRel: false,
controlNavThumbsSearch: '.jpg',
controlNavThumbsReplace: '_thumb.jpg',
keyboardNav: true,
pauseOnHover: true,
manualAdvance: false,
captionOpacity: 0.8,
prevText: 'Prev',
nextText: 'Next',
beforeChange: function(){},
afterChange: function(){},
slideshowEnd: function(){},
lastSlide: function(){},
afterLoad: function(){}
};
$.fn._reverse = [].reverse;
})(jQuery); | JavaScript |
/**
* autoNumeric.js
* @author: Bob Knothe
* @version: 1.6.2
*
* Created by Robert J. Knothe on 2010-10-25. Please report any bug at http://www.decorplanit.com/plugin/
*
* Copyright (c) 2010 Robert J. Knothe http://www.decorplanit.com/plugin/
*
* The MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
(function($) {
$.fn.autoNumeric = function(options) {
var opts = $.extend({}, $.fn.autoNumeric.defaults, options);/* build main options before element iteration */
return this.each(function() {/* iterate and reformat each matched element */
var iv = $(this);/* check input value iv */
var ii = this.id;/* input ID */
var io = $.metadata ? $.extend({}, opts, iv.metadata()) : opts;/* build element specific options io = input options */
io.mDec = isNaN(io.mDec * 1) ? $('#' + io.mDec).val() * 1 : io.mDec * 1;/* sets decimal places */
var kdCode = '';/* Key down Code */
var selectLength = 0;/* length of input selected */
var caretPos = 0;/* caret poistion */
var inLength = 0;/* length prior to keypress event */
var charLeft = 0;/* number of characters to the left of the decimal point */
var numLeft = 0;/* number of numeric characters to the left of the decimal point */
var numRight = 0;/* number of numeric characters to the right of the decimal point */
var cmdKey = false;/* MAC command ket pressed */
$(this).keydown(function(e){/* start keyDown event */
io = $.metadata ? $.extend({}, opts, iv.metadata()) : opts;/* build element specific options io = input options */
io.mDec = isNaN(io.mDec * 1) ? $('#' + io.mDec).val() * 1 : io.mDec * 1;/* sets decimal places */
cmdKey = false;
if (!e){/* routine for key codes on key down */
e = window.event;
}
if (e.keyCode){/* IE support */
kdCode = e.keyCode;
}
else if (e.which){/* FF & O support */
kdCode = e.which;
}
if(e.metaKey){/* tests for Mac command key being pressed down thanks Bart B. for bring to my attention */
cmdKey = true;
}
if (document.selection){/* IE Support to find the caret position */
this.focus();
var select = document.selection.createRange();
selectLength = document.selection.createRange().text.length;
select.moveStart('character', -this.value.length);
caretPos = (select.text.length - selectLength) * 1;
}
else if (this.selectionStart || this.selectionStart == '0'){/* Firefox support to find the caret position */
selectLength = this.selectionEnd * 1 - this.selectionStart * 1;
caretPos = this.selectionStart * 1;
}/* end caret position routine */
inLength = this.value.length;/* pass string length to keypress event for value left & right of the decimal position & keyUp event to set caret position */
}).keypress(function(e){/* start keypress event*/
var allowed = io.aNum + io.aNeg + io.aDec;/* sets allowed input, number, negitive sign and decimal seperator */
charLeft = (this.value.lastIndexOf(io.aDec) == -1) ? inLength : inLength - (inLength - this.value.lastIndexOf(io.aDec));/* characters to the left of the decimal point */
numLeft = autoCount(this.value, 0, charLeft);/* the number of intergers to the left of the decimal point */
if (this.value.lastIndexOf(io.aDec) != -1){
numRight = autoCount(this.value, charLeft, inLength);/* the number of intergers to the right of the decimal point */
}
if ((e.ctrlKey || cmdKey) && (kdCode == 65 || kdCode == 67 || kdCode == 86 || kdCode == 88)){/* allows controll key & select all (v=65) Thanks Jonas Johansson, copy(c=67), past (v=86), cut (v=88) */
return true;
}
if (kdCode == 8 || kdCode == 9 || kdCode == 13 || kdCode == 35 || kdCode == 36 || kdCode == 37 || kdCode == 39 || kdCode == 46){/* allows the backspace (8), tab (9), enter 13, end (35), home(36), left(37) and right(39) arrows key delete key (46) to function in some browsers (FF & O) - Thanks to Bart Bons on the return key */
return true;
}
var kpCode = '';/* Key Press Code */
if (!e){/* routine for key codes on key down */
e = window.event;
}
if (e.keyCode){/* IE */
kpCode = e.keyCode;
}
else if (e.which){/* FF & O */
kpCode = e.which;
}
var cCode = String.fromCharCode(kpCode);/* Character code*/
if (allowed.indexOf(cCode) == -1){/* checks for allowed characters */
e.preventDefault();
}
if (cCode == io.aDec){/* start rules when the decimal charactor key is pressed */
if (selectLength == inLength && selectLength > 0){/* allows the selected input to be replaced with a number - Thanks Bart V. */
return;
}
if(caretPos <= this.value.lastIndexOf('-') || this.value.indexOf(io.aDec) != -1 || io.mDec === 0){/* prevents the decimal decimal character from being enetered left of the negitive symbol */
e.preventDefault();
}
if(caretPos <= this.value.lastIndexOf(io.aSep) && this.value.lastIndexOf(io.aSep) != -1 && io.aSep !== ''){/* prevents the decimal charactor from being entered to the left of a thousand separator */
if(io.pSign == 's' && io.aSign.indexOf(' ') >= 0){/* rules when the curency symbol has a space character and is placed as a suffix and the thousand separator is also a space */
var subStr = this.value.substring(0, this.value.length - io.aSign.length);
var subStrPos = subStr.lastIndexOf(' ');
if(caretPos > subStrPos && caretPos >= subStr.length - io.mDec){
return;
}
else {
e.preventDefault();
}
}
else {
e.preventDefault();
}
}
if(io.aSign === '' && caretPos < this.value.length - io.mDec){/* decimal placement & accuracy with no currency symbol */
e.preventDefault();
}
if(io.aSign !== '' && io.pSign == 'p' && (this.value.length - caretPos > io.mDec || caretPos < io.aSign.length)){/* decimal placement & accuracy with with currency symbol as prefix */
e.preventDefault();
}
if(io.aSign !== '' && io.pSign == 's' && (caretPos > this.value.length - io.aSign.length || caretPos < this.value.length - (io.aSign.length + io.mDec))){/* decimal placement & accuracy with with currency symbol as suffix */
e.preventDefault();
}
}/* end rules when the decimal charactor key is pressed */
if (kpCode == 45 && (caretPos > 0 || this.value.indexOf('-') != -1 || io.aNeg === '')){/* start rules when the negative key pressed */
if (selectLength >= 1 && caretPos === 0){/* allows the selected input to be replaced with a number - Thanks Bart V. */
return;
}
else{
e.preventDefault();
}
}/* end rules when the negative key pressed */
if (kpCode >= 48 && kpCode <= 57){/* start rules for number key press */
if (selectLength > 0){/* allows the selected input to be replaced with a number - Thanks Bart V. */
return;
}
if (caretPos < io.aSign.length && io.aSign !== '' && io.pSign == 'p' && inLength > 0){/* prevents numbers from being entered to the left of the currency sign when the currency symbol is on the left */
e.preventDefault();
}
if (caretPos > this.value.length - io.aSign.length && io.aSign !== '' && io.pSign == 's' && this.value !== ''){/* prevents numbers from being entered to the right of the currency sign when the currency symbol is on the right */
e.preventDefault();
}
if (caretPos == this.value.lastIndexOf('-')){/* prevents numbers from being entered to the left negative sign */
e.preventDefault();
}
if (numLeft >= io.mNum && caretPos <= charLeft){/* checks for max numeric characters to the left of the decimal point */
e.preventDefault();
}
if (this.value.indexOf(io.aDec) != -1 && caretPos >= charLeft + 1 && numRight >= io.mDec){/* checks for max numeric characters to the left and right of the decimal point */
e.preventDefault();
}
}/* end rules for number key press */
}).keyup(function(e){/* start keyup event routine */
if (this.value === '') { /* Fix to let you delete what is in the textbox without it adding padded zeroes - bcull - 6 Sep 2010 */
return;
}
if (io.aSep === '' || e.keyCode == 9 || e.keyCode == 20 || e.keyCode == 35 || e.keyCode == 36 || e.keyCode == 37 || e.keyCode == 39 || kdCode == 9 || kdCode == 13 || kdCode == 20 || kdCode == 35 || kdCode == 36 || kdCode == 37 || kdCode == 39){/* allows the tab(9), end(35), home(36) left(37) & right(39) arrows and when there is no thousand separator to bypass the autoGroup function */
return;/* key codes 35 & 36 Home and end keys fix thanks to JPM USA */
}
/* if(kdCode == 110 && this.value.indexOf(io.aDec) == -1 && io.mDec > 0 && caretPos >= this.value.length - io.mDec && this.value.lastIndexOf(io.aSep) < caretPos && this.value.lastIndexOf('-') < caretPos){ //start modification for period key to enter a comma on numeric pad
$(this).val(this.value.substring(0, caretPos) + io.aDec + this.value.substring(inLength, caretPos));
}*/
$(autoId(ii)).val(autoGroup(this.value, io));/* adds the thousand sepparator */
var outLength = this.value.length;
charLeft = (this.value.lastIndexOf(io.aDec) == -1) ? outLength : outLength - (outLength - this.value.lastIndexOf(io.aDec));
numLeft = autoCount(this.value, 0, charLeft);/* the number of intergers to the left of the decimal point */
if (numLeft > io.mNum){/* if max number of characters are exceeeded */
$(autoId(ii)).val('');
}
var setCaret = 0;/* start - determines the new caret position */
if (inLength < outLength){/* new caret position when a number or decimal character has been added */
setCaret = (outLength == io.aSign.length + 1 && io.pSign == 's') ? 1 : caretPos + (outLength - inLength);
}
if (inLength > outLength){ /* new caret position when a number(s) or decimal character(s) has been deleted */
if(selectLength === 0){
if((inLength - 2) == outLength){/* when two caracters one numeric and one thosand seperator have been deleted */
if(kdCode == 8){/* back space key pressed */
setCaret = (caretPos - 2);
}
else if(kdCode == 46){/* delete key pressed */
setCaret = caretPos;
}
else{
setCaret = (caretPos - 1);
}
}
else{/* back space key pressed */
setCaret = (kdCode == 8) ? caretPos - 1 : caretPos;
}
}
if(selectLength > 0 && selectLength < inLength){/* when multiple characters but not all are deleted */
setCaret = (outLength - (inLength - (caretPos + selectLength)));
}
if(selectLength == inLength){/* when multiple characters but not all are deleted */
setCaret = (outLength == io.aSign.length + 1 && io.pSign == 's') ? 1 : 1 + io.aSign.length;
}
}
if (inLength == outLength){/* new caret position when a and equal aount of characters have been added as the amount deleted */
if(selectLength >= 0){
setCaret = caretPos + selectLength;
}
if(this.value.charAt(caretPos - 1) == io.aSep && kdCode == 8){/* moves caret to the left when trying to delete thousand separartor via the backspace key */
setCaret = (caretPos - 1);
}
else if(this.value.charAt(caretPos) == io.aSep && kdCode == 46){/* moves caret to the right when trying to delete thousand separartor via the delete key */
setCaret = (caretPos + 1);
}
}/* ends - determines the new caret position */
var iField = this;/* start - set caret position */
iField.focus();
if (document.selection) {
var iRange = iField.createTextRange();
iRange.collapse(true);
iRange.moveStart("character", setCaret);
iRange.moveEnd("character", 0);
iRange.select();
}
else if (iField.selectionStart || iField.selectionStart == '0') {
iField.selectionStart = setCaret;
iField.selectionEnd = setCaret;
}/* end - set caret position */
}).bind('change focusout', function(){/* start change - thanks to Javier P. corrected the inline onChange event added focusout version 1.55*/
if ($(autoId(ii)).val() !== ''){
autoCheck(iv, ii, io);
}
}).bind('paste', function(){setTimeout(function(){autoCheck(iv, ii, io);}, 0); });/* thanks to Josh of Digitalbush.com Opera does not fire paste event*/
});
};
function autoId(myid) {/* thanks to Anthony & Evan C */
myid = myid.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
return '#' + myid.replace(/(:|\.)/g,'\\$1');
}
function autoCount(str, start, end){/* private function that counts the numeric characters to the left and right of the decimal point */
var chr = '';
var numCount = 0;
for (j = start; j < end; j++){
chr = str.charAt(j);
if (chr >= '0' && chr <= '9'){
numCount++;
}
}
return numCount;
}
function autoGroup(iv, io){/* private function that places the thousand separtor */
if (io.aSep !== ''){
var digitalGroup = '';
if (io.dGroup == 2){
digitalGroup = /(\d)((\d)(\d{2}?)+)$/;
}
else if (io.dGroup == 4){
digitalGroup = /(\d)((\d{4}?)+)$/;
}
else {
digitalGroup = /(\d)((\d{3}?)+)$/;
}
for (k = 0; k < io.aSign.length; k++){/* clears the currency or other symbols and space */
iv = iv.replace(io.aSign.charAt(k), '').replace("\u00A0",'');
}
iv = iv.split(io.aSep).join('');/* removes the thousand sepparator */
var ivSplit = iv.split(io.aDec);/* splits the string at the decimal string */
var s = ivSplit[0];/* assigns the whole number to the a varibale (s) */
while(digitalGroup.test(s)){
s = s.replace(digitalGroup, '$1'+io.aSep+'$2');/* re-inserts the thousand sepparator via a regualer expression */
}
if (io.mDec !== 0 && ivSplit.length > 1){
iv = s + io.aDec + ivSplit[1];/* joins the whole number with the deciaml value */
}
else {
iv = s;/* if whole numers only */
}
if (iv.indexOf('-') !== -1 && io.aSign !== '' && io.pSign == 'p'){/* places the currency sign to the left (prefix) */
iv = iv.replace('-', '');
return '-' + io.aSign + iv;
}
else if (iv.indexOf('-') == -1 && io.aSign !== '' && io.pSign == 'p'){
return io.aSign + iv;
}
if (iv.indexOf('-') !== -1 && io.aSign !== '' && io.pSign == 's'){/* places the currency sign to the right (suffix) */
iv = iv.replace('-', '');
return '-'+ iv + io.aSign;
}
else if (iv.indexOf('-') == -1 && io.aSign !== '' && io.pSign == 's'){
return iv + io.aSign;
}
else {
return iv;
}
}
else {
return iv;
}
}
function autoRound(iv, mDec, mRound, aPad){/* private function for round the number - please note this handled as text - Javascript math function can return inaccurate values */
iv = (iv === '') ? '0' : iv += ''; /* value to string */
var ivRounded = '';
var i = 0;
var nSign = '';
if (iv.charAt(0) == '-'){/* Checks if the iv (input Value)is a negative value */
nSign = (iv * 1 === 0) ? '' : '-';/* determines if the value is zero - if zero no negative sign */
iv = iv.replace('-', '');/* removes the negative sign will be added back later if required */
}
if ((iv * 1) > 0){/* trims leading zero's if needed */
while (iv.substr(0,1) == '0' && iv.length > 1) {
iv = iv.substr(1);
}
}
var dPos = iv.lastIndexOf('.');/* decimal postion as an integer */
if (dPos === 0){/* prefix with a zero if the decimal point is the first character */
iv = '0' + iv;
dPos = 1;
}
if (dPos == -1 || dPos == iv.length - 1){/* Has an integer been passed in? */
if (aPad && mDec > 0) {
ivRounded = (dPos == -1) ? iv + '.' : iv;
for(i = 0; i < mDec; i++){/* pads with zero */
ivRounded += '0';
}
return nSign + ivRounded;
}
else {
return nSign + iv;
}
}
var cDec = (iv.length - 1) - dPos;/* checks decimal places to determine if rounding is required */
if (cDec == mDec){
return nSign + iv;/* If true return value no rounding required */
}
if (cDec < mDec && aPad){/* Do we already have less than the number of decimal places we want? */
ivRounded = iv;/* If so, pad out with zeros */
for(i = cDec; i < mDec; i++){
ivRounded += '0';
}
return nSign + ivRounded;
}
var rLength = dPos + mDec;/* rounded length of the string after rounding */
var tRound = iv.charAt(rLength + 1) * 1;/* test round */
var ivArray = [];/* new array*/
for(i = 0; i <= rLength; i++){/* populate ivArray with each digit in rLength */
ivArray[i] = iv.charAt(i);
}
var odd = (iv.charAt(rLength) == '.') ? (iv.charAt(rLength - 1) % 2) : (iv.charAt(rLength) % 2);
if ((tRound > 4 && mRound === 'S') ||/* Round half up symetric */
(tRound > 4 && mRound === 'A' && nSign === '') ||/* Round half up asymetric positive values */
(tRound > 5 && mRound === 'A' && nSign == '-') ||/* Round half up asymetric negative values */
(tRound > 5 && mRound === 's') ||/* Round half down symetric */
(tRound > 5 && mRound === 'a' && nSign === '') ||/* Round half down asymetric positive values */
(tRound > 4 && mRound === 'a' && nSign == '-') ||/* Round half down asymetric negative values */
(tRound > 5 && mRound === 'B') ||/* Round half even "Banker's Rounding" */
(tRound == 5 && mRound === 'B' && odd == 1) ||/* Round half even "Banker's Rounding" */
(tRound > 0 && mRound === 'C' && nSign === '') ||/* Round to ceiling toward positive infinite */
(tRound > 0 && mRound === 'F' && nSign == '-') ||/* Round to floor toward negative inifinte */
(tRound > 0 && mRound === 'U')){/* round up away from zero */
for(i = (ivArray.length - 1); i >= 0; i--){/* Round up the last digit if required, and continue until no more 9's are found */
if (ivArray[i] == '.'){
continue;
}
ivArray[i]++;
if (ivArray[i] < 10){/* if i does not equal 10 no more round up required */
break;
}
}
}
for (i=0; i <= rLength; i++){/* Reconstruct the string, converting any 10's to 0's */
if (ivArray[i] == '.' || ivArray[i] < 10 || i === 0){/* routine to reconstruct non '10' */
ivRounded += ivArray[i];
}
else {/* converts 10's to 0 */
ivRounded += '0';
}
}
if (mDec === 0){/* If there are no decimal places, we don't need a decimal point */
ivRounded = ivRounded.replace('.', '');
}
return nSign + ivRounded;/* return rounded value */
}
function autoCheck(iv, ii, io){/* private function that change event and pasted values */
iv = iv.val();
if (iv.length > 100){/* maximum length of pasted value */
$(autoId(ii)).val('');
return;
}
var eNeg = '';
if (io.aNeg == '-'){/* escape the negative sign */
eNeg = '\\-';
}
var reg = new RegExp('[^'+eNeg+io.aNum+io.aDec+']','gi');/* regular expreession constructor to delete any characters not allowed for the input field. */
var testPaste = iv.replace(reg,'');/* deletes all characters that are not permitted in this field */
if (testPaste.lastIndexOf('-') > 0 || testPaste.indexOf(io.aDec) != testPaste.lastIndexOf(io.aDec)){/* deletes input if the negitive sign is incorrectly placed or if the are multiple decimal characters */
testPaste = '';
}
var rePaste = '';
var nNeg = 0;
var nSign = '';
var i = 0;
var s = testPaste.split('');/* split the sting into an array */
for (i=0; i<s.length; i++){/* for loop testing pasted value after non allowable characters have been deleted */
if (i === 0 && s[i] == '-'){/* allows negative symbol to be added if it is the first character */
nNeg = 1;
nSign = '-';
continue;
}
if (s[i] == io.aDec && s.length -1 == i){/* if the last charter is a decimal point it is dropped */
break;
}
if (rePaste.length === 0 && s[i] == '0' && (s[i+1] >= 0 || s[i+1] <= 9)){/* controls leading zero */
continue;
}
else {
rePaste = rePaste + s[i];
}
}
rePaste = nSign + rePaste;
if (rePaste.indexOf(io.aDec) == -1 && rePaste.length > (io.mNum + nNeg)){/* checks to see if the maximum & minimum values have been exceeded when no decimal point is present */
rePaste = '';
}
if (rePaste.indexOf(io.aDec) > (io.mNum + nNeg)){/* check to see if the maximum & minimum values have been exceeded when the decimal point is present */
rePaste = '';
}
if (rePaste.indexOf(io.aDec) != -1 && (io.aDec != '.')){
rePaste = rePaste.replace(io.aDec, '.');
}
rePaste = autoRound(rePaste, io.mDec, io.mRound, io.aPad);/* call round function */
if (io.aDec != '.'){
rePaste = rePaste.replace('.', io.aDec);/* replace the decimal point with the proper decimal separator */
}
if (rePaste !== '' && io.aSep !== ''){
rePaste = autoGroup(rePaste, io);/* calls the group function adds digital grouping */
}
$(autoId(ii)).val(rePaste);
return false;
}
$.fn.autoNumeric.Strip = function(ii, options){/* public function that stripes the format and converts decimal seperator to a period */
var opts = $.extend({}, $.fn.autoNumeric.defaults, options);
var io = $.metadata ? $.extend({}, opts, $(autoId(ii)).metadata()) : opts;
io.mDec = isNaN(io.mDec * 1) ? $('#' + io.mDec).val() * 1 : io.mDec * 1;/* decimal places */
var iv = $(autoId(ii)).val();
iv = iv.replace(io.aSign, '').replace('\u00A0','');
var reg = new RegExp('[^'+'\\-'+io.aNum+io.aDec+']','gi');/* regular expreession constructor */
iv = iv.replace(reg,'');/* deletes all characters that are not permitted in this field */
var nSign = '';
if (iv.charAt(0) == '-'){/* Checks if the iv (input Value)is a negative value */
nSign = (iv * 1 === 0) ? '' : '-';/* determines if the value is zero - if zero no negative sign */
iv = iv.replace('-', '');/* removes the negative sign will be added back later if required */
}
iv = iv.replace(io.aDec, '.');
if (iv * 1 > 0){
while (iv.substr(0,1) == '0' && iv.length > 1) {
iv = iv.substr(1);
}
}
iv = (iv.lastIndexOf('.') === 0) ? ('0' + iv) : iv;
iv = (iv * 1 === 0) ? '0' : iv;
return nSign + iv;
};
$.fn.autoNumeric.Format = function(ii, iv, options){/* public function that recieves a numeric string and formats to the target input field */
iv += '';/* to string */
var opts = $.extend({}, $.fn.autoNumeric.defaults, options);
var io = $.metadata ? $.extend({}, opts, $(autoId(ii)).metadata()) : opts;
io.mDec = isNaN(io.mDec * 1) ? $('#' + io.mDec).val() * 1 : io.mDec * 1;/* decimal places */
iv = autoRound(iv, io.mDec, io.mRound, io.aPad);
var nNeg = 0;
if (iv.indexOf('-') != -1 && io.aNeg === ''){/* deletes negative symbol */
iv = '';
}
else if (iv.indexOf('-') != -1 && io.aNeg == '-'){
nNeg = 1;
}
if (iv.indexOf('.') == -1 && iv.length > (io.mNum + nNeg)){/* check to see if the maximum & minimum values have been exceeded when no decimal point is present */
iv = '';
}
else if (iv.indexOf('.') > (io.mNum + nNeg)){/* check to see if the maximum & minimum values have been exceeded when a decimal point is present */
iv = '';
}
if (io.aDec != '.'){/* replaces the decimal point with the new sepatator */
iv = iv.replace('.', io.aDec);
}
return autoGroup(iv, io);
};
$.fn.autoNumeric.defaults = {/* plugin defaults */
aNum: '0123456789',/* allowed numeric values */
aNeg: '',/* allowed negative sign / character */
aSep: ',',/* allowed thousand separator character */
aDec: '.',/* allowed decimal separator character */
aSign: '',/* allowed currency symbol */
pSign: 'p',/* placement of currency sign prefix or suffix */
mNum: 9,/* max number of numerical characters to the left of the decimal */
mDec: 2,/* max number of decimal places */
dGroup: 3,/* digital grouping for the thousand separator used in Format */
mRound: 'S',/* method used for rounding */
aPad: true/* true= always Pad decimals with zeros, false=does not pad with zeros. If the value is 1000, mDec=2 and aPad=true, the output will be 1000.00, if aPad=false the output will be 1000 (no decimals added) Special Thanks to Jonas Johansson */
};
})(jQuery); | JavaScript |
/**
* Uni-Form jQuery Plugin without Validation
*
* Provides form actions for use with the Uni-Form markup style
*
* Author: Ilija Studen for the purposes of Uni-Form
*
* Modified by Aris Karageorgos to use the parents function
*
* Modified by Toni Karlheinz to support input fields' text
* coloring and removal of their initial values on focus
*
* Modified by Jason Brumwell for optimization, addition
* of valid and invalid states and default data attribues
*
*
* @see http://sprawsm.com/uni-form/
* @license MIT http://www.opensource.org/licenses/mit-license.php
*/
jQuery.fn.uniform = function(settings) {
settings = jQuery.extend({
valid_class : 'valid',
invalid_class : 'invalid',
error_class : 'error',
focused_class : 'focused',
holder_class : 'ctrlHolder',
field_selector : 'input, textarea, select',
default_value_color: "#AFAFAF"
}, settings);
return this.each(function() {
var form = jQuery(this),
validate = function($input,valid,text) {
var $p = $input.closest('div.'+settings.holder_class)
.andSelf()
.toggleClass(settings.invalid_class,!valid)
.toggleClass(settings.error_class,!valid)
.toggleClass(settings.valid_class,valid)
.find('p.formHint');
if (! valid && ! $p.data('info-text')) {
$p.data('info-text',$p.html());
} else if (valid) {
text = $p.data('info-text');
}
if (text) {
$p.html(text);
}
};
form.submit(function(){
form.find(settings.field_selector).each(function(){
if($(this).val() == $(this).data('default-value')) $(this).val("");
});
})
// Select form fields and attach them higlighter functionality
form.find(settings.field_selector).each(function(){
var $input = $(this),
value = $input.val();
$input.data('default-color',$input.css('color'));
if (value == $input.data('default-value') || ! value) {
$input.not('select').css("color",settings.default_value_color);
$input.val($input.data('default-value'));
}
})
form.delegate(settings.field_selector,'focus',function() {
form.find('.' + settings.focused_class).removeClass(settings.focused_class);
var $input = $(this);
$input.parents().filter('.'+settings.holder_class+':first').addClass(settings.focused_class);
if($input.val() == $input.data('default-value')){
$input.val("");
}
$input.not('select').css('color',$input.data('default-color'));
});
form.delegate(settings.field_selector,'blur',function() {
var $input = $(this);
form.find('.' + settings.focused_class).removeClass(settings.focused_class);
if($input.val() == "" || $input.val() == $input.data('default-value')){
$input.not('select').css("color",settings.default_value_color);
$input.val($input.data('default-value'));
} else {
$input.css('color',$input.data('default-color'));
}
});
form.delegate(settings.field_selector,'error',function(e,text) {
validate($(this),false,text);
});
form.delegate(settings.field_selector,'success',function(e,text) {
validate($(this),true);
});
});
};
| JavaScript |
/**
* Initialize tinymce plugin
*/
// define base options for init tinymce
var tinymce_options = {
script_url : base_url + 'vendors/tiny_mce/tiny_mce.js',
plugins: 'table,advimage,inlinepopups,advlink,insertdatetime,media,searchreplace,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking',
theme: 'advanced',
theme_advanced_toolbar_location: 'top',
theme_advanced_toolbar_align: 'left',
theme_advanced_buttons1: 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,cut,copy,paste,pastetext,pasteword,|,removeformat,|,link,unlink,image,media,|,code',
theme_advanced_buttons2: 'undo,redo,|,forecolor,backcolor,|,search,replace,|,bullist,numlist,|,outdent,indent,|,tablecontrols,|,sub,sup,charmap',
theme_advanced_buttons3: '',
theme_advanced_resizing: false,
forced_root_block: false,
force_p_newlines: false,
remove_linebreaks: false,
force_br_newlines: true,
remove_trailing_nbsp: false,
verify_html: true,
invalid_elements: 'script',
width: '100%',
convert_urls: false,
relative_urls: false,
language:"en",
compress: true,
media_strict: false,
entity_encoding:'raw'
};
$().ready(function(){
$('textarea.tinymce').tinymce(tinymce_options);
});
| JavaScript |
/*
* Date prototype extensions. Doesn't depend on any
* other code. Doens't overwrite existing methods.
*
* Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
* isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
* setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
*
* Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
*
* Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
* I've added my name to these methods so you know who to blame if they are broken!
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* An Array of day names starting with Sunday.
*
* @example dayNames[0]
* @result 'Sunday'
*
* @name dayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
/**
* An Array of abbreviated day names starting with Sun.
*
* @example abbrDayNames[0]
* @result 'Sun'
*
* @name abbrDayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
/**
* An Array of month names starting with Janurary.
*
* @example monthNames[0]
* @result 'January'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/**
* An Array of abbreviated month names starting with Jan.
*
* @example abbrMonthNames[0]
* @result 'Jan'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/**
* The first day of the week for this locale.
*
* @name firstDayOfWeek
* @type Number
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.firstDayOfWeek = 1;
/**
* The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';
/**
* The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
* only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.fullYearStart = '20';
(function() {
/**
* Adds a given method under the given name
* to the Date prototype if it doesn't
* currently exist.
*
* @private
*/
function add(name, method) {
if( !Date.prototype[name] ) {
Date.prototype[name] = method;
}
};
/**
* Checks if the year is a leap year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.isLeapYear();
* @result true
*
* @name isLeapYear
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isLeapYear", function() {
var y = this.getFullYear();
return (y%4==0 && y%100!=0) || y%400==0;
});
/**
* Checks if the day is a weekend day (Sat or Sun).
*
* @example var dtm = new Date("01/12/2008");
* dtm.isWeekend();
* @result false
*
* @name isWeekend
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isWeekend", function() {
return this.getDay()==0 || this.getDay()==6;
});
/**
* Check if the day is a day of the week (Mon-Fri)
*
* @example var dtm = new Date("01/12/2008");
* dtm.isWeekDay();
* @result false
*
* @name isWeekDay
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isWeekDay", function() {
return !this.isWeekend();
});
/**
* Gets the number of days in the month.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDaysInMonth();
* @result 31
*
* @name getDaysInMonth
* @type Number
* @cat Plugins/Methods/Date
*/
add("getDaysInMonth", function() {
return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
});
/**
* Gets the name of the day.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayName();
* @result 'Saturday'
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayName(true);
* @result 'Sat'
*
* @param abbreviated Boolean When set to true the name will be abbreviated.
* @name getDayName
* @type String
* @cat Plugins/Methods/Date
*/
add("getDayName", function(abbreviated) {
return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
});
/**
* Gets the name of the month.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getMonthName();
* @result 'Janurary'
*
* @example var dtm = new Date("01/12/2008");
* dtm.getMonthName(true);
* @result 'Jan'
*
* @param abbreviated Boolean When set to true the name will be abbreviated.
* @name getDayName
* @type String
* @cat Plugins/Methods/Date
*/
add("getMonthName", function(abbreviated) {
return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
});
/**
* Get the number of the day of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayOfYear();
* @result 11
*
* @name getDayOfYear
* @type Number
* @cat Plugins/Methods/Date
*/
add("getDayOfYear", function() {
var tmpdtm = new Date("1/1/" + this.getFullYear());
return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
});
/**
* Get the number of the week of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getWeekOfYear();
* @result 2
*
* @name getWeekOfYear
* @type Number
* @cat Plugins/Methods/Date
*/
add("getWeekOfYear", function() {
return Math.ceil(this.getDayOfYear() / 7);
});
/**
* Set the day of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.setDayOfYear(1);
* dtm.toString();
* @result 'Tue Jan 01 2008 00:00:00'
*
* @name setDayOfYear
* @type Date
* @cat Plugins/Methods/Date
*/
add("setDayOfYear", function(day) {
this.setMonth(0);
this.setDate(day);
return this;
});
/**
* Add a number of years to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addYears(1);
* dtm.toString();
* @result 'Mon Jan 12 2009 00:00:00'
*
* @name addYears
* @type Date
* @cat Plugins/Methods/Date
*/
add("addYears", function(num) {
this.setFullYear(this.getFullYear() + num);
return this;
});
/**
* Add a number of months to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addMonths(1);
* dtm.toString();
* @result 'Tue Feb 12 2008 00:00:00'
*
* @name addMonths
* @type Date
* @cat Plugins/Methods/Date
*/
add("addMonths", function(num) {
var tmpdtm = this.getDate();
this.setMonth(this.getMonth() + num);
if (tmpdtm > this.getDate())
this.addDays(-this.getDate());
return this;
});
/**
* Add a number of days to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addDays(1);
* dtm.toString();
* @result 'Sun Jan 13 2008 00:00:00'
*
* @name addDays
* @type Date
* @cat Plugins/Methods/Date
*/
add("addDays", function(num) {
this.setDate(this.getDate() + num);
return this;
});
/**
* Add a number of hours to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addHours(24);
* dtm.toString();
* @result 'Sun Jan 13 2008 00:00:00'
*
* @name addHours
* @type Date
* @cat Plugins/Methods/Date
*/
add("addHours", function(num) {
this.setHours(this.getHours() + num);
return this;
});
/**
* Add a number of minutes to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addMinutes(60);
* dtm.toString();
* @result 'Sat Jan 12 2008 01:00:00'
*
* @name addMinutes
* @type Date
* @cat Plugins/Methods/Date
*/
add("addMinutes", function(num) {
this.setMinutes(this.getMinutes() + num);
return this;
});
/**
* Add a number of seconds to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addSeconds(60);
* dtm.toString();
* @result 'Sat Jan 12 2008 00:01:00'
*
* @name addSeconds
* @type Date
* @cat Plugins/Methods/Date
*/
add("addSeconds", function(num) {
this.setSeconds(this.getSeconds() + num);
return this;
});
/**
* Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
*
* @example var dtm = new Date();
* dtm.zeroTime();
* dtm.toString();
* @result 'Sat Jan 12 2008 00:01:00'
*
* @name zeroTime
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
add("zeroTime", function() {
this.setMilliseconds(0);
this.setSeconds(0);
this.setMinutes(0);
this.setHours(0);
return this;
});
/**
* Returns a string representation of the date object according to Date.format.
* (Date.toString may be used in other places so I purposefully didn't overwrite it)
*
* @example var dtm = new Date("01/12/2008");
* dtm.asString();
* @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
*
* @name asString
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
add("asString", function() {
var r = Date.format;
return r
.split('yyyy').join(this.getFullYear())
.split('yy').join((this.getFullYear() + '').substring(2))
.split('mmm').join(this.getMonthName(true))
.split('mm').join(_zeroPad(this.getMonth()+1))
.split('dd').join(_zeroPad(this.getDate()));
});
/**
* Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
* (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
*
* @example var dtm = Date.fromString("12/01/2008");
* dtm.toString();
* @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
*
* @name fromString
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.fromString = function(s)
{
var f = Date.format;
var d = new Date('01/01/1977');
var iY = f.indexOf('yyyy');
if (iY > -1) {
d.setFullYear(Number(s.substr(iY, 4)));
} else {
// TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
}
var iM = f.indexOf('mmm');
if (iM > -1) {
var mStr = s.substr(iM, 3);
for (var i=0; i<Date.abbrMonthNames.length; i++) {
if (Date.abbrMonthNames[i] == mStr) break;
}
d.setMonth(i);
} else {
d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
}
d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
if (isNaN(d.getTime())) {
return false;
}
return d;
};
// utility method
var _zeroPad = function(num) {
var s = '0'+num;
return s.substring(s.length-2)
//return ('0'+num).substring(-2); // doesn't work on IE :(
};
})(); | JavaScript |
$(document).ready(function(){
//Sidebar Accordion Menu:
$("#main-nav li ul").hide(); // Hide all sub menus
// $("#main-nav li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
$("#main-nav li a.nav-top-item").click( // When a top menu item is clicked...
function () {
$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
return false;
}
);
$("#main-nav li a.no-submenu").click( // When a menu item with no sub menu is clicked...
function () {
window.location.href=(this.href); // Just open the link instead of a sub menu
return false;
}
);
// Sidebar Accordion Menu Hover Effect:
$("#main-nav li .nav-top-item").hover(
function () {
$(this).stop().animate({ paddingRight: "25px" }, 200);
},
function () {
$(this).stop().animate({ paddingRight: "15px" });
}
);
/*
//Minimize Content Box
$(".content-box-header h3").css({ "cursor":"s-resize" }); // Give the h3 in Content Box Header a different cursor
$(".closed-box .content-box-content").hide(); // Hide the content of the header if it has the class "closed"
$(".closed-box .content-box-tabs").hide(); // Hide the tabs in the header if it has the class "closed"
$(".content-box-header h3").click( // When the h3 is clicked...
function () {
$(this).parent().next().toggle(); // Toggle the Content Box
$(this).parent().parent().toggleClass("closed-box"); // Toggle the class "closed-box" on the content box
$(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs
}
);
*/
// Content box tabs:
$('.content-box .content-box-content div.tab-content').hide(); // Hide the content divs
$('ul.content-box-tabs li a.default-tab').addClass('current'); // Add the class "current" to the default tab
$('.content-box-content div.default-tab').show(); // Show the div with class "default-tab"
$('.content-box ul.content-box-tabs li a').click( // When a tab is clicked...
function() {
$(this).parent().siblings().find("a").removeClass('current'); // Remove "current" class from all tabs
$(this).addClass('current'); // Add class "current" to clicked tab
var currentTab = $(this).attr('href'); // Set variable "currentTab" to the value of href of clicked tab
$(currentTab).siblings().hide(); // Hide all content divs
$(currentTab).show(); // Show the content div with the id equal to the id of clicked tab
return false;
}
);
//Close button:
$(".close").click(
function () {
$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
$(this).slideUp(400);
});
return false;
}
);
// Alternating table rows:
$('tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows
// Check all checkboxes when the one in a table head is checked:
$('.check-all').click(function(){
$(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));
});
// Initialise Facebox Modal window:
//$('a[rel*=modal]').facebox(); // Applies modal window to any link with attribute rel="modal"
$('a[rel="colorbox"]').colorbox();
});
| JavaScript |
var Sidebar = {};
Sidebar.menu = {
dashboard: 'dashboard_nav',
article: 'article_nav',
land: 'land_nav',
ads: 'ads_nav',
user: 'user_nav',
project: 'project_nav',
setting: 'setting_nav'
};
Sidebar.setActive = function(_id, _index) {
$('#main-nav').find('a.nav-top-item').removeClass('current');
$('#' + _id).children('a').addClass('current');
$('#' + _id).find('ul').slideDown('slow').find('a').removeClass('current');
$('#' + _id).find('li:eq('+_index+')').children('a').addClass('current');
}; | JavaScript |
/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.7a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/
/*
PLEASE READ:
Absolutely everything in this script is SILLY. I know this. IE's rendering of certain pixels doesn't make sense, so neither does this code!
*/
var DD_belatedPNG = {
ns: 'DD_belatedPNG',
imgSize: {},
createVmlNameSpace: function() { /* enable VML */
if (document.namespaces && !document.namespaces[this.ns]) {
document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
}
if (window.attachEvent) {
window.attachEvent('onbeforeunload', function() {
DD_belatedPNG = null;
});
}
},
createVmlStyleSheet: function() { /* style VML, enable behaviors */
/*
Just in case lots of other developers have added
lots of other stylesheets using document.createStyleSheet
and hit the 31-limit mark, let's not use that method!
further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
*/
var style = document.createElement('style');
document.documentElement.firstChild.insertBefore(style, document.documentElement.firstChild.firstChild);
var styleSheet = style.styleSheet;
styleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
styleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
styleSheet.addRule('img.' + this.ns + '_sizeFinder', 'behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;'); /* large negative top value for avoiding vertical scrollbars for large images, suggested by James O'Brien, http://www.thanatopsic.org/hendrik/ */
this.styleSheet = styleSheet;
},
readPropertyChange: function() {
var el = event.srcElement;
if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
DD_belatedPNG.applyVML(el);
}
if (event.propertyName == 'style.display') {
var display = (el.currentStyle.display == 'none') ? 'none' : 'block';
for (var v in el.vml) {
el.vml[v].shape.style.display = display;
}
}
if (event.propertyName.search('filter') != -1) {
DD_belatedPNG.vmlOpacity(el);
}
},
vmlOpacity: function(el) {
if (el.currentStyle.filter.search('lpha') != -1) {
var trans = el.currentStyle.filter;
trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
el.vml.image.fill.opacity = trans; /* complete guesswork */
}
},
handlePseudoHover: function(el) {
setTimeout(function() { /* wouldn't work as intended without setTimeout */
DD_belatedPNG.applyVML(el);
}, 1);
},
/**
* This is the method to use in a document.
* @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
**/
fix: function(selector) {
var selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
for (var i=0; i<selectors.length; i++) {
this.styleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
}
},
applyVML: function(el) {
el.runtimeStyle.cssText = '';
this.vmlFill(el);
this.vmlOffsets(el);
this.vmlOpacity(el);
if (el.isImg) {
this.copyImageBorders(el);
}
},
attachHandlers: function(el) {
var self = this;
var handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
if (el.nodeName == 'A') {
var moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
for (var a in moreForAs) {
handlers[a] = moreForAs[a];
}
}
for (var h in handlers) {
el.attachEvent('on' + h, function() {
self[handlers[h]](el);
});
}
el.attachEvent('onpropertychange', this.readPropertyChange);
},
giveLayout: function(el) {
el.style.zoom = 1;
if (el.currentStyle.position == 'static') {
el.style.position = 'relative';
}
},
copyImageBorders: function(el) {
var styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
for (var s in styles) {
el.vml.color.shape.style[s] = el.currentStyle[s];
}
},
vmlFill: function(el) {
if (!el.currentStyle) {
return;
} else {
var elStyle = el.currentStyle;
}
for (var v in el.vml) {
el.vml[v].shape.style.zIndex = elStyle.zIndex;
}
el.runtimeStyle.backgroundColor = '';
el.runtimeStyle.backgroundImage = '';
var noColor = (elStyle.backgroundColor == 'transparent');
var noImg = true;
if (elStyle.backgroundImage != 'none' || el.isImg) {
if (!el.isImg) {
el.vmlBg = elStyle.backgroundImage;
el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
}
else {
el.vmlBg = el.src;
}
var lib = this;
if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
var img = document.createElement('img');
lib.imgSize[el.vmlBg] = img;
img.className = lib.ns + '_sizeFinder';
img.runtimeStyle.cssText = 'behavior:none; position:absolute; left:-10000px; top:-10000px; border:none;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
img.attachEvent('onload', function() {
this.width = this.offsetWidth; /* weird cache-busting requirement! */
this.height = this.offsetHeight;
lib.vmlOffsets(el);
});
img.src = el.vmlBg;
img.removeAttribute('width');
img.removeAttribute('height');
document.body.insertBefore(img, document.body.firstChild);
}
el.vml.image.fill.src = el.vmlBg;
noImg = false;
}
el.vml.image.fill.on = !noImg;
el.vml.image.fill.color = 'none';
el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
el.runtimeStyle.backgroundImage = 'none';
el.runtimeStyle.backgroundColor = 'transparent';
},
/* IE can't figure out what do when the offsetLeft and the clientLeft add up to 1, and the VML ends up getting fuzzy... so we have to push/enlarge things by 1 pixel and then clip off the excess */
vmlOffsets: function(el) {
var thisStyle = el.currentStyle;
var size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':this.imgSize[el.vmlBg].width, 'h':this.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
var fudge = (size.L + size.bLW == 1) ? 1 : 0;
/* vml shape, left, top, width, height, origin */
var makeVisible = function(vml, l, t, w, h, o) {
vml.coordsize = w+','+h;
vml.coordorigin = o+','+o;
vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
vml.style.width = w + 'px';
vml.style.height = h + 'px';
vml.style.left = l + 'px';
vml.style.top = t + 'px';
};
makeVisible(el.vml.color.shape, (size.L + (el.isImg ? 0 : size.bLW)), (size.T + (el.isImg ? 0 : size.bTW)), (size.W-1), (size.H-1), 0);
makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1);
var bg = {'X':0, 'Y':0};
var figurePercentage = function(axis, position) {
var fraction = true;
switch(position) {
case 'left':
case 'top':
bg[axis] = 0;
break;
case 'center':
bg[axis] = .5;
break;
case 'right':
case 'bottom':
bg[axis] = 1;
break;
default:
if (position.search('%') != -1) {
bg[axis] = parseInt(position)*.01;
}
else {
fraction = false;
}
}
var horz = (axis == 'X');
bg[axis] = Math.ceil(fraction ? ( (size[horz?'W': 'H'] * bg[axis]) - (size[horz?'w': 'h'] * bg[axis]) ) : parseInt(position));
if (bg[axis] == 0) {
bg[axis]++;
}
};
for (var b in bg) {
figurePercentage(b, thisStyle['backgroundPosition'+b]);
}
el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
var bgR = thisStyle.backgroundRepeat;
var dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
var altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
if (bgR != 'repeat') {
var c = {'T':(bg.Y), 'R':(bg.X+size.w), 'B':(bg.Y+size.h), 'L':(bg.X)}; /* these are defaults for no-repeat - clips down to the image location */
if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
var v = bgR.split('repeat-')[1].toUpperCase();
c[altC[v].b1] = 1;
c[altC[v].b2] = size[altC[v].d];
}
if (c.B > size.H) {
c.B = size.H;
}
el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
}
else {
el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
}
},
fixPng: function(el) {
el.style.behavior = 'none';
if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
return;
}
el.isImg = false;
if (el.nodeName == 'IMG') {
if(el.src.toLowerCase().search(/\.png$/) != -1) {
el.isImg = true;
el.style.visibility = 'hidden';
}
else {
return;
}
}
else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
return;
}
var lib = DD_belatedPNG;
el.vml = {color: {}, image: {}};
var els = {shape: {}, fill: {}};
for (var r in el.vml) {
for (var e in els) {
var nodeStr = lib.ns + ':' + e;
el.vml[r][e] = document.createElement(nodeStr);
}
el.vml[r].shape.stroked = false;
el.vml[r].shape.appendChild(el.vml[r].fill);
el.parentNode.insertBefore(el.vml[r].shape, el);
}
el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
el.vml.image.fill.type = 'tile'; /* Ze magic!! Makes image show up. */
el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
lib.attachHandlers(el);
lib.giveLayout(el);
lib.giveLayout(el.offsetParent);
/* set up element */
lib.applyVML(el);
}
};
try {
document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
} catch(r) {}
DD_belatedPNG.createVmlNameSpace();
DD_belatedPNG.createVmlStyleSheet(); | JavaScript |
/*
* Facebox (for jQuery)
* version: 1.2 (05/05/2008)
* @requires jQuery v1.2 or later
*
* Examples at http://famspam.com/facebox/
*
* Licensed under the MIT:
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
*
* Usage:
*
* jQuery(document).ready(function() {
* jQuery('a[rel*=facebox]').facebox()
* })
*
* <a href="#terms" rel="facebox">Terms</a>
* Loads the #terms div in the box
*
* <a href="terms.html" rel="facebox">Terms</a>
* Loads the terms.html page in the box
*
* <a href="terms.png" rel="facebox">Terms</a>
* Loads the terms.png image in the box
*
*
* You can also use it programmatically:
*
* jQuery.facebox('some html')
*
* The above will open a facebox with "some html" as the content.
*
* jQuery.facebox(function($) {
* $.get('blah.html', function(data) { $.facebox(data) })
* })
*
* The above will show a loading screen before the passed function is called,
* allowing for a better ajaxy experience.
*
* The facebox function can also display an ajax page or image:
*
* jQuery.facebox({ ajax: 'remote.html' })
* jQuery.facebox({ image: 'dude.jpg' })
*
* Want to close the facebox? Trigger the 'close.facebox' document event:
*
* jQuery(document).trigger('close.facebox')
*
* Facebox also has a bunch of other hooks:
*
* loading.facebox
* beforeReveal.facebox
* reveal.facebox (aliased as 'afterReveal.facebox')
* init.facebox
*
* Simply bind a function to any of these hooks:
*
* $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
*
*/
(function($) {
$.facebox = function(data, klass) {
$.facebox.loading()
if (data.ajax) fillFaceboxFromAjax(data.ajax)
else if (data.image) fillFaceboxFromImage(data.image)
else if (data.div) fillFaceboxFromHref(data.div)
else if ($.isFunction(data)) data.call($)
else $.facebox.reveal(data, klass)
}
/*
* Public, $.facebox methods
*/
$.extend($.facebox, {
settings: {
opacity : 0,
overlay : true,
loadingImage : 'resources/images/loading.gif',
closeImage : 'resources/images/closelabel.gif',
imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ],
faceboxHtml : '\
<div id="facebox" style="display:none;"> \
<div class="popup"> \
<table> \
<tbody> \
<tr> \
<td class="tl"/><td class="b"/><td class="tr"/> \
</tr> \
<tr> \
<td class="b"/> \
<td class="body"> \
<div class="content"> \
</div> \
<div class="footer"> \
<a href="#" class="close"> \
<img src="resources/images/closelabel.gif" title="close" class="close_image" /> \
</a> \
</div> \
</td> \
<td class="b"/> \
</tr> \
<tr> \
<td class="bl"/><td class="b"/><td class="br"/> \
</tr> \
</tbody> \
</table> \
</div> \
</div>'
},
loading: function() {
init()
if ($('#facebox .loading').length == 1) return true
showOverlay()
$('#facebox .content').empty()
$('#facebox .body').children().hide().end().
append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')
$('#facebox').css({
top: getPageScroll()[1] + (getPageHeight() / 10),
left: 385.5
}).show()
$(document).bind('keydown.facebox', function(e) {
if (e.keyCode == 27) $.facebox.close()
return true
})
$(document).trigger('loading.facebox')
},
reveal: function(data, klass) {
$(document).trigger('beforeReveal.facebox')
if (klass) $('#facebox .content').addClass(klass)
$('#facebox .content').append(data)
$('#facebox .loading').remove()
$('#facebox .body').children().fadeIn('normal')
$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
$(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
},
close: function() {
$(document).trigger('close.facebox')
return false
}
})
/*
* Public, $.fn methods
*/
$.fn.facebox = function(settings) {
init(settings)
function clickHandler() {
$.facebox.loading(true)
// support for rel="facebox.inline_popup" syntax, to add a class
// also supports deprecated "facebox[.inline_popup]" syntax
var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
if (klass) klass = klass[1]
fillFaceboxFromHref(this.href, klass)
return false
}
return this.click(clickHandler)
}
/*
* Private methods
*/
// called one time to setup facebox on this page
function init(settings) {
if ($.facebox.settings.inited) return true
else $.facebox.settings.inited = true
$(document).trigger('init.facebox')
makeCompatible()
var imageTypes = $.facebox.settings.imageTypes.join('|')
$.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')
if (settings) $.extend($.facebox.settings, settings)
$('body').append($.facebox.settings.faceboxHtml)
var preload = [ new Image(), new Image() ]
preload[0].src = $.facebox.settings.closeImage
preload[1].src = $.facebox.settings.loadingImage
$('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
preload.push(new Image())
preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
})
$('#facebox .close').click($.facebox.close)
$('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
}
// getPageScroll() by quirksmode.com
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
// Backwards compatibility
function makeCompatible() {
var $s = $.facebox.settings
$s.loadingImage = $s.loading_image || $s.loadingImage
$s.closeImage = $s.close_image || $s.closeImage
$s.imageTypes = $s.image_types || $s.imageTypes
$s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
}
// Figures out what you want to display and displays it
// formats are:
// div: #id
// image: blah.extension
// ajax: anything else
function fillFaceboxFromHref(href, klass) {
// div
if (href.match(/#/)) {
var url = window.location.href.split('#')[0]
var target = href.replace(url,'')
$.facebox.reveal($(target).clone().show(), klass)
// image
} else if (href.match($.facebox.settings.imageTypesRegexp)) {
fillFaceboxFromImage(href, klass)
// ajax
} else {
fillFaceboxFromAjax(href, klass)
}
}
function fillFaceboxFromImage(href, klass) {
var image = new Image()
image.onload = function() {
$.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
}
image.src = href
}
function fillFaceboxFromAjax(href, klass) {
$.get(href, function(data) { $.facebox.reveal(data, klass) })
}
function skipOverlay() {
return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
}
function showOverlay() {
if (skipOverlay()) return
if ($('facebox_overlay').length == 0)
$("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
$('#facebox_overlay').hide().addClass("facebox_overlayBG")
.css('opacity', $.facebox.settings.opacity)
.click(function() { $(document).trigger('close.facebox') })
.fadeIn(200)
return false
}
function hideOverlay() {
if (skipOverlay()) return
$('#facebox_overlay').fadeOut(200, function(){
$("#facebox_overlay").removeClass("facebox_overlayBG")
$("#facebox_overlay").addClass("facebox_hide")
$("#facebox_overlay").remove()
})
return false
}
/*
* Bindings
*/
$(document).bind('close.facebox', function() {
$(document).unbind('keydown.facebox')
$('#facebox').fadeOut(function() {
$('#facebox .content').removeClass().addClass('content')
hideOverlay()
$('#facebox .loading').remove()
})
})
})(jQuery);
| JavaScript |
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
//security RegExp
var REG_SCRIPT = new RegExp("< *script.*>|< *style.*>|< *link.*>|< *body .*>", "i");
var REG_PROTOCOL = new RegExp("javascript:|vbscript:|about:", "i");
var REG_CALL_SCRIPT = new RegExp("&\{.*\};", "i");
var REG_EVENT = new RegExp("onError|onUnload|onBlur|onFocus|onClick|onMouseOver|onMouseOut|onSubmit|onReset|onChange|onSelect|onAbort", "i");
// Cookie Basic
var REG_AUTH = new RegExp("document\.cookie|Microsoft\.XMLHTTP", "i");
// TEXTAREA
var REG_NEWLINE = new RegExp("\x0d|\x0a", "i");
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Info', oEditor.FCKLang.DlgInfoTab ) ;
// Get the selected flash embed (if available).
var oFakeImage = FCK.Selection.GetSelectedElement() ;
var oEmbed ;
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
dialog.SetAutoSize( true ) ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
SelectField( 'txtUrl' ) ;
}
//#### The OK button was hit.
function Ok()
{
if ( GetE('txtUrl').value.length == 0 )
{
dialog.SetSelectedTab( 'Info' ) ;
GetE('txtUrl').focus() ;
alert( oEditor.FCKLang.DlgYouTubeCode ) ;
return false ;
}
// check security
if (checkCode(GetE('txtUrl').value) == false) {
alert( oEditor.FCKLang.DlgYouTubeSecurity ) ;
return false;
}
oEditor.FCKUndo.SaveUndoStep() ;
if ( !oEmbed )
{
oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ;
oFakeImage = null ;
}
UpdateEmbed( oEmbed ) ;
if ( !oFakeImage )
{
oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ;
oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ;
oFakeImage = FCK.InsertElement( oFakeImage ) ;
}
oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ;
return true ;
}
function UpdateEmbed( e )
{
var youtubeUrl = GetE('txtUrl').value;
var youtubeId = youtubeUrl.slice(youtubeUrl.search(/\?v=/i)+3);
SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ;
SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ;
if ( GetE('radioHigh').checked ) {
SetAttribute( e, 'src' , 'http://www.youtube.com/v/'+youtubeId+'%26hl=en%26fs=1%26rel=0%26ap=%2526fmt=18') ;
} else {
SetAttribute( e, 'src' , 'http://www.youtube.com/v/'+youtubeId+'%26hl=en%26fs=1%26rel=0') ;
}
SetAttribute( e, "width" , GetE('txtWidth').value == '' ? 425 : GetE('txtWidth').value ) ;
SetAttribute( e, "height" , GetE('txtHeight').value == '' ? 344 : GetE('txtHeight').value ) ;
}
function checkCode(code)
{
if (code.search(REG_SCRIPT) != -1) {
return false;
}
if (code.search(REG_PROTOCOL) != -1) {
return false;
}
if (code.search(REG_CALL_SCRIPT) != -1) {
return false;
}
if (code.search(REG_EVENT) != -1) {
return false;
}
if (code.search(REG_AUTH) != -1) {
return false;
}
if (code.search(REG_NEWLINE) != -1) {
return false;
}
} | JavaScript |
/*
* For FCKeditor 2.3
*
*
* File Name: ja.js
* English language file for the youtube plugin.
*
* File Authors:
* Uprush (uprushworld@yahoo.co.jp) 2007/10/30
*/
FCKLang['YouTubeTip'] = '插入YouTube網址' ;
FCKLang['DlgYouTubeTitle'] = 'YouTube內容' ;
FCKLang['DlgYouTubeCode'] = '"請插入/貼上YouTube影片連結網址"' ;
FCKLang['DlgYouTubeSecurity'] = '不合法的連結網址' ;
FCKLang['DlgYouTubeURL'] = '貼上YouTube連結網址' ;
FCKLang['DlgYouTubeWidth'] = '寬度' ;
FCKLang['DlgYouTubeHeight'] = '高度' ;
FCKLang['DlgYouTubeQuality'] = '影片品質' ;
FCKLang['DlgYouTubeLow'] = '低' ;
FCKLang['DlgYouTubeHigh'] = '高 (如果有提供)' ;
| JavaScript |
/*
* For FCKeditor 2.3
*
*
* File Name: pt.js
* Portuguese language file for the youtube plugin.
*
* File Authors:
* Ivo Emanuel Gonçalves (justivo (at) gmail.com) 2009/01/19
*/
FCKLang['YouTubeTip'] = 'Inserir/Editar YouTube' ;
FCKLang['DlgYouTubeTitle'] = 'Propriedade YouTube' ;
FCKLang['DlgYouTubeCode'] = '"Por favor insira o endereço do video YouTube."' ;
FCKLang['DlgYouTubeSecurity'] = 'Endereço inválido.' ;
FCKLang['DlgYouTubeURL'] = 'Endereço' ;
FCKLang['DlgYouTubeWidth'] = 'Largura' ;
FCKLang['DlgYouTubeHeight'] = 'Altura' ;
FCKLang['DlgYouTubeQuality'] = 'Qualidade' ;
FCKLang['DlgYouTubeLow'] = 'Baixa' ;
FCKLang['DlgYouTubeHigh'] = 'Alta (se disponível)' ;
| JavaScript |
/*
* For FCKeditor 2.3
*
*
* File Name: de.js
* German language file for the youtube plugin.
*
* File Authors:
* Miro Dietiker (miro.dietiker (at) md-systems.ch) 2009/07/06
*/
FCKLang['YouTubeTip'] = 'YouTube Einfügen/Bearbeiten' ;
FCKLang['DlgYouTubeTitle'] = 'YouTube Einstellung' ;
FCKLang['DlgYouTubeCode'] = '"Bitte die YouTube Video URLs einfügen."' ;
FCKLang['DlgYouTubeSecurity'] = 'Ungültige URL.' ;
FCKLang['DlgYouTubeURL'] = 'URL' ;
FCKLang['DlgYouTubeWidth'] = 'Breite' ;
FCKLang['DlgYouTubeHeight'] = 'Höhe' ;
FCKLang['DlgYouTubeQuality'] = 'Qualität' ;
FCKLang['DlgYouTubeLow'] = 'Niedrig' ;
FCKLang['DlgYouTubeHigh'] = 'Hoch (Wenn verfügbar)' ;
| JavaScript |
/*
* For FCKeditor 2.3
*
*
* File Name: no.js
* Norwegian language file for the youtube plugin.
*
* File Authors:
* Odd-Henrik (odd at multicase.no) 2009/02/12
*/
FCKLang['YouTubeTip'] = 'Legg til/Rediger YouTube video' ;
FCKLang['DlgYouTubeTitle'] = 'YouTube video egenskaper' ;
FCKLang['DlgYouTubeCode'] = '"Skriv inn URLen til YouTube videoen."' ;
FCKLang['DlgYouTubeSecurity'] = 'Feil URL.' ;
FCKLang['DlgYouTubeURL'] = 'URL' ;
FCKLang['DlgYouTubeWidth'] = 'Bredde' ;
FCKLang['DlgYouTubeHeight'] = 'Høyde';
FCKLang['DlgYouTubeQuality'] = 'Kvalitet' ;
FCKLang['DlgYouTubeLow'] = 'Lav' ;
FCKLang['DlgYouTubeHigh'] = 'Høy (Hvis tilgjengelig)';
| JavaScript |
/*
* For FCKeditor 2.6
*
*
* File Name: lt.js
* Lithuanian language file for the youtube plugin.
*
* File Authors:
* teibaz (tomas@1985.lt) 2009/01/26
*/
FCKLang['YouTubeTip'] = 'Įterpti/Koreguoti YouTube' ;
FCKLang['DlgYouTubeTitle'] = 'YouTube Nustatymai' ;
FCKLang['DlgYouTubeCode'] = '"Įveskite YouTube video URL adresą."' ;
FCKLang['DlgYouTubeSecurity'] = 'Nekorektiškas URL' ;
FCKLang['DlgYouTubeURL'] = 'URL' ;
FCKLang['DlgYouTubeWidth'] = 'Plotis' ;
FCKLang['DlgYouTubeHeight'] = 'Aukštis' ;
FCKLang['DlgYouTubeQuality'] = 'Kokybė' ;
FCKLang['DlgYouTubeLow'] = 'Žema' ;
FCKLang['DlgYouTubeHigh'] = 'Aukšta (jei įmanoma)' ;
| JavaScript |
/*
* For FCKeditor 2.3
*
*
* File Name: it.js
* Italian language file for the youtube plugin.
*
* File Authors:
* Fabrizio Balliano (fabrizio.balliano@crealabs.it) 2008/01/29
*/
FCKLang['YouTubeTip'] = 'Inserisci un video di YouTube' ;
FCKLang['DlgYouTubeTitle'] = 'Proprietà video YouTube' ;
FCKLang['DlgYouTubeCode'] = '"Digita l\'URL del video YouTube."' ;
FCKLang['DlgYouTubeSecurity'] = 'Invalid URL.' ;
FCKLang['DlgYouTubeURL'] = 'URL' ;
FCKLang['DlgYouTubeWidth'] = 'Larghezza' ;
FCKLang['DlgYouTubeHeight'] = 'Altezza' ;
FCKLang['DlgYouTubeQuality'] = 'Qualità' ;
FCKLang['DlgYouTubeLow'] = 'Bassa' ;
FCKLang['DlgYouTubeHigh'] = 'Alta (se disponibile)' ;
FCKLang['DlgInfoTab'] = 'Informazioni' ;
| JavaScript |
/*
* For FCKeditor 2.3
*
*
* File Name: zh-cn.js
* Chinese(simplify) language file for the youtube plugin.
*
* File Authors:
* Uprush (uprushworld@yahoo.co.jp) 2008/03/22
*/
FCKLang['YouTubeTip'] = 'YouTube插入/编辑' ;
FCKLang['DlgYouTubeTitle'] = 'YouTube属性' ;
FCKLang['DlgYouTubeCode'] = '请插入 YouTube 动画的URL。' ;
FCKLang['DlgYouTubeSecurity'] = '不正确的URL。' ;
FCKLang['DlgYouTubeURL'] = 'URL' ;
FCKLang['DlgYouTubeWidth'] = '宽' ;
FCKLang['DlgYouTubeHeight'] = '高' ;
FCKLang['DlgYouTubeQuality'] = '画质' ;
FCKLang['DlgYouTubeLow'] = '低' ;
FCKLang['DlgYouTubeHigh'] = '高 (如果可能)' ;
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.