// -- Sammy -- /sammy.js
// http://code.quirkey.com/sammy
// Version: 0.5.0
// Built: Mon Feb 15 13:56:01 -0500 2010
(function(g){var d="([^/]+)",f=/:([\w\d]+)/g,c=/\?([^#]*)$/,a=decodeURIComponent,b=function(h){return function(i,j){return this.route.apply(this,[h,i,j])}},e=[];Sammy=function(){var i=g.makeArray(arguments),j,h;Sammy.apps=Sammy.apps||{};if(i.length==0||i[0]&&g.isFunction(i[0])){return Sammy.apply(Sammy,["body"].concat(i))}else{if(typeof(h=i.shift())=="string"){j=Sammy.apps[h]||new Sammy.Application();j.element_selector=h;if(i.length>0){g.each(i,function(k,l){j.use(l)})}if(j.element_selector!=h){delete Sammy.apps[h]}Sammy.apps[j.element_selector]=j;return j}}};Sammy.VERSION="0.5.0";Sammy.addLogger=function(h){e.push(h)};Sammy.log=function(){var h=g.makeArray(arguments);h.unshift("["+Date()+"]");g.each(e,function(k,j){j.apply(Sammy,h)})};if(typeof window.console!="undefined"){if(g.isFunction(console.log.apply)){Sammy.addLogger(function(){window.console.log.apply(console,arguments)})}else{Sammy.addLogger(function(){window.console.log(arguments)})}}else{if(typeof console!="undefined"){Sammy.addLogger(function(){console.log.apply(console,arguments)})}}Sammy.Object=function(h){return g.extend(this,h||{})};g.extend(Sammy.Object.prototype,{toHash:function(){var h={};g.each(this,function(j,i){if(!g.isFunction(i)){h[j]=i}});return h},toHTML:function(){var h="";g.each(this,function(j,i){if(!g.isFunction(i)){h+="<strong>"+j+"</strong> "+i+"<br />"}});return h},uuid:function(){if(typeof this._uuid=="undefined"||!this._uuid){this._uuid=(new Date()).getTime()+"-"+parseInt(Math.random()*1000)}return this._uuid},keys:function(h){var i=[];for(var j in this){if(!g.isFunction(this[j])||!h){i.push(j)}}return i},has:function(h){return this[h]&&g.trim(this[h].toString())!=""},join:function(){var i=g.makeArray(arguments);var h=i.shift();return i.join(h)},log:function(){Sammy.log.apply(Sammy,arguments)},toString:function(h){var i=[];g.each(this,function(l,j){if(!g.isFunction(j)||h){i.push('"'+l+'": '+j.toString())}});return"Sammy.Object: {"+i.join(",")+"}"}});Sammy.HashLocationProxy=function(i,h){this.app=i;if("onhashchange" in window){Sammy.log("native hash change exists, using");this.is_native=true}else{Sammy.log("no native hash change, falling back to polling");this.is_native=false;this._startPolling(h)}};Sammy.HashLocationProxy.prototype={bind:function(){var h=this.app;g(window).bind("hashchange."+this.app.eventNamespace(),function(){h.trigger("location-changed")})},unbind:function(){g(window).die("hashchange."+this.app.eventNamespace())},getLocation:function(){var h=window.location.toString().match(/^[^#]*(#.+)$/);return h?h[1]:""},setLocation:function(h){return window.location=h},_startPolling:function(j){var i=this;if(!Sammy.HashLocationProxy._interval){if(!j){j=10}var h=function(){current_location=i.getLocation();if(!Sammy.HashLocationProxy._last_location||current_location!=Sammy.HashLocationProxy._last_location){setTimeout(function(){g(window).trigger("hashchange")},1)}Sammy.HashLocationProxy._last_location=current_location};h();Sammy.HashLocationProxy._interval=setInterval(h,j);g(window).bind("unload",function(){clearInterval(Sammy.HashLocationProxy._interval)})}}};Sammy.DataLocationProxy=function(i,h){this.app=i;this.data_name=h||"sammy-location"};Sammy.DataLocationProxy.prototype={bind:function(){var h=this;this.app.$element().bind("setData",function(j,i){if(i==h.data_name){h.app.trigger("location-changed")}})},unbind:function(){this.app.$element().die("setData")},getLocation:function(){return this.app.$element().data(this.data_name)},setLocation:function(h){return this.app.$element().data(this.data_name,h)}};Sammy.Application=function(h){var i=this;this.routes={};this.listeners=new Sammy.Object({});this.arounds=[];this.befores=[];this.namespace=this.uuid();this.context_prototype=function(){Sammy.EventContext.apply(this,arguments)};this.context_prototype.prototype=new Sammy.EventContext();if(g.isFunction(h)){h.apply(this,[this])}if(!this.location_proxy){this.location_proxy=new Sammy.HashLocationProxy(i,this.run_interval_every)}if(this.debug){this.bindToAllEvents(function(k,j){i.log(i.toString(),k.cleaned_type,j||{})})}};Sammy.Application.prototype=g.extend({},Sammy.Object.prototype,{ROUTE_VERBS:["get","post","put","delete"],APP_EVENTS:["run","unload","lookup-route","run-route","route-found","event-context-before","event-context-after","changed","error-404","check-form-submission","redirect"],_last_route:null,_running:false,data_store_name:"sammy-app",element_selector:"body",debug:false,silence_404:true,run_interval_every:50,location_proxy:null,template_engine:null,toString:function(){return"Sammy.Application:"+this.element_selector},$element:function(){return g(this.element_selector)},use:function(){var h=g.makeArray(arguments);var i=h.shift();try{h.unshift(this);i.apply(this,h)}catch(j){if(typeof i=="undefined"){throw ("Error: called use() but plugin is not defined")}else{if(!g.isFunction(i)){throw ("Error: called use() but '"+i.toString()+"' is not a function")}else{throw (j)}}}return this},route:function(k,i,m){var j=this,l=[],h;if(!m&&g.isFunction(i)){i=k;m=i;k="any"}k=k.toLowerCase();if(i.constructor==String){f.lastIndex=0;while((path_match=f.exec(i))!=null){l.push(path_match[1])}i=new RegExp("^"+i.replace(f,d)+"$")}if(typeof m=="string"){m=j[m]}h=function(n){var o={verb:n,path:i,callback:m,param_names:l};j.routes[n]=j.routes[n]||[];j.routes[n].push(o)};if(k==="any"){g.each(this.ROUTE_VERBS,function(o,n){h(n)})}else{h(k)}return this},get:b("get"),post:b("post"),put:b("put"),del:b("delete"),any:b("any"),mapRoutes:function(i){var h=this;g.each(i,function(j,k){h.route.apply(h,k)});return this},eventNamespace:function(){return[this.data_store_name,this.namespace].join("-")},bind:function(h,j,l){var k=this;if(typeof l=="undefined"){l=j}var i=function(){var o,m,n;o=arguments[0];n=arguments[1];if(n&&n.context){m=n.context;delete n.context}else{m=new k.context_prototype(k,"bind",o.type,n)}o.cleaned_type=o.type.replace(k.eventNamespace(),"");l.apply(m,[o,n])};if(!this.listeners[h]){this.listeners[h]=[]}this.listeners[h].push(i);if(this.isRunning()){this._listen(h,i)}return this},trigger:function(h,i){this.$element().trigger([h,this.eventNamespace()].join("."),[i]);return this},refresh:function(){this.last_location=null;this.trigger("location-changed");return this},before:function(h,i){if(g.isFunction(h)){i=h;h={}}this.befores.push([h,i]);return this},after:function(h){return this.bind("event-context-after",h)},around:function(h){this.arounds.push(h);return this},isRunning:function(){return this._running},helpers:function(h){g.extend(this.context_prototype.prototype,h);return this},helper:function(h,i){this.context_prototype.prototype[h]=i;return this},run:function(h){if(this.isRunning()){return false}var i=this;g.each(this.listeners.toHash(),function(j,k){g.each(k,function(m,l){i._listen(j,l)})});this.trigger("run",{start_url:h});this._running=true;this.$element().data(this.data_store_name,this);this.last_location=null;if(this.getLocation()==""&&typeof h!="undefined"){this.setLocation(h)}this._checkLocation();this.location_proxy.bind();this.bind("location-changed",function(){i._checkLocation()});this.bind("submit",function(k){var j=i._checkFormSubmission(g(k.target).closest("form"));return(j===false)?k.preventDefault():false});g("body").bind("onunload",function(){i.unload()});return this.trigger("changed")},unload:function(){if(!this.isRunning()){return false}var h=this;this.trigger("unload");this.location_proxy.unbind();this.$element().unbind("submit").removeClass(h.eventNamespace());this.$element().removeData(this.data_store_name);g.each(this.listeners.toHash(),function(i,j){g.each(j,function(l,k){h._unlisten(i,k)})});this._running=false;return this},bindToAllEvents:function(i){var h=this;g.each(this.APP_EVENTS,function(j,k){h.bind(k,i)});g.each(this.listeners.keys(true),function(k,j){if(h.APP_EVENTS.indexOf(j)==-1){h.bind(j,i)}});return this},routablePath:function(h){return h.replace(c,"")},lookupRoute:function(k,i){var j=this,h=false;this.trigger("lookup-route",{verb:k,path:i});if(typeof this.routes[k]!="undefined"){g.each(this.routes[k],function(m,l){if(j.routablePath(i).match(l.path)){h=l;return false}})}return h},runRoute:function(i,r,k){this.log("runRoute",[i,r].join(" "));this.trigger("run-route",{verb:i,path:r,params:k});if(typeof k=="undefined"){k={}}g.extend(k,this._parseQueryString(r));var j=this,h,n,l,m,q,o,p=this.lookupRoute(i,r);if(p){this.trigger("route-found",{route:p});if((path_params=p.path.exec(this.routablePath(r)))!=null){path_params.shift();g.each(path_params,function(s,t){if(p.param_names[s]){k[p.param_names[s]]=a(t)}else{if(!k.splat){k.splat=[]}k.splat.push(a(t))}})}h=new this.context_prototype(this,i,r,k);l=this.arounds.slice(0);q=this.befores.slice(0);n=function(){var s;while(q.length>0){o=q.shift();if(j.contextMatchesOptions(h,o[0])){s=o[1].apply(h,[h]);if(s===false){return false}}}j.last_route=p;h.trigger("event-context-before",{context:h});s=p.callback.apply(h,[h]);h.trigger("event-context-after",{context:h});return s};g.each(l.reverse(),function(s,t){var u=n;n=function(){return t.apply(h,[u])}});return n()}else{this.notFound(i,r)}},contextMatchesOptions:function(k,m,i){var j=m;if(typeof j==="undefined"||j=={}){return true}if(typeof i==="undefined"){i=true}if(typeof j==="string"||g.isFunction(j.test)){j={path:j}}if(j.only){return this.contextMatchesOptions(k,j.only,true)}else{if(j.except){return this.contextMatchesOptions(k,j.except,false)}}var h=true,l=true;if(j.path){if(g.isFunction(j.path.test)){h=j.path.test(k.path)}else{h=(j.path.toString()===k.path)}}if(j.verb){l=j.verb===k.verb}return i?(l&&h):!(l&&h)},getLocation:function(){return this.location_proxy.getLocation()},setLocation:function(h){return this.location_proxy.setLocation(h)},swap:function(h){return this.$element().html(h)},notFound:function(i,h){this.trigger("error-404",{verb:i,path:h});throw ("404 Not Found "+i+" "+h)},_checkLocation:function(){try{var h,i;h=this.getLocation();if(h!=this.last_location){i=this.runRoute("get",h)}this.last_location=h}catch(j){this.last_location=h;if(j.toString().match(/^404/)&&this.silence_404){return i}else{throw (j)}}return i},_checkFormSubmission:function(j){var h,l,n,m,i;this.trigger("check-form-submission",{form:j});h=g(j);l=h.attr("action");n=g.trim(h.attr("method").toString().toLowerCase());if(!n||n==""){n="get"}this.log("_checkFormSubmission",h,l,n);m=g.extend({},this._parseFormParams(h),{"$form":h});try{i=this.runRoute(n,l,m)}catch(k){if(k.toString().match(/^404/)&&this.silence_404){return true}else{throw (k)}}return(typeof i=="undefined")?false:i},_parseFormParams:function(h){var i={};g.each(h.serializeArray(),function(j,k){if(i[k.name]){if(g.isArray(i[k.name])){i[k.name].push(k.value)}else{i[k.name]=[i[k.name],k.value]}}else{i[k.name]=k.value}});return i},_parseQueryString:function(m){var k={},l,j,n,h;l=m.match(c);if(l){j=l[1].split("&");for(h=0;h<j.length;h+=1){n=j[h].split("=");k[n[0]]=a(n[1])}}return k},_listen:function(h,i){return this.$element().bind([h,this.eventNamespace()].join("."),i)},_unlisten:function(h,i){return this.$element().unbind([h,this.eventNamespace()].join("."),i)}});Sammy.EventContext=function(k,j,h,i){this.app=k;this.verb=j;this.path=h;this.params=new Sammy.Object(i)};Sammy.EventContext.prototype=g.extend({},Sammy.Object.prototype,{$element:function(){return this.app.$element()},partial:function(p,l,o){var h,k,n,m,j="partial:"+p,i=this;if((n=p.match(/\.([^\.]+)$/))){n=n[1]}if((!n||!g.isFunction(i[n]))&&this.app.template_engine){n=this.app.template_engine}if(n&&!g.isFunction(n)&&g.isFunction(i[n])){n=i[n]}if(!o&&g.isFunction(l)){o=l;l={}}m=(g.isArray(l)?l:[l||{}]),k=function(q){var r=q,s="";g.each(m,function(t,u){g.extend(u,i);if(g.isFunction(n)){r=n.apply(i,[q,u])}s+=r;if(o){return o.apply(i,[r,t])}});if(!o){i.app.swap(s)}i.trigger("changed")};if(this.app.cache_partials&&this.cache(j)){k.apply(i,[this.cache(j)])}else{g.get(p,function(q){if(i.app.cache_partials){i.cache(j,q)}k.apply(i,[q])})}},redirect:function(){var j,i=g.makeArray(arguments),h=this.app.getLocation();if(i.length>1){i.unshift("/");j=this.join.apply(this,i)}else{j=i[0]}this.trigger("redirect",{to:j});this.app.last_location=this.path;this.app.setLocation(j);if(h==j){this.app.trigger("location-changed")}},trigger:function(h,i){if(typeof i=="undefined"){i={}}if(!i.context){i.context=this}return this.app.trigger(h,i)},eventNamespace:function(){return this.app.eventNamespace()},notFound:function(){return this.app.notFound(this.verb,this.path)},toString:function(){return"Sammy.EventContext: "+[this.verb,this.path,this.params].join(" ")}});g.sammy=Sammy})(jQuery);
