Skip to content

Instantly share code, notes, and snippets.

@markbrown4
Created April 8, 2010 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markbrown4/359639 to your computer and use it in GitHub Desktop.
Save markbrown4/359639 to your computer and use it in GitHub Desktop.
/*
* mQuery, My journey into the world of js libraries
* Selectors, Events, DOM, Ajax and Animation
*/
var $ = (function() {
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
var chunker=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,done=0,toString=Object.prototype.toString,hasDuplicate=false,baseHasDuplicate=true;[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 parts=[],m,set,checkSet,extra,prune=true,contextXML=Sizzle.isXML(context),soFar=selector,ret,cur,pop,i;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{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.find=function(expr,context,isXML){var set;if(!expr){return[];}
for(var i=0,l=Expr.order.length;i<l;i++){var type=Expr.order[i],match;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(/\\/g,"");set=Expr.find[type](match,context,isXML);if(set!=null){expr=expr.replace(Expr.match[type],"");break;}}}}
if(!set){set=context.getElementsByTagName("*");}
return{set:set,expr:expr};};Sizzle.filter=function(expr,set,inplace,not){var old=expr,result=[],curLoop=set,match,anyFound,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 filter=Expr.filter[type],found,item,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;}}}
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|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,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");}},relative:{"+":function(checkSet,part){var isPartStr=typeof part==="string",isTag=isPartStr&&!/\W/.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 isPartStr=typeof part==="string",elem,i=0,l=checkSet.length;if(isPartStr&&!/\W/.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 doneName=done++,checkFn=dirCheck,nodeCheck;if(typeof part==="string"&&!/\W/.test(part)){part=part.toLowerCase();nodeCheck=part;checkFn=dirNodeCheck;}
checkFn("parentNode",part,doneName,checkSet,nodeCheck,isXML);},"~":function(checkSet,part,isXML){var doneName=done++,checkFn=dirCheck,nodeCheck;if(typeof part==="string"&&!/\W/.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]);return m?[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){return context.getElementsByTagName(match[1]);}},preFilter:{CLASS:function(match,curLoop,inplace,result,not,isXML){match=" "+match[1].replace(/\\/g,"")+" ";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]/g," ").indexOf(match)>=0)){if(!inplace){result.push(elem);}}else if(inplace){curLoop[i]=false;}}}
return false;},ID:function(match){return match[1].replace(/\\/g,"");},TAG:function(match,curLoop){return match[1].toLowerCase();},CHILD:function(match){if(match[1]==="nth"){var test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(match[2]==="even"&&"2n"||match[2]==="odd"&&"2n+1"||!/\D/.test(match[2])&&"0n+"+match[2]||match[2]);match[2]=(test[1]+(test[2]||1))-0;match[3]=test[3]-0;}
match[0]=done++;return match;},ATTR:function(match,curLoop,inplace,result,not,isXML){var name=match[1].replace(/\\/g,"");if(!isXML&&Expr.attrMap[name]){match[1]=Expr.attrMap[name];}
if(match[2]==="~="){match[4]=" "+match[4]+" ";}
return match;},PSEUDO:function(match,curLoop,inplace,result,not){if(match[1]==="not"){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){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){return"text"===elem.type;},radio:function(elem){return"radio"===elem.type;},checkbox:function(elem){return"checkbox"===elem.type;},file:function(elem){return"file"===elem.type;},password:function(elem){return"password"===elem.type;},submit:function(elem){return"submit"===elem.type;},image:function(elem){return"image"===elem.type;},reset:function(elem){return"reset"===elem.type;},button:function(elem){return"button"===elem.type||elem.nodeName.toLowerCase()==="button";},input:function(elem){return(/input|select|textarea|button/i).test(elem.nodeName);}},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("Syntax error, unrecognized expression: "+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;};try{Array.prototype.slice.call(document.documentElement.childNodes,0)[0].nodeType;}catch(e){makeArray=function(array,results){var ret=results||[],i=0;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;if(document.documentElement.compareDocumentPosition){sortOrder=function(a,b){if(!a.compareDocumentPosition||!b.compareDocumentPosition){if(a==b){hasDuplicate=true;}
return a.compareDocumentPosition?-1:1;}
var ret=a.compareDocumentPosition(b)&4?-1:a===b?0:1;if(ret===0){hasDuplicate=true;}
return ret;};}else if("sourceIndex"in document.documentElement){sortOrder=function(a,b){if(!a.sourceIndex||!b.sourceIndex){if(a==b){hasDuplicate=true;}
return a.sourceIndex?-1:1;}
var ret=a.sourceIndex-b.sourceIndex;if(ret===0){hasDuplicate=true;}
return ret;};}else if(document.createRange){sortOrder=function(a,b){if(!a.ownerDocument||!b.ownerDocument){if(a==b){hasDuplicate=true;}
return a.ownerDocument?-1:1;}
var aRange=a.ownerDocument.createRange(),bRange=b.ownerDocument.createRange();aRange.setStart(a,0);aRange.setEnd(a,0);bRange.setStart(b,0);bRange.setEnd(b,0);var ret=aRange.compareBoundaryPoints(Range.START_TO_END,bRange);if(ret===0){hasDuplicate=true;}
return ret;};}
Sizzle.getText=function(elems){var ret="",elem;for(var i=0;elems[i];i++){elem=elems[i];if(elem.nodeType===3||elem.nodeType===4){ret+=elem.nodeValue;}else if(elem.nodeType!==8){ret+=Sizzle.getText(elem.childNodes);}}
return ret;};(function(){var form=document.createElement("div"),id="script"+(new Date()).getTime();form.innerHTML="<a name='"+id+"'/>";var root=document.documentElement;root.insertBefore(form,root.firstChild);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);root=form=null;})();(function(){var div=document.createElement("div");div.appendChild(document.createComment(""));if(div.getElementsByTagName("*").length>0){Expr.find.TAG=function(match,context){var results=context.getElementsByTagName(match[1]);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;};}
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);};}
div=null;})();if(document.querySelectorAll){(function(){var oldSizzle=Sizzle,div=document.createElement("div");div.innerHTML="<p class='TEST'></p>";if(div.querySelectorAll&&div.querySelectorAll(".TEST").length===0){return;}
Sizzle=function(query,context,extra,seed){context=context||document;if(!seed&&context.nodeType===9&&!Sizzle.isXML(context)){try{return makeArray(context.querySelectorAll(query),extra);}catch(e){}}
return oldSizzle(query,context,extra,seed);};for(var prop in oldSizzle){Sizzle[prop]=oldSizzle[prop];}
div=null;})();}
(function(){var div=document.createElement("div");div.innerHTML="<div class='test e'></div><div class='test'></div>";if(!div.getElementsByClassName||div.getElementsByClassName("e").length===0){return;}
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]);}};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){elem=elem[dir];var match=false;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){elem=elem[dir];var match=false;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;}}}
Sizzle.contains=document.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16);}:function(a,b){return a!==b&&(a.contains?a.contains(b):true);};Sizzle.isXML=function(elem){var documentElement=(elem?elem.ownerDocument||elem:0).documentElement;return documentElement?documentElement.nodeName!=="HTML":false;};var posProcess=function(selector,context){var tmpSet=[],later="",match,root=context.nodeType?[context]:context;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);};
/*!
* Animator.js 1.1.9
* This library is released under the BSD license:
* Copyright (c) 2006, Bernard Sumption. All rights reserved.
*/
function Animator(options){this.setOptions(options);var _this=this;this.timerDelegate=function(){_this.onTimerEvent()};this.subjects=[];this.target=0;this.state=0;this.lastTime=null;};Animator.prototype={setOptions:function(options){this.options=Animator.applyDefaults({interval:20,duration:400,onComplete:function(){},onStep:function(){},transition:'easeInOut'},options);},seekTo:function(to){this.seekFromTo(this.state,to);},seekFromTo:function(from,to){this.target=Math.max(0,Math.min(1,to));this.state=Math.max(0,Math.min(1,from));this.lastTime=new Date().getTime();if(!this.intervalId){this.intervalId=window.setInterval(this.timerDelegate,this.options.interval);}},jumpTo:function(to){this.target=this.state=Math.max(0,Math.min(1,to));this.propagate();},toggle:function(){this.seekTo(1-this.target);},addSubject:function(subject){this.subjects[this.subjects.length]=subject;return this;},clearSubjects:function(){this.subjects=[];},propagate:function(){var value=Animator.tx[this.options.transition](this.state);for(var i=0;i<this.subjects.length;i++){if(this.subjects[i].setState){this.subjects[i].setState(value);}else{this.subjects[i](value);}}},onTimerEvent:function(){var now=new Date().getTime();var timePassed=now-this.lastTime;this.lastTime=now;var movement=(timePassed/this.options.duration)*(this.state<this.target?1:-1);if(Math.abs(movement)>=Math.abs(this.state-this.target)){this.state=this.target;}else{this.state+=movement;}
try{this.propagate();}finally{this.options.onStep.call(this);if(this.target==this.state){window.clearInterval(this.intervalId);this.intervalId=null;this.options.onComplete.call(this);}}},play:function(){this.seekFromTo(0,1)},reverse:function(){this.seekFromTo(1,0)},inspect:function(){var str="#<Animator:\n";for(var i=0;i<this.subjects.length;i++){str+=this.subjects[i].inspect();}
str+=">";return str;}}
Animator.applyDefaults=function(defaults,prefs){prefs=prefs||{};var prop,result={};for(prop in defaults)result[prop]=prefs[prop]!==undefined?prefs[prop]:defaults[prop];return result;}
Animator.makeArray=function(o){if(o==null)return[];if(!o.length)return[o];var result=[];for(var i=0;i<o.length;i++)result[i]=o[i];return result;}
Animator.camelize=function(string){var oStringList=string.split('-');if(oStringList.length==1)return oStringList[0];var camelizedString=string.indexOf('-')==0?oStringList[0].charAt(0).toUpperCase()+oStringList[0].substring(1):oStringList[0];for(var i=1,len=oStringList.length;i<len;i++){var s=oStringList[i];camelizedString+=s.charAt(0).toUpperCase()+s.substring(1);}
return camelizedString;}
Animator.apply=function(el,style,options){if(style instanceof Array){return new Animator(options).addSubject(new CSSStyleSubject(el,style[0],style[1]));}
return new Animator(options).addSubject(new CSSStyleSubject(el,style));}
Animator.makeEaseIn=function(a){return function(state){return Math.pow(state,a*2);}}
Animator.makeEaseOut=function(a){return function(state){return 1-Math.pow(1-state,a*2);}}
Animator.makeElastic=function(bounces){return function(state){state=Animator.tx.easeInOut(state);return((1-Math.cos(state*Math.PI*bounces))*(1-state))+state;}}
Animator.makeADSR=function(attackEnd,decayEnd,sustainEnd,sustainLevel){if(sustainLevel==null)sustainLevel=0.5;return function(state){if(state<attackEnd){return state/attackEnd;}
if(state<decayEnd){return 1-((state-attackEnd)/(decayEnd-attackEnd)*(1-sustainLevel));}
if(state<sustainEnd){return sustainLevel;}
return sustainLevel*(1-((state-sustainEnd)/(1-sustainEnd)));}}
Animator.makeBounce=function(bounces){var fn=Animator.makeElastic(bounces);return function(state){state=fn(state);return state<=1?state:2-state;}}
Animator.tx={easeInOut:function(pos){return((-Math.cos(pos*Math.PI)/2)+0.5);},linear:function(x){return x;},easeIn:Animator.makeEaseIn(1.5),easeOut:Animator.makeEaseOut(1.5),strongEaseIn:Animator.makeEaseIn(2.5),strongEaseOut:Animator.makeEaseOut(2.5),elastic:Animator.makeElastic(1),veryElastic:Animator.makeElastic(3),bouncy:Animator.makeBounce(1),veryBouncy:Animator.makeBounce(3)}
function NumericalStyleSubject(els,property,from,to,units){this.els=Animator.makeArray(els);if(property=='opacity'&&window.ActiveXObject){this.property='filter';}else{this.property=Animator.camelize(property);}
this.from=parseFloat(from);this.to=parseFloat(to);this.units=units!=null?units:'px';}
NumericalStyleSubject.prototype={setState:function(state){var style=this.getStyle(state);var visibility=(this.property=='opacity'&&state==0)?'hidden':'';var j=0;for(var i=0;i<this.els.length;i++){try{this.els[i].style[this.property]=style;}catch(e){if(this.property!='fontWeight')throw e;}
if(j++>20)return;}},getStyle:function(state){state=this.from+((this.to-this.from)*state);if(this.property=='filter')return"alpha(opacity="+Math.round(state*100)+")";if(this.property=='opacity')return state;return Math.round(state)+this.units;},inspect:function(){return"\t"+this.property+"("+this.from+this.units+" to "+this.to+this.units+")\n";}}
function ColorStyleSubject(els,property,from,to){this.els=Animator.makeArray(els);this.property=Animator.camelize(property);this.to=this.expandColor(to);this.from=this.expandColor(from);this.origFrom=from;this.origTo=to;}
ColorStyleSubject.prototype={expandColor:function(color){var hexColor,red,green,blue;hexColor=ColorStyleSubject.parseColor(color);if(hexColor){red=parseInt(hexColor.slice(1,3),16);green=parseInt(hexColor.slice(3,5),16);blue=parseInt(hexColor.slice(5,7),16);return[red,green,blue]}
if(window.DEBUG){alert("Invalid colour: '"+color+"'");}},getValueForState:function(color,state){return Math.round(this.from[color]+((this.to[color]-this.from[color])*state));},setState:function(state){var color='#'
+ColorStyleSubject.toColorPart(this.getValueForState(0,state))
+ColorStyleSubject.toColorPart(this.getValueForState(1,state))
+ColorStyleSubject.toColorPart(this.getValueForState(2,state));for(var i=0;i<this.els.length;i++){this.els[i].style[this.property]=color;}},inspect:function(){return"\t"+this.property+"("+this.origFrom+" to "+this.origTo+")\n";}}
ColorStyleSubject.parseColor=function(string){var color='#',match;if(match=ColorStyleSubject.parseColor.rgbRe.exec(string)){var part;for(var i=1;i<=3;i++){part=Math.max(0,Math.min(255,parseInt(match[i])));color+=ColorStyleSubject.toColorPart(part);}
return color;}
if(match=ColorStyleSubject.parseColor.hexRe.exec(string)){if(match[1].length==3){for(var i=0;i<3;i++){color+=match[1].charAt(i)+match[1].charAt(i);}
return color;}
return'#'+match[1];}
return false;}
ColorStyleSubject.toColorPart=function(number){if(number>255)number=255;var digits=number.toString(16);if(number<16)return'0'+digits;return digits;}
ColorStyleSubject.parseColor.rgbRe=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;ColorStyleSubject.parseColor.hexRe=/^\#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function DiscreteStyleSubject(els,property,from,to,threshold){this.els=Animator.makeArray(els);this.property=Animator.camelize(property);this.from=from;this.to=to;this.threshold=threshold||0.5;}
DiscreteStyleSubject.prototype={setState:function(state){var j=0;for(var i=0;i<this.els.length;i++){this.els[i].style[this.property]=state<=this.threshold?this.from:this.to;}},inspect:function(){return"\t"+this.property+"("+this.from+" to "+this.to+" @ "+this.threshold+")\n";}}
function CSSStyleSubject(els,style1,style2){els=Animator.makeArray(els);this.subjects=[];if(els.length==0)return;var prop,toStyle,fromStyle;if(style2){fromStyle=this.parseStyle(style1,els[0]);toStyle=this.parseStyle(style2,els[0]);}else{toStyle=this.parseStyle(style1,els[0]);fromStyle={};for(prop in toStyle){fromStyle[prop]=CSSStyleSubject.getStyle(els[0],prop);}}
var prop;for(prop in fromStyle){if(fromStyle[prop]==toStyle[prop]){delete fromStyle[prop];delete toStyle[prop];}}
var prop,units,match,type,from,to;for(prop in fromStyle){var fromProp=String(fromStyle[prop]);var toProp=String(toStyle[prop]);if(toStyle[prop]==null){if(window.DEBUG)alert("No to style provided for '"+prop+'"');continue;}
if(from=ColorStyleSubject.parseColor(fromProp)){to=ColorStyleSubject.parseColor(toProp);type=ColorStyleSubject;}else if(fromProp.match(CSSStyleSubject.numericalRe)&&toProp.match(CSSStyleSubject.numericalRe)){from=parseFloat(fromProp);to=parseFloat(toProp);type=NumericalStyleSubject;match=CSSStyleSubject.numericalRe.exec(fromProp);var reResult=CSSStyleSubject.numericalRe.exec(toProp);if(match[1]!=null){units=match[1];}else if(reResult[1]!=null){units=reResult[1];}else{units=reResult;}}else if(fromProp.match(CSSStyleSubject.discreteRe)&&toProp.match(CSSStyleSubject.discreteRe)){from=fromProp;to=toProp;type=DiscreteStyleSubject;units=0;}else{if(window.DEBUG){alert("Unrecognised format for value of "
+prop+": '"+fromStyle[prop]+"'");}
continue;}
this.subjects[this.subjects.length]=new type(els,prop,from,to,units);}}
CSSStyleSubject.prototype={parseStyle:function(style,el){var rtn={};if(style.indexOf(":")!=-1){var styles=style.split(";");for(var i=0;i<styles.length;i++){var parts=CSSStyleSubject.ruleRe.exec(styles[i]);if(parts){rtn[parts[1]]=parts[2];}}}
else{var prop,value,oldClass;oldClass=el.className;el.className=style;for(var i=0;i<CSSStyleSubject.cssProperties.length;i++){prop=CSSStyleSubject.cssProperties[i];value=CSSStyleSubject.getStyle(el,prop);if(value!=null){rtn[prop]=value;}}
el.className=oldClass;}
return rtn;},setState:function(state){for(var i=0;i<this.subjects.length;i++){this.subjects[i].setState(state);}},inspect:function(){var str="";for(var i=0;i<this.subjects.length;i++){str+=this.subjects[i].inspect();}
return str;}}
CSSStyleSubject.getStyle=function(el,property){var style;if(document.defaultView&&document.defaultView.getComputedStyle){style=document.defaultView.getComputedStyle(el,"").getPropertyValue(property);if(style){return style;}}
property=Animator.camelize(property);if(el.currentStyle){style=el.currentStyle[property];}
return style||el.style[property]}
CSSStyleSubject.ruleRe=/^\s*([a-zA-Z\-]+)\s*:\s*(\S(.+\S)?)\s*$/;CSSStyleSubject.numericalRe=/^-?\d+(?:\.\d+)?(%|[a-zA-Z]{2})?$/;CSSStyleSubject.discreteRe=/^\w+$/;CSSStyleSubject.cssProperties=['azimuth','background','background-attachment','background-color','background-image','background-position','background-repeat','border-collapse','border-color','border-spacing','border-style','border-top','border-top-color','border-right-color','border-bottom-color','border-left-color','border-top-style','border-right-style','border-bottom-style','border-left-style','border-top-width','border-right-width','border-bottom-width','border-left-width','border-width','bottom','clear','clip','color','content','cursor','direction','display','elevation','empty-cells','css-float','font','font-family','font-size','font-size-adjust','font-stretch','font-style','font-variant','font-weight','height','left','letter-spacing','line-height','list-style','list-style-image','list-style-position','list-style-type','margin','margin-top','margin-right','margin-bottom','margin-left','max-height','max-width','min-height','min-width','orphans','outline','outline-color','outline-style','outline-width','overflow','padding','padding-top','padding-right','padding-bottom','padding-left','pause','position','right','size','table-layout','text-align','text-decoration','text-indent','text-shadow','text-transform','top','vertical-align','visibility','white-space','width','word-spacing','z-index','opacity','outline-offset','overflow-x','overflow-y'];
// utility functions
var push = Array.prototype.push,
emptyFunction = function() {},
extend = function(b, a) {
for (var p in a || {}) b[p] = a[p];
return b;
},
$ = function(elm) {
if (typeof(elm) == 'string') {
return new ElementList(Sizzle(elm));
}
else if (typeof(elm) == 'function') {
return $.addEvent(window, 'load', elm);
}
return new ElementList(elm);
},
// wrapper
ElementList = function(elm) {
if (elm) {
elm = elm.nodeName ? [elm] : elm;
push.apply(this, elm);
}
return this;
};
// wrapper functions
ElementList.prototype = {
each: function(fn) {
for (var i = 0, l = this.length; i < l; i++) {
fn.call(this[i],this[i]);
}
return this;
},
addClass: function(theClass) {
var regex = RegExp("(^| )" + theClass + "( |$)");
return this.each(function(){
if (!regex.test(this.className)) {
this.className = (this.className == "") ? theClass : this.className + " " + theClass;
}
});
},
hasClass: function(theClass) {
var has = 0, regex = RegExp("(^| )" + theClass + "( |$)");
this.each(function(){
if (regex.test(this.className)) ++has;
});
return has == this.length;
},
removeClass: function(theClass) {
var regex = RegExp("(^| )" + theClass + "( |$)");
return this.each(function(){
this.className = this.className.replace(regex, "$1").replace(/ $/, "");
});
},
computedStyle: function(styleProperty) {
var computedStyle = (typeof this[0].currentStyle != "undefined") ? computedStyle = this[0].currentStyle : document.defaultView.getComputedStyle(this[0], null);
return computedStyle[styleProperty];
},
up: function(selector) {
var nodes = new ElementList();
this.each(function() {
var elm = this, found = false;
while ((elm = elm.parentNode) && (!found)) {
var matches = Sizzle.matches(selector, [elm]);
if (matches.length > 0) {
push.apply(nodes, [matches[0]]);
found = true;
}
}
});
return nodes;
},
down: function(selector) {
var nodes = new ElementList();
this.each(function(){
var elements = Sizzle(selector, this);
push.apply(nodes, elements);
});
return nodes;
},
setStyle: function(styles) {
return this.each(function() {
extend(this.style, styles);
});
},
addEvent:function(type, fn) {
type = (typeof(type)=='string') ? [type]: type;
return this.each(function() {
for (var i = 0, l = type.length; i < l; i++)
$.addEvent(this,type[i],fn);
});
},
removeEvent: function(type, fn) {
return this.each(function() {
$.removeEvent(this,type,fn);
});
},
fireEvent: function(name) {
return this.each(function() {
$.fireEvent(this, name);
});
},
load: function(url, options) {
return this.each(function(elm) {
elm = $(elm);
$.ajax(url, extend(options, {
onStart: function(xhr) {
elm.addClass('loading');
},
onSuccess: function(xhr) {
elm[0].innerHTML = xhr.responseText;
},
onEnd: function(xhr) {
elm.removeClass('loading');
}})
);
});
},
animate: function(to, options) {
return this.each(function() {
Animator.apply(this, to, options).toggle();
});
},
saveAnimation: function(to, options) {
return this.each(function() {
this._effect = Animator.apply(this, to, options);
});
},
toggleAnimation: function() {
return this.each(function() {
this._effect.toggle();
});
}
};
// Events
if (window.addEventListener) {
$.addEvent = function(obj, type, fn) {
obj.addEventListener(type, fn, false);
}
$.removeEvent = function(obj, type, fn) {
obj.removeEventListener(type, fn, false);
}
$.stopEvent = function(event) {
event.preventDefault();
event.stopPropagation();
}
}
else {
$.addEvent = function(obj, type, fn) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
}
$.removeEvent = function(obj, type, fn) {
obj.detachEvent('on'+type, this[type+fn]);
obj[type+fn] = null;
}
$.stopEvent = function(event) {
event.returnValue = false;
event.cancelBubble = true;
}
}
if (document.createEventObject) {
$.fireEvent = function (elm, name) {
var evt = document.createEventObject();
return elm.fireEvent('on'+name,evt);
}
}
else {
$.fireEvent = function (elm, name) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true );
return !elm.dispatchEvent(evt);
}
}
// Ajax
var getXHR = function() { return false };
if (window.XMLHttpRequest) {
getXHR = function() { return new XMLHttpRequest(); }
}
else if (window.ActiveXObject) {
getXHR = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e) {
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e) {}
}
}
}
$.ajax = function(url, options) {
options = extend({
type: 'get',
onStart: emptyFunction,
onEnd: emptyFunction,
onSuccess: emptyFunction,
onFailure: emptyFunction
}, options);
var xhr = getXHR();
if (!xhr) return;
xhr.open(options.type, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
options.onSuccess(xhr);
}
else {
options.onFailure(xhr);
}
options.onEnd(xhr);
}
};
try {
xhr.send(null);
options.onStart(xhr);
}
catch(e) {
options.onFailure(xhr);
}
};
// Native object extensions
String.prototype.format = function() {
var pattern = /\{\d+\}/g, args = arguments;
return this.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });
}
return $;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment