if(!this.JSON){this.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());function Uri()
{}
Uri.joinHostAndPort=function(host,port)
{var result=host;if(port!==null)
{result+=":"+port.toString();}
return result;};Uri.joinComponents=function(protocol,host,port,absoluteUrl)
{return protocol+"://"+
Uri.joinHostAndPort(host,port)+
absoluteUrl;};Function.prototype.bind=function(target)
{var method=this;var slice=Array.prototype.slice;var args=slice.apply(arguments,[1]);return function()
{return method.apply(target,args.concat(slice.apply(arguments,[0])));};};Function.prototype.curry=function()
{var slice=Array.prototype.slice;var args=slice.apply(arguments);var that=this;return function()
{return that.apply(null,args.concat(slice.apply(arguments)));}};Function.prototype.inherits=function(Parent)
{$.extend(true,this,Parent);this.prototype=new Parent();};Function.prototype.define=function(Parent,classMethods,instanceMethods)
{if(Parent)
{this.inherits(Parent);}
this.prototype.klass=this;$.extend(this,classMethods||{});$.extend(this.prototype,instanceMethods||{});return this;};function invokeAsync(target,method,args,success,error,complete)
{args=args||[];args.push(success);if(error)args.push(error);if(complete)args.push(complete);method.apply(target,args);}
function invokeAsyncChain(firstObject,invocations,success,error,complete)
{var i=0;var target=firstObject;var invokeNext=function()
{if(i>invocations.length-1)
{success(target);}
else
{invokeAsync(target,invocations[i][0],invocations[i][1]||[],function(result){target=result;++i;invokeNext();},error,complete);}};invokeNext();}
function invokeAsyncParallel(invocations,success,error,complete)
{var i;var successes=[];var errors=[];var returnedCount=0;var invocationCount=invocations.length;var finish=function()
{if(returnedCount===invocationCount)
{if(errors.length===0)
{success(successes);}
else if(error)
{error(errors[0]);}
if(complete)
{complete();}}};var makeSingleSuccess=function(i)
{return function(data)
{successes[i]=data;++returnedCount;finish();};};var singleError=function(e)
{errors.push(e);++returnedCount;finish();};for(i=0;i<invocationCount;++i)
{invokeAsync(invocations[i][0],invocations[i][1],invocations[i][2]||[],makeSingleSuccess(i),singleError,function(){});}}
function Event()
{this.handlers=new ArrayList();}
Event.prototype={attach:function(handler)
{this.handlers.add(handler);return new Binding(this,handler);},detach:function(handler)
{this.handlers.remove(handler);},fire:function()
{var i;for(i=0;i<this.handlers.getLength();++i)
{this.handlers.get(i).apply(null,arguments);}}};function Binding(event,handler)
{this.event=event;this.handler=handler;}
Binding.prototype={destroy:function()
{this.event.detach(this.handler);}};String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"");};String.prototype.lpad=function(length,padstring)
{var s=this;while(s.length<length)
s=padstring+s;return s;};String.prototype.splitAndTrim=function(delimeter)
{var i;var parts=this.split(delimeter);for(i=0;i<parts.length;++i)
{parts[i]=parts[i].trim();}
return parts;};Date.prototype.getMonthName=function()
{return Date.monthNames[this.getMonth()];};Date.prototype.getUTCMonthName=function()
{return Date.monthNames[this.getUTCMonth()];};Date.prototype.getTwoDigitYear=function()
{return(this.getFullYear()%100).toString().lpad(2,"0");};Date.prototype.getTwoDigitUTCYear=function()
{return(this.getUTCFullYear()%100).toString().lpad(2,"0");};Date.prototype.friendlyTime=function()
{var minutes=this.getUTCMinutes();var hours=this.getUTCHours();if((minutes===0)&&(hours===0))
{return"midnight";}
else if((minutes===0)&&(hours===12))
{return"noon";}
else if(hours<12)
{return((hours===0)?"12":hours.toString())+
((minutes===0)?"":":"+minutes.toString().lpad(2,"0"))+"am";}
else
{return((hours===12)?"12":(hours-12).toString())+
((minutes===0)?"":":"+minutes.toString().lpad(2,"0"))+"pm";}};Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];Array.prototype.indexOf=function(value)
{var i;for(i=0;i<this.length;++i)
{if(this[i]===value)
{return i;}}
return-1;};Array.prototype.contains=function(value)
{return(-1!==this.indexOf(value));};Array.prototype.uniq=function()
{var i;var result=[];for(i=0;i<this.length;++i)
{if(!result.contains(this[i]))
{result.push(this[i]);}}
return result;};Array.prototype.copy=function()
{var i;var copy=[];for(i=0;i<this.length;++i)
{copy[i]=this[i];}
return copy;};Array.prototype.each=function(f)
{var i;for(i=0;i<this.length;++i)
{f(this[i]);}};Array.prototype.collect=function(f)
{var i;var result=[];for(i=0;i<this.length;++i)
{result.push(f(this[i]));}
return result;};Array.prototype.findFirst=function(predicate)
{var i;if(this.length===0)
{return null;}
for(i=0;i<this.length;++i)
{if(predicate(this[i]))
{return this[i];}}
return null;};Array.prototype.findMax=function(comparer)
{if(this.length===0)
{return null;}
var i;var max=this[0];for(i=1;i<this.length;++i)
{if(comparer(max,this[i])<0)
{max=this[i];}}
return max;};Array.prototype.trueForAny=function(predicate)
{var i;for(i=0;i<this.length;++i)
{if(predicate(this[i]))
{return true;}}
return false;};function ArrayList()
{this.clear();}
ArrayList.prototype.clear=function()
{this.data=[];};ArrayList.prototype.add=function(value)
{this.data[this.data.length]=value;};ArrayList.prototype.remove=function(value)
{for(var i=0;i<this.data.length;++i)
{if(this.data[i]===value)
{this.removeAt(i);break;}}};ArrayList.prototype.removeAt=function(index)
{var i;if((index<0)||(index>this.data.length-1))
{throw"Index out of bounds";}
for(i=index;i<this.data.length-1;++i)
{this.data[i]=this.data[i+1];}
this.data.length=this.data.length-1;};ArrayList.prototype.get=function(index)
{if((index<0)||(index>this.data.length-1))
{throw"Index out of bounds";}
return this.data[index];};ArrayList.prototype.indexOf=function(value)
{var i;for(i=0;i<this.data.length;++i)
{if(this.data[i]===value)
{return i;}}
return-1;};ArrayList.prototype.contains=function(value)
{return(this.indexOf(value)!==-1);};ArrayList.prototype.toArray=function()
{return this.data.copy();};ArrayList.prototype.getLength=function()
{return this.data.length;};function Length(number,unit)
{this.number=number||0;this.unit=unit||"px";}
Length.pattern=/^(-?[0-9]+|-?[0-9]*\.[0-9]+)(em|ex|px|cm|mm|in|pt|pc)$/;Length.parse=function(length)
{if(Length.pattern.test(length))
{return new Length(parseFloat(RegExp.$1),RegExp.$2);}
throw"Not a valid length: "+length;};Length.prototype.toString=function()
{return this.number+this.unit;};Length.prototype.multiply=function(factor)
{return new Length(this.number*factor,this.unit);};Length.prototype.mix=function(length,percent)
{if((percent<0)||(percent>1))
{throw"Percent "+percent+" out of range";}
if(this.unit!=length.unit)
{throw"Can not mix lengths of different units: "+this.unit+", "+length.unit;}
return new Length(this.number+(length.number-this.number)*percent,this.unit);};function Timer(interval,options)
{options=options||{};this.interval=interval||33
this.context=options.context||window;this.tick=new Event();this.started=false;this.intervalId=null;}
Timer.prototype={destroy:function()
{this.stop();},start:function()
{if(!this.started)
{this.started=true;this.intervalId=this.context.setInterval(this.update.bind(this),this.interval);}},stop:function()
{if(this.started)
{this.started=false;this.context.clearInterval(this.intervalId);}},update:function()
{this.tick.fire();},toString:function()
{return"Timer ("+(this.started?"started":"stopped")+")";}};function TimeSpan(milliseconds)
{this.totalMilliseconds=milliseconds;this.totalSeconds=Math.floor(milliseconds/TimeSpan.MILLISECONDS_PER_SECOND);this.totalMinutes=Math.floor(this.totalSeconds/TimeSpan.SECONDS_PER_MINUTE);this.totalHours=Math.floor(this.totalSeconds/TimeSpan.SECONDS_PER_HOUR);this.totalDays=Math.floor(this.totalSeconds/TimeSpan.SECONDS_PER_DAY);this.milliseconds=Math.floor(this.totalMilliseconds%TimeSpan.MILLISECONDS_PER_SECOND);this.seconds=Math.floor(this.totalSeconds%TimeSpan.SECONDS_PER_MINUTE);this.minutes=Math.floor(this.totalMinutes%TimeSpan.MINUTES_PER_HOUR);this.hours=Math.floor(this.totalHours%TimeSpan.HOURS_PER_DAY);this.days=this.totalDays;}
TimeSpan.MILLISECONDS_PER_SECOND=1000;TimeSpan.SECONDS_PER_MINUTE=60;TimeSpan.MINUTES_PER_HOUR=60;TimeSpan.HOURS_PER_DAY=24;TimeSpan.SECONDS_PER_HOUR=TimeSpan.SECONDS_PER_MINUTE*TimeSpan.MINUTES_PER_HOUR;TimeSpan.SECONDS_PER_DAY=TimeSpan.SECONDS_PER_HOUR*TimeSpan.HOURS_PER_DAY;TimeSpan.prototype={toString:function()
{return this.days.toString()+" days, "+
this.hours.toString()+" hours "+
this.minutes.toString()+" minutes "+
this.seconds.toString()+" seconds";}};function Tab(labelElement,contentElement)
{this.labelClick=new Event();this.contentClick=new Event();this.labelElement=labelElement;this.contentElement=contentElement;if(this.labelElement!==null)
{this.labelElement.onclick=this.labelElementOnClick.bind(this);}}
Tab.prototype={select:function()
{this.selected=true;$(this.contentElement).show();if(this.labelElement!==null)
{$(this.labelElement).addClass("selected");}},deselect:function()
{this.selected=false;$(this.contentElement).hide();if(this.labelElement!==null)
{$(this.labelElement).removeClass("selected");}},contentElementOnClick:function()
{this.contentClick.fire(this);},labelElementOnClick:function()
{this.labelClick.fire(this);}};function TabGroup(tabs)
{var i;this.tabs=tabs||[];this.selectedTab=null;this.tabSelected=new Event();for(i=0;i<this.tabs.length;++i)
{this.attachTab(this.tabs[i]);}
this.updateTabClasses();this.updateTabIndices();this.selectFirstTab();}
TabGroup.prototype={addTab:function(tab)
{this.tabs.push(tab);this.attachTab(tab);this.updateTabClasses();this.updateTabIndices();},removeTab:function(tab)
{},updateTabIndices:function()
{var i;for(i=0;i<this.tabs.length;++i)
{this.tabs[i].index=i;}},updateTabClasses:function()
{var i;var tab;for(i=0;i<this.tabs.length;++i)
{tab=$(this.tabs[i].contentElement);tab.addClass("tab");if(this.tabs.length>1)
{tab.addClass("siblingTab");}
else
{tab.removeClass("siblingTab");}}},attachTab:function(tab)
{tab.labelClick.attach(this.tabLabelClick.bind(this));tab.contentClick.attach(this.tabContentClick.bind(this));},selectTab:function(tab)
{if(this.selectedTab!==tab)
{if(this.selectedTab!==null)
{this.selectedTab.deselect();}
this.selectedTab=tab;this.selectedTab.select();this.tabSelected.fire(this.selectedTab);}},selectFirstTab:function()
{var i;for(i=0;i<this.tabs.length;++i)
{if(i===0)
{this.selectTab(this.tabs[i]);}
else
{this.tabs[i].deselect();}}},selectNextTab:function()
{var nextIndex;if(this.selectedTab!==null)
{nextIndex=(this.selectedTab.index+1)%this.tabs.length;this.selectTab(this.tabs[nextIndex]);}},tabLabelClick:function(tab)
{this.selectTab(tab);},tabContentClick:function(tab)
{this.selectNextTab();}};function Drawer(handle,contents,options)
{this.handle=handle;this.contents=contents;options=options||{};this.startOpen=(options.startOpen===undefined)?false:options.startOpen;this.context=options.context||document;this.auto=(options.auto===undefined)?true:options.auto;this.closeOnClick=(options.closeOnClick===undefined)?true:options.closeOnClick;this.didStartOpen=new Event();this.didStartClose=new Event();this.didFinishOpen=new Event();this.didFinishClose=new Event();if(this.auto)
{this.handle.onclick=this.handleOnClick.bind(this);}
this.setOpen(this.startOpen);$(this.contents)[this.startOpen?"show":"hide"]();}
Drawer.prototype={toggle:function()
{(this.opened?this.close:this.open).call(this);},setOpen:function(open)
{this.opened=open;$(this.handle).toggleClass("open_handle",open);},open:function(speed)
{if(speed===undefined)speed="fast";if(!this.opened)
{this.setOpen(true);this.didStartOpen.fire(this);$(this.contents).slideDown(speed,function(){this.didFinishOpen.fire(this);}.bind(this));}},close:function(speed)
{if(speed===undefined)speed="fast";if(this.opened)
{this.setOpen(false);this.didStartClose.fire(this);$(this.contents).slideUp(speed,function(){this.didFinishClose.fire(this);}.bind(this));}},handleOnClick:function()
{if(this.opened)
{if(this.allowClose)
{this.close();}}
else
{this.open();}}};function DrawerCloser(drawers)
{var i;this.drawers=new ArrayList();drawers=drawers||[];for(i=0;i<drawers.length;++i)
{this.drawers.add(drawers[i]);this.bindDrawer(drawers[i]);}}
DrawerCloser.prototype={add:function(drawer)
{this.drawers.add(drawer);this.bindDrawer(drawer);},bindDrawer:function(drawer)
{drawer.didStartOpen.attach(this.drawerDidStartOpen.bind(this));},drawerDidStartOpen:function(source)
{var i,drawer;for(i=0;i<this.drawers.getLength();++i)
{drawer=this.drawers.get(i);if(drawer!==source&&drawer.opened)
{drawer.close();}}}};function Grid(columnCount,options)
{this.columnCount=columnCount;this.cellCount=0;options=options||{};this.context=options.context||document;this.div=this.context.createElement("div");this.div.className="grid";this.clearer=this.context.createElement("div");this.clearer.className="clearer";this.div.appendChild(this.clearer);}
Grid.prototype={render:function(parent)
{parent.appendChild(this.div);},getElement:function()
{return this.div;},createCell:function()
{var rowClearer;var cell=this.context.createElement("div");cell.className="cell";if(this.cellCount<this.columnCount)
$(cell).addClass("top_cell ");if(0===mod(this.cellCount,this.columnCount)){if(this.cellCount>0){rowClearer=this.context.createElement("div");rowClearer.className="clearer";this.div.insertBefore(rowClearer,this.clearer);}
$(cell).addClass("left_cell");}
this.div.insertBefore(cell,this.clearer);++this.cellCount;return cell;}};function ElementBuilder(context)
{this.context=context||document;}
$.extend(ElementBuilder,{createElementMethods:function()
{var i;var names=["div","span","a","img","br","ul","li","input","textArea","select","table","thead","tbody","tr","th","td","label","h1","h2","h3","h4","p"];for(i in names)
{this.createElementMethod(names[i]);}},createElementMethod:function(name)
{ElementBuilder.prototype[name]=function()
{var args=ElementBuilder.argumentsToArray(arguments);var parent=args.shift();args.unshift(name);args.unshift(parent);return this.element.apply(this,args);};},argumentsToArray:function(arguments)
{return Array.prototype.slice.call(arguments);}});ElementBuilder.createElementMethods();$.extend(ElementBuilder.prototype,{text:function(parent,text)
{var node=this.context.createTextNode(text);if(parent)
{parent.appendChild(node);}
return node;},element:function(parent,name,className,attributes)
{var element=this.context.createElement(name);var jElement;var key;if(parent)
{parent.appendChild(element);}
if(className)
{element.className=className;}
if(attributes)
{for(key in attributes)
{if(key==="html")
{element.innerHTML=h(attributes.html);}
else
{element[key]=attributes[key];}}}
return element;},clearer:function(parent)
{return this.element.apply(this,[parent,"div","clearer"]);},opt:function()
{var args=ElementBuilder.argumentsToArray(arguments);var parent=args.shift();args.unshift("option");args.unshift(parent);return this.element.apply(this,args);}});function FormBuilder()
{this.elementBuilder=new ElementBuilder();}
$.extend(FormBuilder.prototype,{field:function(id,value,attrs,type)
{type=type||"input";attrs=attrs||{};attrs.id=id;attrs.value=value||"";return this.elementBuilder[type](null,null,attrs);},input:function(id,value,attrs,inputType)
{attrs=attrs||{};attrs.type=inputType||"text";attrs.className=attrs.type+"_input";return this.field(id,value,attrs);},text:function(id,value,attrs)
{return this.input(id,value,attrs,"text");},password:function(id,value,attrs)
{return this.input(id,value,attrs,"password");},textArea:function(id,value,attrs)
{return this.field(id,value,attrs,"textArea");},select:function(id,value,choices,attrs)
{var select,opt;var b=this.elementBuilder;var key;choices=choices||[];select=this.input(id,null,attrs,"select");for(key in choices)
{opt=b.opt(select,null,{value:key,innerHTML:choices[key]});if(value&&value.toString()===key){opt["selected"]="1";}}
return select;},label:function(forId,text,attrs)
{attrs=attrs||{};attrs["for"]=forId;attrs.innerHTML=text;return this.elementBuilder.label(null,null,attrs);}});function History()
{}
History.create=function()
{var version=parseInt($.browser.version,10);if($.browser.msie)
{if(version>=8)
{return new HashChangeHistory();}
else
{return new IframePollingHistory();}}
else
{return new WindowPollingHistory();}};History.setWindowHash=function(hash)
{window.top.location.hash="#"+hash;};History.getWindowHash=function()
{return window.top.location.hash.replace('#','');};History.prototype={init:function()
{this.locationChanged=new Event();},destroy:function()
{},changeLocation:function(hash,force)
{if(hash===this.getLocation())
{if(force)
{this.locationChanged.fire(this,hash);}}
else
{this.changeLocationInternal(hash);}},changeLocationInternal:function(hash)
{},move:function(n)
{window.history.go(n);},back:function(n)
{this.move(-n||-1);},forward:function(n)
{this.move(n||1);},changeLocationInternal:function(hash)
{},getLocation:function()
{}};function HashChangeHistory()
{}
HashChangeHistory.prototype=new History();$.extend(HashChangeHistory.prototype,{init:function()
{History.prototype.init.call(this);this.windowHashChangeBinding=this.windowHashChange.bind(this);$(window).bind('hashchange',this.windowHashChangeBinding);return this;},destroy:function()
{History.prototype.destroy.call(this);if(this.windowHashChangeBinding)
{$(window).unbind('hashchange',this.windowHashChangeBinding);this.windowHashChangeBinding=null;}},getLocation:function()
{return History.getWindowHash();},changeLocationInternal:function(hash)
{History.setWindowHash(hash);},windowHashChange:function()
{this.locationChanged.fire(this,History.getWindowHash());}});function PollingHistory()
{}
PollingHistory.prototype=new History();$.extend(PollingHistory.prototype,{init:function()
{History.prototype.init.call(this);this.setLocation(History.getWindowHash());this.intervalId=null;this.startPolling();return this;},destroy:function()
{History.prototype.destroy.call(this);this.stopPolling();},changeLocationInternal:function(hash)
{this.setLocation(hash);this.locationChanged.fire(this,hash);},getLocation:function()
{return this.location;},setLocation:function(hash)
{this.location=hash;History.setWindowHash(hash);},startPolling:function()
{this.intervalId=window.setInterval(this.poll.bind(this),50);},stopPolling:function()
{if(this.intervalId)
{window.clearInterval(this.intervalId);}},poll:function()
{}});function WindowPollingHistory()
{}
WindowPollingHistory.prototype=new PollingHistory();$.extend(WindowPollingHistory.prototype,{poll:function()
{var windowHash=History.getWindowHash();if(this.location!==windowHash)
{this.changeLocation(windowHash);}}});function IframePollingHistory()
{}
IframePollingHistory.prototype=new PollingHistory();$.extend(IframePollingHistory.prototype,{init:function()
{this.createIframe();return PollingHistory.prototype.init.call(this);},poll:function()
{var windowHash=History.getWindowHash();var iframeHash=this.getIframeHash();if(this.location!==windowHash)
{this.changeLocation(windowHash);}
else if(this.location!==iframeHash)
{this.changeLocation(iframeHash);}},destroy:function()
{History.prototype.destroy.call(this);this.destroyIframe();},setLocation:function(hash)
{this.setIframeHash(hash);PollingHistory.prototype.setLocation.apply(this,arguments);},createIframe:function()
{this.iframe=$('<iframe style="display: none;"/>').appendTo(document.body)[0];},destroyIframe:function()
{$(this.iframe).remove();},getIframeHash:function()
{return this.iframe.contentWindow.document.location.hash.replace('#','');},setIframeHash:function(hash)
{if(this.getIframeHash()!==hash)
{var doc=this.iframe.contentWindow.document;doc.open();doc.close();doc.location.hash=hash;}}});function Cache()
{this.flush();}
Cache.prototype={flush:function()
{this.data={};},write:function(key,value)
{this.data[key]=value;},read:function(key,fetch,success,error,complete)
{if(this.data[key]!==undefined)
{success(this.data[key]);}
else
{fetch(function(value){this.data[key]=value;success(value);}.bind(this),error,complete);}}};function ImageLoader()
{}
ImageLoader.define(null,{},{init:function(url)
{this.url=url;return this;},load:function(success,error,complete)
{var image=new Image();image.onload=function(){if(success)success();if(complete)complete();}.bind(this);image.onerror=image.onabort=function(){if(error)error();if(complete)complete();}.bind(this);image.src=this.url;}});function h(s)
{return $('<div/>').text(s).html();}
function eventSource(event)
{event=event||window.event;return event.currentTarget||event.srcElement;}
function clearChildNodes(parent)
{parent.innerHTML="";}
function mod(n,k)
{return n-(Math.floor(n/k)*k);}
function argumentsToArray(arguments)
{return Array.prototype.slice.call(arguments);}
function formatYesNo(value)
{return value?"Yes":"No";}
function formatDateShort(date)
{return(date.getMonth()+1).toString()+"/"+
date.getDate().toString()+"/"+
date.getTwoDigitYear();}
function formatPrice(totalCents)
{var negative=(totalCents<0);totalCents=Math.abs(totalCents);var dollars=Math.floor(totalCents/100);var cents=totalCents%100;var number=dollars.toString()+"."+
cents.toString().lpad(2,"0");if(negative){number="("+number+")";}
return"$ "+number;}
function getSkuImageThumbnailByName(skuImage,name)
{var i;var thumbnail;var filename=skuImage.filename.substring(0,skuImage.filename.indexOf("."))+"_"+
name+".png";for(i=0;i<skuImage.thumbnails.length;++i)
{thumbnail=skuImage.thumbnails[i];if(thumbnail.filename===filename)
{return thumbnail;}}
return null;}
function constantToUpperCamelCase(constant)
{var i;var result="";var parts=constant.split("_");for(i=0;i<parts.length;++i)
{result+=toUpperCamelCase(parts[i]);}
return result;}
function toUpperCamelCase(s)
{return s.substring(0,1).toUpperCase()+
s.substring(1).toLowerCase();}
function Application(environment,site,assetMap,authorized)
{this.environment=environment;this.site=site;this.assetMap=assetMap;this.authorized=authorized;this.isBusy=false;this.ssl=null;this.locationChanging=new Event();this.locationChanged=new Event();this.viewport=new Viewport().init(window);this.rootController=null;this.setHostsAndPorts();this.location=Location.fromHash("/");this.timer=new Timer(100);this.dataSource=new DataSource(this);}
Application.prototype={setHostsAndPorts:function()
{if(this.environment==="production"){this.host="marketfordrama.com";this.assetHost="assets.marketfordrama.com";}else{this.host=this.assetHost="192.168.5.1";}
this.port=(this.environment==="development")?3000:null;this.assetPort=this.port;},run:function()
{this.ssl=(window.document.location.protocol==="https:");this.history=History.create().init();this.history.locationChanged.attach(this.onHistoryLocationChanged.bind(this));var hash=document.location.hash.replace("#","");if(hash.length===0)
{hash=this.authorized?"store":"welcome";}
this.go(hash,true);},work:function(worker,success,error,complete,completeOnSuccess)
{var successful=false;if(!this.isBusy)
{this.busy();worker(function(){this.free();successful=true;if(success)success.apply(null,arguments);}.bind(this),function(e){this.free();if(error){error.apply(null,arguments);}else{this.rootController.leaf().handleError(e);}}.bind(this),function(){if(complete){complete.apply(null,arguments);}
if(successful&&completeOnSuccess){completeOnSuccess.apply(null,arguments);}}.bind(this));}},busy:function()
{this.isBusy=true;this.rootController.showThrobber();},free:function()
{this.rootController.hideThrobber();this.isBusy=false;},trackPageView:function(location)
{if(this.environment==="production")
{try{_gat._getTracker("UA-11376839-2")._trackPageview(location.toHash());}
catch(err){}}},doCommand:function(type,params)
{if(this.rootController)
{this.rootController.leaf().routeCommand(new Command(type,params));}},go:function(locationOrHash,applicationStarting)
{applicationStarting=applicationStarting||false;var location=(typeof locationOrHash==="string")?Location.fromHash(locationOrHash):locationOrHash;if(!location.isAbsolute())
{location=this.location.clone().append(location);}
this.history.changeLocation(location.toHash(),applicationStarting);},changeLocation:function(location)
{if(this.isBusy){return;}
var resolved=false;var changedProtocol=false;if(!location.isAbsolute())
{throw"changeLocation may only be called with an absolute location";}
this.locationChanging.fire(location);if(this.rootController===null)
{this.rootController=new FrontController(null);}
resolved=this.rootController.createControllerChain(location.iterator());if(resolved)
{if(!this.changeProtocolIfNecessary(location))
{this.work(this.rootController.activate.bind(this.rootController).curry(window.document.body,{}),function(){this.location=this.rootController.leaf().getLocation();this.locationChanged.fire(this.location);this.trackPageView(this.location);this.rootController.start();}.bind(this));}}
else
{app.go("/welcome");}},changeProtocolIfNecessary:function(location)
{if(this.rootController.sslRequired()){if(!this.ssl){if(this.sslEnabled()){this.changeProtocol(location,true);return true;}else{this.ssl=true;return false;}}}
else if(!this.rootController.sslAllowed()){if(this.ssl){if(this.sslEnabled()){this.changeProtocol(location,false);return true;}else{this.ssl=false;return false;}}}
return false;},changeProtocol:function(location,secure)
{window.document.location.href=this.createAbsoluteUrl("/#"+location.toHash(),{secure:secure});},sslEnabled:function()
{return(this.environment==="production");},assetUrl:function(key)
{return this.createAbsoluteAssetUrl(this.assetMap[key]);},getHostWithPort:function()
{return Uri.joinHostAndPort(this.host,this.port);},getAssetHostWithPort:function()
{return Uri.joinHostAndPort(this.assetHost,this.assetPort);},createAbsoluteUrl:function(url,options)
{return this.createAbsoluteUrlHelper(this.host,this.port,url,options);},createAbsoluteAssetUrl:function(url,options)
{if(this.ssl)
{options=options||{};options.secure=true;return this.createAbsoluteUrl(url,options);}
else
{return this.createAbsoluteUrlHelper(this.assetHost,this.assetPort,url,options);}},createAbsoluteUrlHelper:function(host,port,url,options)
{options=options||{};var defaultProtocol=(this.sslEnabled()&&(options.secure===true))?"https":"http";var protocol=options.protocol||defaultProtocol;return Uri.joinComponents(protocol,host,port,url);},onHistoryLocationChanged:function(history,hash)
{this.changeLocation(Location.fromHash(hash));}};function DataSource(application)
{this.application=application;}
DataSource.prototype={find:function(resource,id,success,error,complete)
{var url=this.createUrl([resource.plural,id]);return this.get(url,{},success,error,complete);},findSingleton:function(resource,success,error,complete)
{var url=this.createUrl([resource.singular]);this.get(url,{},success,error,complete);},findNamedSingleton:function(resource,name,success,error,complete)
{var url=this.createUrl([name]);this.get(url,{},success,error,complete);},findMany:function(resource,params,success,error,complete)
{var url=this.createUrl([resource.plural],params);this.get(url,{},success,error,complete);},findNamedSet:function(resource,name,params,success,error,complete)
{var url=this.createUrl([resource.plural,name],params);this.get(url,{},success,error,complete);},findAssociated:function(sourceInstance,targetResource,success,error,complete)
{var url=this.createUrl([sourceInstance.klass.plural,sourceInstance.id.toString(),targetResource.plural]);this.get(url,{},success,error,complete);},findAssociatedNamedSet:function(sourceInstance,setName,targetResource,success,error,complete)
{var url=this.createUrl([sourceInstance.klass.plural,sourceInstance.id.toString(),setName+"_"+targetResource.plural]);this.get(url,{},success,error,complete);},create:function(resource,params,success,error,complete)
{var url=this.createUrl([resource.plural]);return this.post(url,params,success,error,complete);},update:function(instance,params,success,error,complete)
{return this.put(this.createInstanceUrl(instance),params,success,error,complete);},createSingleton:function(resource,params,success,error,complete)
{var url=this.createUrl([resource.singular]);this.post(url,params,success,error,complete);},destroySingleton:function(resource,success,error,complete)
{return this.delete2(this.createUrl([resource.singular]),success,error,complete);},invokeClassMethod:function(resource,method,params,success,error,complete)
{var url=this.createUrl([resource.plural,method]);this.post(url,params,success,error,complete);},invokeInstanceMethod:function(instance,method,params,success,error,complete)
{var url=this.createUrl([instance.klass.plural,instance.id,method]);return this.post(url,params,success,error,complete);},invokeSingletonInstanceMethod:function(instance,method,params,success,error,complete)
{var url=this.createUrl([instance.getSingular(),method]);return this.post(url,params,success,error,complete);},invokeInstanceGetterMethod:function(instance,method,params,success,error,complete)
{var url=this.createUrl([instance.klass.plural,instance.id,method]);return this.get(url,params,success,error,complete);},findModel:function(model,id,success,error,complete)
{this.resourceToModel(this.find.bind(this).curry(model,id),model,false,success,error,complete);},findSingletonModel:function(model,success,error,complete)
{this.resourceToModel(this.findSingleton.bind(this).curry(model),model,false,success,error,complete);},findNamedSingletonModel:function(model,name,success,error,complete)
{this.resourceToModel(this.findNamedSingleton.bind(this).curry(model,name),model,false,success,error,complete);},findManyModels:function(model,params,success,error,complete)
{this.resourceToModel(this.findMany.bind(this).curry(model,params),model,true,success,error,complete);},findNamedSetModels:function(model,name,params,success,error,complete)
{this.resourceToModel(this.findNamedSet.bind(this).curry(model,name,params),model,true,success,error,complete);},findAssociatedModels:function(sourceInstance,targetClass,success,error,complete)
{this.resourceToModel(this.findAssociated.bind(this).curry(sourceInstance,targetClass),targetClass,true,success,error,complete);},findAssociatedNamedSetModels:function(sourceInstance,setName,targetClass,success,error,complete)
{this.resourceToModel(this.findAssociatedNamedSet.bind(this).curry(sourceInstance,setName,targetClass),targetClass,true,success,error,complete);},createModel:function(model,attrs,success,error,complete)
{var params=this.createModelParams(attrs,model.singular);this.resourceToModel(this.create.bind(this).curry(model,params),model,false,success,error,complete);},updateModel:function(modelInstance,attrs,success,error,complete)
{var params=DataSource.createModelParamsFromInstance(modelInstance,attrs);this.update(modelInstance,params,function(data){modelInstance.setAttributes(data);success();},error,complete);},invokeModelMutator:function(modelInstance,method,params,success,error,complete)
{this.invokeInstanceMethod(modelInstance,method,params,function(data){modelInstance.setAttributes(data);success();},error,complete);},invokeSingletonModelMutator:function(modelInstance,method,params,success,error,complete)
{this.invokeSingletonInstanceMethod(modelInstance,method,params,function(data){modelInstance.setAttributes(data);success();},error,complete);},resourceToModel:function(resourceMethod,model,many,success,error,complete)
{var models;resourceMethod(function(data){models=many?model.manyFromAttrs(data):model.fromAttrs(data);success(models);},error,complete);},get:function(url,data,successCallback,errorCallback,completeCallback)
{var args=argumentsToArray(arguments);args.unshift("GET");this.request.apply(this,args);},post:function(url,data,successCallback,errorCallback,completeCallback)
{var args=argumentsToArray(arguments);args.unshift("POST");this.request.apply(this,args);},put:function(url,data,successCallback,errorCallback,completeCallback)
{data["_method"]="put";return this.post(url,data,successCallback,errorCallback,completeCallback);},delete2:function(url,successCallback,errorCallback,completeCallback)
{return this.post(url,{"_method":"delete"},successCallback,errorCallback,completeCallback);},request:function(method,url,data,successCallback,errorCallback,completeCallback)
{$.ajax({url:url,data:data||{},async:true,dataType:"text",global:false,type:method,success:function(data,textStatus)
{successCallback(JSON.parse(data));if(completeCallback!==undefined)
{completeCallback();}},error:function(xhr,textStatus,errorThrown)
{if(errorCallback!==undefined)
{errorCallback(DataSource.createError(xhr,textStatus,errorThrown));if(completeCallback!==undefined)
{completeCallback();}}}});},createInstanceUrl:function(instance,params)
{var parts=instance.singleton?[instance.getSingular()]:[instance.getPlural(),instance.id.toString()];return this.createUrl(parts,params);},createUrl:function(parts,params)
{var encodedParts=[];var encodedParams=[];var i;var key;var url;var queryString;parts=parts||[];params=params||{};for(i=0;i<parts.length;++i)
{encodedParts.push(encodeURIComponent(parts[i].toString()));}
for(key in params)
{encodedParams.push(encodeURIComponent(key)+"="+
encodeURIComponent(params[key]));}
queryString=(encodedParams.length===0)?"":"?"+encodedParams.join("&");return"/"+encodedParts.join("/")+".json"+queryString;}};DataSource.createError=function(xhr,textStatus,errorThrown)
{if((errorThrown!==undefined)&&(errorThrown!==null))
{return new UnknownAjaxError();}
switch(textStatus)
{case"error":{if(xhr.status===0)
{return new NetworkError();}
else
{return DataSource.createApplicationError(xhr,textStatus,errorThrown);}}
case"timeout":{return new TimeoutError();}
default:{return new UnknownAjaxError();}}};DataSource.createApplicationError=function(xhr,textStatus,errorThrown)
{var info=JSON.parse(xhr.responseText);var code=info.code;delete info.code;if(code==="DataInvalid")
{return new DataInvalidError(code,code,info);}
else
{return new ApplicationError(ApplicationError.messagesByCode[code]||code,code,info);}};DataSource.encodeParams=function(params)
{return{args:JSON.stringify(params)};};DataSource.createModelParamsFromInstance=function(modelInstance,attrs)
{return DataSource.createModelParams(attrs,modelInstance.klass.singular);};DataSource.createModelParams=function(params,instanceName)
{var modelParamsKey;var modelParams={};for(key in params)
{if(params.hasOwnProperty(key))
{modelParamsKey=instanceName+"["+key+"]";modelParams[modelParamsKey]=params[key];}}
return modelParams;};function Command(type,params)
{this.type=type;for(key in params)
{this[key]=params[key];}}
Command.prototype={raise:function(view)
{view.raiseCommand(this);}};function Iterator(array)
{this.array=array;this.i=-1;}
Iterator.prototype={next:function()
{++this.i;return(this.i>this.array.length-1)?null:this.array[this.i];},peek:function()
{return(this.i>this.array.length-2)?null:this.array[this.i+1];},onFirst:function()
{return(this.i===0);}};function Location(nodes)
{this.nodes=nodes||[];}
Location.delimiter="/";Location.prototype={toString:function()
{return this.toHash(true);},iterator:function()
{return new Iterator(this.nodes);},clone:function()
{var i;var nodes=[];for(i=0;i<this.nodes.length;++i)
{nodes.push(this.nodes[i].clone());}
return new Location(nodes,this.absolute);},head:function()
{return(this.nodes.length===0)?null:this.nodes[0];},tail:function()
{return new Location(this.nodes.slice(1));},lastNode:function()
{return(this.nodes.length===0)?null:this.nodes[this.nodes.length-1];},isEmpty:function()
{return(this.nodes.length===0);},push:function(node)
{if(node.isRoot()&&this.nodes.length>0)
{throw"Can't push root node onto non-empty location";}
this.nodes.push(node);return this;},pushHash:function(hash)
{return this.push(LocationNode.fromHash(hash));},pop:function()
{if(this.nodes.length===0)throw"Can't pop empty location";this.nodes.pop();return this;},prefix:function(lastNode)
{var i;var nodes=[];var k=this.nodes.indexOf(lastNode);if(k===-1)throw"Node does not exist in location";for(i=0;i<k+1;++i)
{nodes.push(this.nodes[i].clone());}
return new Location(nodes);},isAbsolute:function()
{return((this.nodes.length>0)&&(this.nodes[0].isRoot()));},isRelative:function()
{return!this.isAbsolute();},canonicalize:function()
{var i;var node;var lastNode;var canonical=new Location([],this.absolute);for(i=0;i<this.nodes.length;++i)
{node=this.nodes[i];if(node.isCurrentPointer())
{}
else if(node.isParentPointer())
{lastNode=canonical.lastNode();if(!lastNode||lastNode.isPointer())
{canonical.push(node);}
else if(lastNode.isRoot())
{throw"Invalid absolute location: descends below root";}
else
{canonical.pop();}}
else
{canonical.push(node);}}
this.nodes=canonical.nodes;return this;},append:function(other)
{var i;if(!other.isRelative())
{throw"Can not join a location to a non-relative location";}
for(i=0;i<other.nodes.length;++i)
{this.nodes.push(other.nodes[i].clone());}
return this.canonicalize();},appendHash:function(other)
{return this.append(Location.fromHash(other));},toHash:function(includeDefaultNodes)
{var i,node;var nodeHashes=[];var hash;includeDefaultNodes=includeDefaultNodes||false;for(i=0;i<this.nodes.length;++i)
{node=this.nodes[i];if(includeDefaultNodes||!node.isDefault)
{nodeHashes.push(node.toHash());}}
if(this.isAbsolute()&&(nodeHashes.length===1))
{nodeHashes.push("");}
return nodeHashes.join(Location.delimiter);},match:function(other,full)
{var i;var node;var thisHead,otherHead;if(other.isEmpty())
{return(!full||this.isEmpty());}
else if(this.isEmpty())
{return false;}
else
{thisHead=this.head();otherHead=other.head();if(thisHead.match(otherHead))
{return this.tail().match(other.tail());}
else if(thisHead.isDefault)
{return this.tail().match(other);}
else if(otherHead.isDefault)
{return this.match(other.tail());}
else
{return false;}}},matchHash:function(otherHash,full)
{return this.match(Location.fromHash(otherHash),full);},findFirstByType:function(type)
{if(this.isEmpty())
{return null;}
else if(this.head().type===type)
{return this.head();}
else
{return this.tail().findFirstByType(type);}}};Location.fromHash=function(hash)
{if(hash.length<1)throw"Invalid hash tag";var location=new Location();var parts=hash.splitAndTrim(Location.delimiter);if(hash.charAt(hash.length-1)===Location.delimiter)
{parts.pop();}
for(i=0;i<parts.length;++i)
{location.push(LocationNode.fromHash(parts[i]));}
return location.canonicalize();};Location.h=Location.fromHash;Location.prototype.h=Location.prototype.toHash;Location.prototype.hmatch=Location.prototype.matchHash;Location.prototype.hpush=Location.prototype.pushHash;Location.prototype.happend=Location.prototype.appendHash;function LocationNode(type,isDefault,params)
{this.type=type;this.isDefault=isDefault||false;this.params=params||{};}
LocationNode.currentType=".";LocationNode.parentType="..";LocationNode.prototype={clone:function()
{var key;var params={};for(key in this.params)
{params[key]=this.params[key];}
return new LocationNode(this.type,this.isDefault,params);},toString:function()
{return this.isRoot()?"<root>"+this.toHash():this.toHash();},isRoot:function()
{return(this.type==="");},isCurrentPointer:function()
{return(this.type===LocationNode.currentType);},isParentPointer:function()
{return(this.type===LocationNode.parentType);},isPointer:function()
{return(this.isCurrentPointer()||this.isParentPointer());},isNormal:function()
{return(!this.isPointer()&&!this.isRoot());},toHash:function()
{var key;var hash;var encodedParams=[];var encodeParam=function(key,value)
{return encodeURIComponent(key)+"="+encodeURIComponent(value);};if(this.params.id)
{encodedParams.push(encodeURIComponent(this.params.id));}
for(key in this.params)
{if(key!=="id")
{encodedParams.push(encodeParam(key,this.params[key]));}}
hash=encodeURIComponent(this.type);if(encodedParams.length>0)
{hash+="?"+encodedParams.join("&");}
return hash;},match:function(other)
{var key;if(other.type!==this.type)
return false;for(key in other.params)
{if(other.params[key]!==this.params[key])
{return false;}}
for(key in this.params)
{if(this.params[key]!==other.params[key])
{return false;}}
return true;}};LocationNode.fromHash=function(hash)
{var error=function(message)
{throw message?("Invalid hash tag: "+message):"Invalid hash tag";};var decode=function(s)
{return decodeURIComponent(s);};var parseParams=function(paramsString)
{var i;var parts;var sides;var params={};if(paramsString.length<=0)error();parts=paramsString.splitAndTrim("&");for(i=0;i<parts.length;++i)
{sides=parts[i].splitAndTrim("=");if(sides.length>2)
{error("Param contains more than two '='");}
else if(sides.length===1)
{if(i>0)error("Param contains no '='");params.id=decode(sides[0]);}
else
{if(sides[0].length<=0)error("Param key is blank");params[decode(sides[0])]=decode(sides[1]);}}
return params;};var type;var params=null;var parts=hash.splitAndTrim("?");if(parts.length>2)error("Segment contains more than one '?'");type=decode(parts[0]);if(parts.length===2)
{params=parseParams(parts[1]);}
return new LocationNode(type,false,params);};function MfdError(message)
{this.message=message;}
ApplicationError.messagesByCode={"SaleNotCurrent":"The sale has ended.","TooManyEmails":"You may enter up to 100 email addresses at a time.","ExceededPerOrderUnitLimit":"You may purchase up to 5 units of each product per order.","InsufficientUnitsRemaining":"This item has just sold out","PromotionNotCurrent":"Invalid promo code","InvalidPromotionCode":"Invalid promo code","MemberAlreadyAppliedPromotion":"We're sorry, you already used this promo code. You may use each promo code once.","InternalServerError":"We're sorry, we encountered an unexpected error. If you need assistance, please email support@marketfordrama.com."};function ApplicationError(message,code,attrs)
{var attr;MfdError.call(this,message);this.code=code;if(attrs!==undefined)
{for(attr in attrs)
{this[attr]=attrs[attr];}}}
function DataInvalidError(message,code,attrs)
{ApplicationError.call(this,message,code,attrs);}
function NetworkError()
{MfdError.call(this,"We could not contact the Market for Drama servers. Your Internet connection may be down.");}
function TimeoutError()
{MfdError.call(this,"The Market for Drama servers are taking too long to respond. Please try again later.");}
function UnknownAjaxError()
{MfdError.call(this,"We're sorry, we encountered an unknown error. Please try again.");}
Messages={all_items_expired:{title:"Expired",body:"All items in your cart expired. Please return to the Shop and fill your cart again. Make sure to complete checkout before the timer at the top of the screen reaches zero."},payment_failed:{title:"Payment Failed",body:"We could not charge your credit card. Please check the information and try again."},reconfirm:{title:"Reconfirm",body:"One or more items expired right after you clicked Purchase. Please review your order and try again."}};function Viewport()
{}
Viewport.define(null,{},{init:function(context)
{this.resized=new Event();this.context=context||window;this.setBounds();this.context.onresize=this.contextOnResize.bind(this);return this;},contextOnResize:function()
{this.setBounds();this.resized.fire(this);},setBounds:function()
{var context=this.context;if(context.self&&(context.self.innerHeight!==undefined))
{this.width=window.self.innerWidth;this.height=window.self.innerHeight;}
else if(context.document.documentElement&&context.document.documentElement.clientHeight!==undefined)
{this.width=context.document.documentElement.clientWidth;this.height=context.document.documentElement.clientHeight;}
else
{throw"Viewport can not set bounds";}}});Formatters={longUTCDateFromTicks:function(ticks,options)
{return Formatters.longUTCDate(new Date(ticks),options);},longUTCDate:function(date,options)
{options=options||{};var comma=(options.comma===undefined)?true:options.comma;return date.getUTCMonthName()+" "+
date.getUTCDate().toString()+
(comma?", ":" ")+
date.getUTCFullYear().toString();},longUTCMonthAndYearFromTicks:function(ticks)
{return Formatters.longUTCMonthAndYear(new Date(ticks));},longUTCMonthAndYear:function(date)
{return date.getUTCMonthName()+", "+
date.getUTCFullYear().toString();},money:function(cents)
{return formatPrice(cents);}};function Value()
{}
Value.define(Object,{},{init:function(obj,attr)
{this.obj=obj;this.attr=attr;this.changed=new Event();return this;},get:function()
{return this.obj[this.attr];},set:function(value)
{if(value!==this.get())
{this.obj[this.attr]=value;this.changed.fire();}},bindTo:function(target)
{var binding=this.changed.attach(function(){target.setValue(this.get());}.bind(this));target.addResource(binding);target.setValue(this.get());}});function Model()
{}
Model.define(null,{associations:[],cache:new Cache(),cacheEnabled:false,readCache:function(modelRelativeKey,fetch,success,error,complete)
{var key;if(this.cacheEnabled)
{key=this.singular+"/"+modelRelativeKey;Model.cache.read(key,fetch,success,error,complete);}
else
{fetch(success,error,complete);}},create:function(attrs,success,error,complete)
{return Application.instance.dataSource.create(this,attrs,success,error,complete);},find:function(id,success,error,complete)
{var key="find/"+id.toString();this.readCache(key,app.dataSource.findModel.bind(app.dataSource).curry(this,id),success,error,complete);},findAll:function(success,error,complete)
{return this.findFiltered({},success,error,complete);},findFiltered:function(params,success,error,complete)
{var key="findFiltered/"+JSON.stringify(params);this.readCache(key,app.dataSource.findManyModels.bind(app.dataSource).curry(this,params),success,error,complete);},findNamedSet:function(name,success,error,complete)
{var key="findNamedSet/"+name;this.readCache(key,app.dataSource.findNamedSetModels.bind(app.dataSource).curry(this,name,{}),success,error,complete);},findSingleton:function(success,error,complete)
{var key="findSingleton";this.readCache(key,app.dataSource.findSingletonModel.bind(app.dataSource).curry(this),function(model){model.singleton=true;success(model);},error,complete);},findNamedSingleton:function(name,success,error,complete)
{var key="findNamedSingleton/"+name;this.readCache(key,app.dataSource.findNamedSingletonModel.bind(app.dataSource).curry(this,name),function(model){model.singleton=true;model.singular=name;success(model);},error,complete);},fromId:function(id)
{return new this().init({id:id});},fromAttrs:function(attrs)
{return new this().init(attrs);},manyFromAttrs:function(attrsArray)
{var i;var many=[];for(i=0;i<attrsArray.length;++i)
{many.push(this.fromAttrs(attrsArray[i]));}
return many;},hasMany:function(target)
{this.addAssociation(new HasManyAssociation(this,target));},addAssociation:function(association)
{this.associations.push(association);association.createMethods(this);},getAssociationByTargetPluralName:function(targetPluralName)
{var i;var association;for(i=0;i<this.associations.length;++i)
{association=this.associations[i];if(association.target.plural===targetPluralName)
{return association;}}
return null;}},{init:function(attrs)
{this.values={};this.updated=new Event();this.resources=new ArrayList();this.singleton=false;this.singular=null;this.plural=null;this.initAssociated();this.setAttributes(attrs||{});return this;},getSingular:function()
{return this.singular||this.klass.singular;},getPlural:function()
{return this.plural||this.klass.plural;},get:function(attr)
{return this[attr];},set:function(attr,value)
{var val=this.values[attr];if(val===undefined)
{this[attr]=value;}
else
{val.set(value);}},value:function(attr)
{var val=this.values[attr];if(val===undefined)
{val=this.values[attr]=new Value().init(this,attr);}
return val;},destroy:function()
{var i;for(i=0;i<this.resources.getLength();++i)
{this.resources.get(i).destroy();}
this.resources.clear();},update:function(attrs,success,error,complete)
{app.dataSource.updateModel(this,attrs,success,error,complete);},refresh:function(success,error,complete)
{this.klass.find(this.id,function(model){this.setAttributes(model.attributes);success(this);}.bind(this),error,complete);},refreshSingleton:function(success,error,complete)
{this.klass.findNamedSingleton(this.getSingular(),function(model){this.setAttributes(model.attributes);if(success)success(this);}.bind(this),error,complete);},findAssociated:function(targetClass,success,error,complete)
{var key="findAssociated/"+this.id+"/"+targetClass.singular;this.klass.readCache(key,app.dataSource.findAssociatedModels.bind(app.dataSource).curry(this,targetClass),success,error,complete);},findAssociatedNamedSet:function(setName,targetClass,success,error,complete)
{var key="findAssociatedNamedSet/"+this.id+"/"+
targetClass.singular+"/"+setName;this.klass.readCache(key,app.dataSource.findAssociatedNamedSetModels.bind(app.dataSource).curry(this,setName,targetClass),success,error,complete);},addResource:function(resource)
{this.resources.add(resource);},removeResource:function(resource)
{this.resources.remove(resource);},initAssociated:function()
{var i;var association;for(i=0;i<this.klass.associations.length;++i)
{association=this.klass.associations[i];this[association.target.plural]=association.klass.getDefaultValue();}},setAttributes:function(attrs)
{var attr;var association;var associated;var i,key;this.attributes=attrs;for(key in attrs)
{association=this.klass.getAssociationByTargetPluralName(key);if(association)
{this[key]=association.parse(attrs[key]);}
else
{this.set(key,attrs[key]);}}
this.updated.fire(this);}});function Member()
{Model.call(this);}
Member.define(Model,{singular:"member",plural:"members",current:null,findCurrent:function(success,error,complete)
{app.dataSource.findSingleton({singular:"current_member"},function(data){var member=this.fromAttrs(data);member.singleton=true;member.singular="current_member";success(member);}.bind(this),error,complete);},create:function(attrs,invitationCode,success,error,complete)
{var params=DataSource.createModelParams(attrs,"member");params["invitation_code"]=invitationCode||null;app.dataSource.create(this,params,function(data){success(this.fromAttrs(data));}.bind(this),error,complete);},initiatePasswordReset:function(email,success,error,complete)
{app.dataSource.invokeClassMethod(this,"initiate_password_reset",{email:email},success,error,complete);},resetPassword:function(code,password,success,error,complete)
{app.dataSource.invokeClassMethod(this,"reset_password",{code:code,password:password},success,error,complete);}},{updatePassword:function(password,success,error,complete)
{app.dataSource.invokeSingletonInstanceMethod(this,"update_password",{password:password},success,error,complete);}});function Association()
{}
function HasManyAssociation(source,target)
{this.source=source;this.target=target;}
HasManyAssociation.define(Association,{getDefaultValue:function()
{return[];}},{createMethods:function()
{var sourceClass=this.source;var targetClass=this.target;sourceClass.prototype["load"+targetClass.plural]=function(success,error,complete)
{Application.instance.dataSource.findAssociated(sourceClass,targetClass,this.id,function(models)
{this[targetClass.plural]=models;success(models);},error,complete);};},parse:function(array)
{var models=[];var i;for(i=0;i<array.length;++i)
{models.push(new this.target().init(array[i]));}
return models;}});function Session()
{}
Session.singular="session";Session.plural="sessions";Session.create=function(credentials,success,error,complete)
{return app.dataSource.createSingleton(this,credentials,function(data){success(Member.fromAttrs(data));},error,complete);};Session.destroy=function(success,error,complete)
{return app.dataSource.destroySingleton(this,success,error,complete);};function OrderLine()
{}
OrderLine.define(Model,{singular:"line",plural:"lines"},{init:function(attrs)
{this.expired=new Event();this.lastSetAttributesTime=null;return Model.prototype.init.call(this,attrs);},fireExpired:function()
{this.expired.fire();},getTotal:function()
{return this.quantity*this.unit_price;},getTotalRetail:function()
{return this.quantity*this.unit_retail_price;},getCurrentExpiresIn:function()
{var elapsed=new Date().getTime()-this.lastSetAttributesTime.getTime();return this.expires_in-elapsed;},isExpired:function()
{return(this.getCurrentExpiresIn()<=0);},setAttributes:function(attrs)
{this.lastSetAttributesTime=new Date();Model.prototype.setAttributes.apply(this,arguments);}});function Order()
{}
Order.define(Model,{singular:"order",plural:"orders"},{init:function(attrs)
{Model.prototype.init.apply(this,arguments);this.calculating=false;this.lineExpired=new Event();this.addResource(app.timer.tick.attach(this.timerTick.bind(this)));return this;},add:function(saleSku,success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"add_sale_sku",{"sale_sku[id]":saleSku.id},success,error,complete);},remove:function(saleSku,success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"remove_sale_sku",{"sale_sku[id]":saleSku.id},success,error,complete);},changeQuantity:function(saleSku,quantity,success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"change_sale_sku_quantity",{"sale_sku[quantity]":quantity,"sale_sku[id]":saleSku.id},success,error,complete);},applyPromotion:function(code,success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"apply_promotion",{code:code},success,error,complete);},clearPromotions:function(success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"clear_promotions",{},success,error,complete);},calculate:function(success,error,complete)
{this.setAttributes({calculating:true});app.dataSource.invokeSingletonInstanceMethod(this,"calculate",{},function(data){this.setAttributes({calculating:false,tax:data.tax,shipping:data.shipping});success();}.bind(this),error,complete);},digest:function()
{var i,line;var parts=[];var lines=this.getUnexpiredLines();for(i=0;i<lines.length;++i)
{line=lines[i];parts.push(line.sale_sku.id.toString()+","+
line.quantity.toString());}
return parts.join("|");},timerTick:function()
{var i,line;for(i=0;i<this.lines.length;++i)
{line=this.lines[i];if(line.isExpired()&&!line.firedLineExpired)
{line.firedLineExpired=true;this.lineExpired.fire(line);line.fireExpired();}}},getLinesTotal:function()
{var i,line;var lines=this.getUnexpiredLines();var total=0;for(i=0;i<lines.length;++i)
{line=lines[i];total+=line.getTotal();}
return total;},hasPromotion:function()
{return(this.promotions.length>0);},getPromotionCode:function()
{return this.hasPromotion()?this.promotions[0].code:null;},getDiscount:function()
{var discount=this.dollar_discount+
Math.floor(this.percentage_discount/100*this.getLinesTotal());return Math.min(discount,this.getLinesTotal());},getSubtotal:function()
{return this.getLinesTotal()-this.getDiscount();},getTotal:function()
{return this.getSubtotal()+this.shipping+this.tax;},getTotalRetail:function()
{var i,line;var lines=this.getUnexpiredLines();var total=0;for(i=0;i<lines.length;++i)
{line=lines[i];total+=line.getTotalRetail();}
return total;},getTotalQuantity:function()
{var total=0;var i;var lines=this.getUnexpiredLines();for(i=0;i<lines.length;++i)
{total+=lines[i].quantity;}
return total;},getTotalSavings:function()
{return this.getTotalRetail()-this.getTotal();},getOrderLineBySaleSku:function(saleSku)
{var i;var line;var lines=this.getUnexpiredLines();for(i=0;i<lines.length;++i)
{line=lines[i];if(line.sale_sku.id==saleSku.id)
{return line;}}
return null;},getOrderLineWithSoonestExpiration:function()
{var i;var line;var soonest=null;var lines=this.getUnexpiredLines();for(i=0;i<lines.length;++i)
{line=lines[i];if((soonest===null)||(line.expires_at<soonest.expires_at))
{soonest=line;}}
return soonest;},isEmpty:function()
{return(this.getTotalQuantity()===0);},getUnexpiredLines:function()
{if(this.status==2)
{return this.lines;}
var i,line;var unexpired=[];for(i=0;i<this.lines.length;++i)
{line=this.lines[i];if(!line.isExpired())
{unexpired.push(line);}}
return unexpired;},containsSaleSku:function(saleSku)
{return(null!==this.getOrderLineBySaleSku(saleSku));}});Order.hasMany(OrderLine);function Checkout()
{}
Checkout.define(Model,{singular:"checkout",plural:"checkouts"},{updateUnsavedShippingAddress:function(address,success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"update_unsaved_shipping_address",DataSource.createModelParams(address,"address"),success,error,complete);},updateUnsavedCreditCard:function(creditCard,success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"update_unsaved_credit_card",DataSource.createModelParams(creditCard,"credit_card"),success,error,complete);},calculate:function(success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"calculate",{},success,error,complete);},confirm:function(digest,success,error,complete)
{app.dataSource.invokeSingletonModelMutator(this,"confirm",{digest:digest},success,error,complete);}});function Sale()
{}
Sale.define(Model,{singular:"sale",plural:"sales",cacheEnabled:true,findFeatured:function(success,error,complete)
{this.findNamedSet("featured",success,error,complete);},findCurrent:function(success,error,complete)
{this.findNamedSet("current",success,error,complete);}},{init:function(attrs)
{this.lastSetAttributesTime=null;return Model.prototype.init.call(this,attrs);},findSoldOutSaleSkuIds:function(success,error,complete)
{app.dataSource.findAssociated(this,{plural:"sold_out_sale_sku_ids"},success,error,complete);},hasStarted:function()
{return(new Date(this.start_time)<new Date());},startsTodayEst:function()
{var timeUntilStart=this.start_time-new Date().getTime();var startTimeEst=new Date(this.start_time_est);var startOfDayEst=Date.UTC(startTimeEst.getUTCFullYear(),startTimeEst.getUTCMonth(),startTimeEst.getUTCDate());return(timeUntilStart<startTimeEst.getTime()-startOfDayEst);},setAttributes:function(attrs)
{Model.prototype.setAttributes.apply(this,arguments);this.lastSetAttributesTime=new Date();},getCurrentEndsIn:function()
{var elapsed=new Date().getTime()-this.lastSetAttributesTime.getTime();return this.ends_in-elapsed;}});function SaleSku()
{}
SaleSku.define(Model,{singular:"sale_sku",plural:"sale_skus",cacheEnabled:true},{init:function()
{Model.prototype.init.apply(this,arguments);this.soldOutChanged=new Event();return this;},populate:function(success,error,complete)
{this.klass.find(this.id,function(model){delete model.attributes.sold_out;this.setAttributes(model.attributes);success();}.bind(this),error,complete);},setSoldOut:function(value)
{if(value!==this.sold_out){this.sold_out=value;this.soldOutChanged.fire(this);}},refreshSoldOut:function(success,error,complete)
{app.dataSource.invokeInstanceGetterMethod(this,"sold_out",{},function(data){this.sold_out=data;success(this);}.bind(this),error,complete);}});function Clip()
{}
Clip.define(Model,{singular:"clip",plural:"clips",cacheEnabled:true},{getLeft:function()
{return this.x;},getTop:function()
{return this.y;},getBottom:function()
{return this.y+this.height;},getRight:function()
{return this.x+this.width;},intersects:function(other)
{return!((this.getLeft()>=other.getRight())||(this.getRight()<=other.getLeft())||(this.getTop()>=other.getBottom())||(this.getBottom()<=other.getTop()));}});function Story()
{}
Story.define(Model,{singular:"story",plural:"stories",cacheEnabled:true},{getHeight:function()
{var i;var height=0;for(i=0;i<this.clips.length;++i)
{height=Math.max(height,this.clips[i].getBottom());}
return height;},getMaxZ:function()
{var i;var z=null;for(i=0;i<this.clips.length;++i)
{z=(z===null)?z:Math.max(z,this.clips[i].z);}
return z;},getMinZ:function()
{var i;var z=null;for(i=0;i<this.clips.length;++i)
{z=(z===null)?z:Math.min(z,this.clips[i].z);}
return z;}});Story.hasMany(Clip);function Invitation()
{}
Invitation.define(Model,{singular:"invitation",plural:"invitations",createManyFromEmails:function(emails,success,error,complete)
{app.dataSource.invokeClassMethod(this,"create_many_from_emails",{emails:emails},success,error,complete);}},{});function Vendor()
{}
Vendor.define(Model,{singular:"vendor",plural:"vendors",cacheEnabled:true,findFeatured:function(success,error,complete)
{this.findNamedSet("featured",success,error,complete);}},{});function Page()
{}
Page.define(null,{cache:new Cache(),find:function(id,success,error,complete)
{Page.cache.read(id,this.get.bind(this).curry(id),success,error,complete);},get:function(id,successCallback,errorCallback,completeCallback)
{var url="/page/"+encodeURIComponent(id);$.ajax({url:url,data:{},async:true,dataType:"html",global:false,type:"GET",success:function(data,textStatus)
{if(successCallback){successCallback(data);}
if(completeCallback){completeCallback();}},error:function(xhr,textStatus,errorThrown)
{if(errorCallback){errorCallback(DataSource.createError(xhr,textStatus,errorThrown));}
if(completeCallback){completeCallback();}}});}},{});function SaleCategory()
{}
SaleCategory.define(Model,{singular:"sale_category",plural:"sale_categories",cacheEnabled:true},{});function CreditCardType(id,name,numberPattern)
{this.id=id;this.name=name;this.numberPattern=numberPattern;}
CreditCardType.find=function(id)
{var type=CreditCardType.all.findFirst(function(card){return card.id===id;});if(type===null){throw"Invalid credit card ID";}
return type;};CreditCardType.all=function()
{var i;var types=[];var data=[[1,'Visa','visa',/^4\d{12}(\d{3})?$/],[2,'MasterCard','master',/^(5[1-5]\d{4}|677189)\d{10}$/],[3,'Discover','discover',/^(6011|65\d{2})\d{12}$/],[4,'American Express','american_express',/^3[47]\d{13}$/],[5,'Diners Club','diners_club',/^3(0[0-5]|[68]\d)\d{11}$/],[6,'JCB','jcb',/^3528\d{12}$/],[7,'Switch','switch',/^6759\d{12}(\d{2,3})?$/],[8,'Solo','solo',/^6767\d{12}(\d{2,3})?$/],[9,'Dankort','dankort',/^5019\d{12}$/],[10,'Maestro','maestro',/^(5[06-8]|6\d)\d{10,17}$/],[11,'Forbrugsforeningen','forbrugsforeningen',/^600722\d{10}$/],[12,'Laser','laser',/^(6304|6706|6771|6709)\d{8}(\d{4}|\d{6,7})?$/]];for(i=0;i<data.length;++i)
{types.push(new CreditCardType(data[i][0],data[i][1],data[i][3]));}
return types;}();function Feature()
{}
Feature.define(Model,{singular:"feature",plural:"features",cacheEnabled:true,findCurrent:function(success,error,complete)
{this.findNamedSet("current",success,error,complete);}},{});function View()
{}
View.prototype={init:function(element,params)
{params=params||{};this.children=new ArrayList();this.resources=new ArrayList();this.element=element;this.params=params;this.initView(element,params);this.createControls();return this;},initView:function(element,params)
{},destroy:function()
{var i;for(i=0;i<this.resources.getLength();++i)
{this.resources.get(i).destroy();}
this.resources.clear();this.destroyView();},destroyView:function()
{if(this.root&&this.root.parentNode)
{this.root.parentNode.removeChild(this.root);}},createControls:function()
{},render:function()
{var i;this.renderView(this.element);for(i=0;i<this.children.getLength();++i)
{this.children.get(i).render(parent);}
this.update();this.setFocus();},renderView:function(element)
{if(this.root)
{element.appendChild(this.root);}},update:function()
{var i;this.updateView();for(i=0;i<this.children.getLength();++i)
{this.children.get(i).update();}},updateView:function()
{},hide:function()
{$(this.root).hide();},show:function()
{$(this.root).show();},toggle:function(show)
{show?this.show():this.hide();},scrollIntoView:function(topPadding)
{topPadding=topPadding||0;if(this.root){window.scrollTo(0,$(this.root).offset().top-topPadding);}},setFocus:function()
{},addResource:function(resource)
{this.resources.add(resource);},removeResource:function(resource)
{this.resources.remove(resource);},addChild:function(view)
{this.children.add(view);this.resources.add(view);},removeChild:function(view)
{this.children.remove(view);this.resources.remove(view);},raiseCommand:function(command)
{this.controller.routeCommand(command);},raiseError:function(error)
{this.controller.handleError(error);},focusFirstInput:function()
{var inputs=$(":input",this.element);if(inputs.length>0)
{$(inputs[0]).focus().select();}},createErrorMessages:function(ul,errors)
{var key;var messages;var b=new ElementBuilder();clearChildNodes(ul);for(key in errors)
{messages=errors[key];if(messages.length>0)
{b.li(ul,null,{html:messages[0]});}}},highlightFieldsWithErrors:function(parent,errors)
{var i;var inputs=$(":input",parent);var hasError=false;for(i=0;i<inputs.length;++i)
{hasError=errors.hasOwnProperty(inputs[i].id);$(inputs[i]).toggleClass("error",hasError);}},collectFormValues:function(parent)
{var values={};var value;var inputs=$(":input",parent);var i,input;for(i=0;i<inputs.length;++i)
{input=inputs[i];value=input.value;if(value==="")value="";values[input.id]=value;}
return values;}};function MessageView()
{View.call();}
MessageView.define(View,{},{initView:function(element,params)
{this.message=params.message;},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"message_view");if(this.message.title){b.h1(root,"first",{html:this.message.title});}
if(this.message.body){b.p(root,null,{html:this.message.body});}}});function HtmlView()
{View.call(this);}
HtmlView.define(View,{},{createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"html_view");root.innerHTML=this.params.html;}});function LabelView()
{View.call(this);}
LabelView.define(View,{},{init:function(element,value,formatter)
{View.prototype.init.call(this,element);this.formatter=formatter;value.bindTo(this);return this;},createControls:function()
{this.root=new ElementBuilder().div(null);},setValue:function(value)
{this.root.innerHTML=this.formatter?this.formatter(value):h(value);}});function CountdownView()
{View.call(this);}
CountdownView.define(View,{},{initView:function(element,params)
{params=params||{};this.dotIsGreen=null;this.id=params.id||null;this.warningMsecs=params.warningMsecs||null;this.expiredText=params.expiredText||null;this.showDot=params.showDot||false;this.prefix=params.prefix||"";if(params.endsIn){this.setEndsIn(params.endsIn);}else{this.setEndsAt(params.endsAt);}
if(params.timer){this.timer=params.timer;}else{this.timer=new Timer();this.addResource(this.timer);}},renderView:function(element)
{View.prototype.renderView.call(this,element);this.addResource(this.timer.tick.attach(this.timerTick.bind(this)));this.update();this.timer.start();},createControls:function()
{var div=this.root=document.createElement("div");div.className="countdown_view";if(this.id!==null){this.div.id=this.id;}
var dot=this.dot=document.createElement("img");dot.id="dot";dot.width=dot.height="8";dot.style.width=dot.style.height="8px";dot.src="";dot.alt="";div.appendChild(dot);$(dot).toggle(this.showDot);var span=this.textSpan=document.createElement("span");span.id="text";div.appendChild(span);},setEndsIn:function(msecs)
{this.endTimeMsecs=new Date().getTime()+msecs;},setEndsAt:function(time)
{this.endTimeMsecs=time.getTime();},updateView:function()
{var msecsLeft=Math.max(0,this.endTimeMsecs-new Date().getTime());var span=new TimeSpan(msecsLeft);var dotIsGreen;var imageKey;var text;if((msecsLeft===0)&&this.expiredText)
{this.setText(this.expiredText);}
else
{if(span.totalDays>0)
{text=span.days.toString()+"d "+span.hours.toString()+"h";}
else if(span.totalHours>0)
{text=span.hours.toString()+"h "+span.minutes.toString()+"m";}
else if(span.totalMinutes>0)
{text=span.minutes.toString()+"m "+span.seconds.toString()+"s";}
else if(span.totalMilliseconds>0)
{text=span.seconds.toString()+"s";}
else
{text="0s";}
this.setText(this.prefix+text);}
if(this.showDot)
{dotIsGreen=((this.warningMsecs===null)||(msecsLeft>this.warningMsecs));if((this.dotIsGreen===null)||(this.dotIsGreen!==dotIsGreen))
{this.dotIsGreen=dotIsGreen;imageKey=dotIsGreen?"images/countdown_dot_green.gif":"images/countdown_dot_red.gif";this.dot.src=Application.instance.assetUrl(imageKey);}}
if(this.warningMsecs!==null)
{$(this.div).toggleClass("countdown_warning",msecsLeft<=this.warningMsecs);}},setText:function(text)
{this.textSpan.innerHTML=h(text);},timerTick:function()
{this.update();}});function FormView()
{View.call(this);}
FormView.define(View,{},{initView:function(element,params)
{this.formBuilder=new FormBuilder();this.fieldViews=[];this.fieldViewsById={};this.defaultCommand=null;},createControls:function()
{var root;var params=this.params;var b=new ElementBuilder();root=this.root=b.div(null,"form_view");$(root).keypress(this.rootOnKeyPress.bind(this));this.errorsUl=b.ul(root,"errors");$(this.errorsUl).hide();this.tbody=b.tbody(b.table(root));this.actionsDiv=b.div(root,"actions");},reset:function()
{this.fieldViews.each(function(fieldView){fieldView.reset();});this.clearErrors();},text:function(id,value,label)
{this.addField(new TextFieldView().init(null,id,value),label);},password:function(id,value,label)
{this.addField(new PasswordFieldView().init(null,id,value),label);},textArea:function(id,value,label)
{this.addField(new TextAreaFieldView().init(null,id,value),label);},date:function(id,value,label)
{this.addField(new DateFieldView().init(null,id,value),label);},monthAndYear:function(monthId,yearId,monthValue,yearValue,label)
{var tr,td;var monthDiv,yearDiv;var fieldView;var b=new ElementBuilder();tr=b.tr(this.tbody);td=b.td(tr,"label",{html:label});td=b.td(tr,"field month_and_year_field");monthSpan=b.span(td);fieldView=new TextFieldView().init(monthSpan,monthId,monthValue);this.fieldViews.push(fieldView);this.addFieldView(fieldView);b.text(td," / ");yearSpan=b.span(td);fieldView=new TextFieldView().init(yearSpan,yearId,yearValue);this.addFieldView(fieldView);},action:function(text,command,options)
{options=options||{};var important=options.important?true:false;var builder=new ElementBuilder();var div=builder.div(this.actionsDiv,"form_action");var a=builder.a(div,null,{html:text||"Submit"});$(div).toggleClass("important_form_action",important);if(!this.defaultCommand||options.defaultCommand){this.defaultCommand=command;}
a.onclick=function(){app.doCommand(command||"submit");}.bind(this);},isValid:function()
{var i;var valid=true;for(i=0;i<this.fieldViews.length;++i)
{if(!this.fieldViews[i].isValid())
{return false;}}
return true;},getValues:function()
{var i;var fieldView;var values={};for(i=0;i<this.fieldViews.length;++i)
{fieldView=this.fieldViews[i];values[fieldView.id]=fieldView.getValue();}
return values;},getFieldView:function(id)
{return this.fieldViewsById[id];},focus:function()
{if(this.fieldViews.length>0){this.fieldViews[0].focus();}},showValidationErrors:function()
{var i;var errors={};var fieldView;for(i=0;i<this.fieldViews.length;++i)
{fieldView=this.fieldViews[i];if(!fieldView.isValid())
{errors[fieldView.id]=fieldView.getErrors();}}
this.showErrors(errors);},showErrors:function(errors)
{this.highlightFieldsWithErrors(errors);this.createErrorMessageListItems(errors);$(this.errorsUl).slideDown("fast");this.focus();},clearErrors:function()
{$(this.errorsUl).hide();clearChildNodes(this.errorsUl);},addField:function(fieldView,label)
{this.addFieldView(fieldView);var tr,td;var b=new ElementBuilder();tr=b.tr(this.tbody);if(label)
{td=b.td(tr,"label",{html:label});td=b.td(tr,"field");fieldView.element=td;}
else
{td=b.td(tr,"field",{colSpan:2});fieldView.element=td;}},addFieldView:function(fieldView)
{this.fieldViews.push(fieldView);this.fieldViewsById[fieldView.id]=fieldView;this.addChild(fieldView);},createErrorMessageListItems:function(errors)
{var key;var messages;var b=new ElementBuilder();clearChildNodes(this.errorsUl);for(key in errors)
{messages=errors[key];if(messages.length>0)
{b.li(this.errorsUl,"error",{html:messages[0]});}}},highlightFieldsWithErrors:function(errors)
{},rootOnKeyPress:function(event)
{if(event.which===13){if(this.defaultCommand){app.doCommand(this.defaultCommand);}}}});function FieldView()
{View.call(this);}
FieldView.define(View,{defaultValue:""},{init:function(element,id,value)
{View.prototype.init.call(this,element);this.id=id;if(value instanceof Value)
{this.value=value;value.bindTo(this);}
else if(value!==undefined)
{this.setValue(value);}
return this;},reset:function()
{if(this.value)
{this.setValue(this.value.get());}
else
{this.setValue(this.klass.defaultValue);}},focus:function()
{},setValue:function(value)
{throw"Not implemented";},getValue:function()
{if(!this.isValid())
{throw"Value is not valid";}
else
{return this.getValueInternal();}},getValueInternal:function()
{throw"Not implemented";},isValid:function()
{return true;},getErrors:function()
{return this.isValid()?[]:[this.id+" is invalid"];}});function InputFieldView()
{FieldView.call(this);}
InputFieldView.define(FieldView,{},{focus:function()
{$(this.input).focus().select();},createControls:function()
{this.root=this.input=this.createInput();},createInput:function()
{throw"Not implemented";},setValue:function(value)
{this.input.value=value||"";},getValueInternal:function()
{return this.input.value;}});function TextFieldView()
{InputFieldView.call(this);}
TextFieldView.define(InputFieldView,{},{createInput:function()
{return new FormBuilder().text(this.attr);}});function PasswordFieldView()
{InputFieldView.call(this);}
PasswordFieldView.define(InputFieldView,{},{createInput:function()
{return new FormBuilder().password(this.attr);}});function TextAreaFieldView()
{InputFieldView.call(this);}
TextAreaFieldView.define(InputFieldView,{},{createInput:function()
{return new FormBuilder().textArea(this.attr);}});function DateFieldView()
{FieldView.call(this);}
DateFieldView.define(FieldView,{},{createControls:function()
{var b=new FormBuilder();this.root=this.input=b.text(this.attr);},focus:function()
{$(this.input).focus();},isValid:function()
{return!isNaN(Date.parse(this.input.value));},setValue:function(value)
{if(value)
{var date=new Date(value);this.input.value=(1+date.getUTCMonth()).toString()+"/"+
date.getUTCDate().toString()+"/"+
date.getUTCFullYear().toString();}
else
{this.input.value="";}},getValueInternal:function()
{var date=new Date(Date.parse(this.input.value));return Date.UTC(date.getFullYear(),date.getMonth(),date.getDate());}});function DrawersView()
{View.call(this);}
DrawersView.define(View,{},{initView:function()
{this.drawers=[];},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"drawers_view");},createDrawer:function(label,params)
{params=params||{};params.label=label;var drawer=new DrawerView().init(this.root,params);this.drawers.push(drawer);this.addChild(drawer);this.addResource(drawer.handleClicked.attach(this.drawerHandleClicked.bind(this)));return drawer;},openDrawerAndCloseOthers:function(openDrawer)
{var i,drawer;openDrawer.open();for(i=0;i<this.drawers.length;++i)
{drawer=this.drawers[i];if(openDrawer!==drawer)
{drawer.close();}}},drawerHandleClicked:function(drawer)
{if(drawer.isOpen)
{drawer.close();}
else
{this.openDrawerAndCloseOthers(drawer);}}});function DrawerView()
{View.call(this);}
DrawerView.define(View,{},{initView:function(element,params)
{params=params||{};this.label=params.label||"";this.isOpen=params.open?true:false;this.handleClicked=new Event();},open:function()
{$(this.contents).slideDown("fast");this.setOpen(true);},close:function(speed)
{$(this.contents).slideUp("fast");this.setOpen(false);},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"drawer_view");var handle=this.handle=b.div(root,"handle",{html:this.label});var contents=this.contents=b.div(root,"contents");handle.onclick=function(){this.handleClicked.fire(this);}.bind(this);$(contents)[this.isOpen?"show":"hide"]();this.setOpen(this.isOpen);},setOpen:function(open)
{this.isOpen=open;$(this.root).toggleClass("open_drawer_view",open);},addContentChild:function(child)
{child.element=this.contents;this.addChild(child);}});function AttributesTableView()
{View.call(this);}
AttributesTableView.define(View,{},{initView:function(element,params)
{},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"attributes_table_view");var table=b.table(root);this.tbody=b.tbody(table);this.actionsDiv=b.div(root,"actions");},add:function(value,label,formatter)
{var tr,td;var b=new ElementBuilder();tr=b.tr(this.tbody);td=b.td(tr,"label",{html:label});td=b.td(tr,"value");this.addChild(new LabelView().init(td,value,formatter));},action:function(text,command,options)
{options=options||{};var important=options.important?true:false;var builder=new ElementBuilder();var div=builder.div(this.actionsDiv,"action");var a=builder.a(div,null,{html:text||"Submit"});$(div).toggleClass("important_action",important);a.onclick=function(){app.doCommand(command);}.bind(this);}});function FrontView()
{View.call(this);}
FrontView.define(View,{},{createControls:function()
{b=new ElementBuilder();var root=this.root=b.div(null,"front_view");this.throbber=b.img(root,null,{id:"throbber",src:app.assetUrl("images/throbber.gif")});$(this.throbber).hide();},showError:function(message)
{alert(message);},showThrobber:function()
{$(this.throbber).show();},hideThrobber:function()
{$(this.throbber).hide();}});function WelcomeView()
{View.call(this);}
WelcomeView.define(View,{},{initView:function(element,params)
{this.leftImageUrl=params.leftImageUrl;},createControls:function()
{var frame,fixedFrameDiv,leftFixedFrameDiv,contentDiv;var topMenu,topMenuView;b=new ElementBuilder();frame=this.root=b.div(this.element,"welcome_view");fixedFrameDiv=b.div(frame,null,{id:"fixed_frame"});leftFixedFrameDiv=b.div(frame,null,{id:"left_fixed_frame"});this.contentDiv=b.div(frame,"column",{id:"content"});b.img(leftFixedFrameDiv,null,{id:"logo",src:this.leftImageUrl||app.assetUrl("images/welcome_logo.gif"),alt:"Market for Drama"});topMenu=b.div(fixedFrameDiv,"top_menu");topMenuView=new MenuBarView().init(topMenu,this.controller);this.addChild(topMenuView);topMenuView.createGoMenuView("Sign In","/welcome/login");topMenuView.createGoMenuView("About","/welcome/page?about");topMenuView.createGoMenuView("Contact","/welcome/page?contact");topMenuView.createGoMenuView("Privacy","/welcome/page?privacy");}});function LoginView()
{View.call(this);}
LoginView.define(View,{},{init:function(element,params)
{this.signupStartOpen=((params.invitation_code!==undefined)||(params.signup!==undefined));return View.prototype.init.apply(this,arguments);},setFocus:function()
{if(this.signupStartOpen){this.params.invitation_recipient_email?this.signupFormView.getFieldView("password").focus():this.signupFormView.focus();}else{this.params.email?this.loginFormView.getFieldView("password").focus():this.loginFormView.focus();}},showValidationRequestMessage:function()
{$(this.loginSignupDiv).slideUp("medium",function(){$(this.validationRequestMessageDiv).slideDown("fast");}.bind(this));},createControls:function()
{var root;var loginSignupDiv;var description,forms;var loginDrawerDiv,signupDrawerDiv;var loginContentsDiv,signupContentsDiv;var loginHandleDiv,signupHandleDiv;var loginFormDiv,signupFormDiv;var loginDrawer,signupDrawer,drawerCloser;var table,tbody,tr,td;var actionsDiv;var el;b=new ElementBuilder();root=this.root=b.div(this.element,"login_view");b.div(root,null,{id:"header",innerHTML:"Beauty<br/>Shopping Events<br/>&amp; Editorial."});this.validationRequestMessageDiv=b.div(root,null,{id:"validation_message",innerHTML:"<p class='first'><b>Thank you for signing up.</b></p><p>Please check your\
     email for a message from Market for Drama. Click the enclosed link to\
     validate your email address and gain immediate access to Market for\
     Drama.</p>"});$(this.validationRequestMessageDiv).hide();loginSignupDiv=this.loginSignupDiv=b.div(root,null,{id:"login_signup"});description=b.div(loginSignupDiv,null,{id:"description",innerHTML:"<p class='first'>Market for Drama is a private online beauty destination,<br/>\
     providing members with access to original content and<br/>\
     exclusive shopping events from luxury beauty brands.</p>\
     <p>Membership is free.</p>"});forms=b.div(loginSignupDiv,null,{id:"forms"});loginDrawerDiv=b.div(forms,"drawer");loginHandleDiv=b.div(loginDrawerDiv,"handle");loginContentsDiv=b.div(loginDrawerDiv,"contents");b.a(loginHandleDiv,"clickable",{innerHTML:"<span class='important_action'>Sign In</span>"});this.validationSuccessMessageDiv=b.div(loginContentsDiv,"message",{html:"Thank you for validating your email address."});$(this.validationSuccessMessageDiv).toggle(this.params.validated==="1",0);loginFormDiv=this.loginFormDiv=b.div(loginContentsDiv,"form",{id:"login_form"});var loginFormView=this.loginFormView=new FormView().init(loginFormDiv);this.addChild(loginFormView);loginFormView.text("email",this.params.email,"Email");loginFormView.password("password",null,"Password");loginFormView.action("Enter","log_in",{important:true});loginFormView.action("Forgot Password","forgot_password");signupDrawerDiv=b.div(forms,"drawer");signupHandleDiv=b.div(signupDrawerDiv,"handle");signupContentsDiv=b.div(signupDrawerDiv,"contents");$(signupContentsDiv).hide();b.a(signupHandleDiv,"clickable",{innerHTML:"<span class='important_action'>Sign Up</span>"});signupFormDiv=this.signupFormDiv=b.div(signupContentsDiv,"form",{id:"signup_form"});var signupFormView=this.signupFormView=new FormView().init(signupFormDiv);this.addChild(signupFormView);signupFormView.text("email",this.params.invitation_recipient_email,"Email");signupFormView.password("password",null,"Password");signupFormView.password("password_confirm",null,"Password Confirm");signupFormView.text("first_name",null,"First Name");signupFormView.text("last_name",null,"Last Name");signupFormView.text("postal_code",null,"Zip");signupFormView.text("birthday",null,"Birthday (MM/DD/YYYY)");signupFormView.action("Submit","sign_up",{important:true});loginDrawer=this.loginDrawer=new Drawer(loginHandleDiv,loginContentsDiv,{startOpen:!this.signupStartOpen,closeOnClick:false});loginDrawer.didFinishOpen.attach(function(){$("#login_form input:first").focus();});signupDrawer=this.signupDrawer=new Drawer(signupHandleDiv,signupContentsDiv,{startOpen:this.signupStartOpen,closeOnClick:false});signupDrawer.didFinishOpen.attach(function(){$("#signup_form input:first").focus();});new DrawerCloser([loginDrawer,signupDrawer]);}});function ForgotPasswordView()
{View.call(this);}
ForgotPasswordView.define(View,{},{setFocus:function()
{this.formView.focus();},showSuccessMessage:function()
{$(this.beforeDiv).slideUp("medium",function(){$(this.afterDiv).slideDown("fast");}.bind(this));},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"forgot_password_view");b.h1(root,"first",{html:"Forgot Password"});var afterDiv=this.afterDiv=b.div(root,null,{html:"Please check your email for a message from Market for Drama\
      and click the enclosed link."});$(this.afterDiv).hide();var beforeDiv=this.beforeDiv=b.div(root);b.div(beforeDiv,null,{html:"Enter your email address below, and we will send you a message\
     with a link to reset your password."});var formDiv=b.div(beforeDiv,null,{id:"form"});var formView=this.formView=new FormView().init(formDiv);this.addChild(formView);formView.text("email","","Email");formView.action("Submit","initiate_password_reset",{important:true});formView.action("Back","back");}});function ResetPasswordView()
{View.call(this);}
ResetPasswordView.define(View,{},{setFocus:function()
{this.formView.focus();},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"reset_password_view");b.h1(root,"first",{html:"Reset Password"});var formDiv=b.div(root,null,{id:"form"});var formView=this.formView=new FormView().init(formDiv);this.addChild(formView);formView.password("password","","Password");formView.password("password_confirm","","Password Confirm");formView.action("Submit","reset_password",{important:true});}});function InsideView()
{View.call(this);}
InsideView.define(View,{},{initView:function(element,params)
{this.controller=params.controller;this.addResource(app.locationChanged.attach(this.applicationLocationChanged.bind(this)));},applicationLocationChanged:function(location)
{$(this.shopDiv).toggleClass("selected_half_link",location.hmatch("/store"));$(this.journalDiv).toggleClass("selected_half_link",location.hmatch("/journal"));},setBackgroundColor:function(white)
{this.logoImg.src=app.assetUrl(white?"images/logo.gif":"images/logo-journal.gif");this.throbberImg.src=app.assetUrl(white?"images/throbber.gif":"images/throbber-journal.gif");document.body.style.backgroundColor=white?"#fff":"#eee5ee";},createControls:function()
{var b=new ElementBuilder();var el;var frame;var fixedFrameDiv;var backgroundFixedFrameDiv;var leftFixedFrameDiv;var leftColumnDiv;var homeAnchor;var topMenu,topMenuView;frame=this.root=b.div(null,"inside_view");backgroundFixedFrameDiv=this.backgroundFixedFrame=b.div(frame,null,{id:"background_fixed_frame"});leftFixedFrameDiv=b.div(frame,null,{id:"left_fixed_frame"});fixedFrameDiv=this.fixedFrame=b.div(frame,null,{id:"fixed_frame"});this.contentContainer=b.div(frame,null,{id:"content"});b.div(frame,"clearer");b.div(backgroundFixedFrameDiv,null,{id:"color_background"});leftColumnDiv=b.div(leftFixedFrameDiv,null,{id:"left_column"});homeAnchor=b.a(leftColumnDiv,null,{href:"#/store"});this.logoImg=b.img(homeAnchor,null,{src:app.assetUrl("images/logo.gif"),alt:"Market for Drama",width:"65",height:"141",id:"logo"});this.menuDiv=b.div(leftColumnDiv,null,{id:"menu"});this.throbberImg=b.img(fixedFrameDiv,null,{src:app.assetUrl("images/throbber.gif"),alt:"",width:"16",height:"16",id:"throbber"});el=this.shopDiv=b.div(fixedFrameDiv,"half_link",{id:"shop_link"});b.a(el,null,{href:"#/store",html:"Shop"});el=this.journalDiv=b.div(fixedFrameDiv,"half_link",{id:"journal_link"});b.a(el,null,{href:"#/journal",html:"Journal"});el=this.userNameDiv=b.div(fixedFrameDiv,null,{id:"user_name"});this.addChild(new LabelView().init(el,Member.current.value("full_name")));topMenu=b.div(fixedFrameDiv,"top_menu");topMenuView=new MenuBarView().init(topMenu);this.addChild(topMenuView);topMenuView.createGoMenuView("Account","/store/account");topMenuView.createGoMenuView("Cart","/store/cart");topMenuView.createView(CartDetailsView,[this.controller]);topMenuView.createGoMenuView("Invite","/store/invite");topMenuView.createMenuView("Sign Out","javascript:app.doCommand( 'sign_out' );");topMenuView.render();}});function MenuView()
{View.call(this);}
MenuView.define(View,{},{init:function(element,label,href)
{this.label=label;this.href=href;this.childMenuViews=new ArrayList();this.contentsVisible=false;return View.prototype.init.call(this,element);},createControls:function()
{var menu;var label;var b=new ElementBuilder();var root=this.root=b.div(null,"menu_view");menu=this.menuDiv=b.div(root,"menu");label=b.div(menu,"label");b.a(label,null,{html:this.label,href:this.href});this.contentsDiv=b.div(menu);$(this.contentsDiv).hide();},addChildMenuView:function(menuView)
{menuView.element=this.contentsDiv;this.childMenuViews.add(menuView);this.addChild(menuView);},removeChildMenuView:function(menuView)
{this.childMenuViews.remove(menuView);this.removeChild(menuView);},isSelected:function(location)
{return false;},updateSelection:function(location)
{var i;var selected=false;var childSelected;var childCount=this.childMenuViews.getLength();for(i=0;i<childCount;++i)
{childSelected=this.childMenuViews.get(i).updateSelection(location);selected=selected||childSelected;}
if(!selected)
{selected=selected||this.isSelected(location);}
$(this.menuDiv).toggleClass("menu_selected",selected);if(this.childMenuViews.getLength()>0)
{if(selected!==this.contentsVisible)
{$(this.contentsDiv)[selected?"slideDown":"slideUp"]("fast");this.contentsVisible=selected;}}
return selected;}});function GoMenuView()
{MenuView.call(this);}
GoMenuView.define(MenuView,{},{init:function(element,label,locationOrHash)
{this.location=(locationOrHash instanceof Location)?locationOrHash:Location.fromHash(locationOrHash);return MenuView.prototype.init.call(this,element,label,"#"+this.location.toHash());},isSelected:function(location)
{return location.match(this.location,false);}});function MenuBarView()
{View.call(this);}
MenuBarView.define(View,{},{init:function()
{this.menuViews=[];return View.prototype.init.apply(this,arguments);},renderView:function(element)
{View.prototype.renderView.call(this,element);this.attachApplication();},attachApplication:function()
{this.addResource(app.locationChanged.attach(this.applicationLocationChanged.bind(this)));},applicationLocationChanged:function(location)
{this.updateSelection(location);},updateSelection:function(location)
{var i;for(i=0;i<this.menuViews.length;++i)
{this.menuViews[i].updateSelection(location);}},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"menu_bar_view");},createView:function(klass,initParams)
{initParams.unshift(this.root);var view=new klass();view.init.apply(view,initParams);this.addChild(view);},createMenuView:function(label,href)
{var menuView=new MenuView().init(this.root,label,href);this.addChild(menuView);this.menuViews.push(menuView);},createGoMenuView:function(label,locationOrHash)
{var menuView=new GoMenuView().init(this.root,label,locationOrHash);this.addChild(menuView);this.menuViews.push(menuView);}});function StoreMenuView()
{View.call(this);}
StoreMenuView.define(View,{},{init:function(element,controller)
{this.applicationLocationChangedBinding=null;this.menuViews=[];this.controller=controller;return View.prototype.init.call(this,element);},render:function()
{View.prototype.render.call(this);this.attachApplication();},destroy:function()
{View.prototype.destroy.call(this);this.detachApplication();},attachApplication:function()
{this.applicationLocationChangedBinding=this.applicationLocationChanged.bind(this);Application.instance.locationChanged.attach(this.applicationLocationChangedBinding);},detachApplication:function()
{Application.instance.locationChanged.detach(this.applicationLocationChangedBinding);},applicationLocationChanged:function(location)
{this.updateSelection(location);},updateSelection:function(location)
{var i;for(i=0;i<this.menuViews.length;++i)
{this.menuViews[i].updateSelection(location);}},createControls:function()
{var i;var salesMenuSectionDiv;var otherMenuSectionDiv;var menuView;var b=new ElementBuilder();this.root=b.div(null,"store_menu_view");salesMenuSectionDiv=b.div(this.root,"menu_section first_menu_section");otherMenuSectionDiv=b.div(this.root,"menu_section");for(i=0;i<this.controller.sales.length;++i)
{menuView=new SaleMenuView().init(salesMenuSectionDiv,this.controller.sales[i]);this.menuViews.push(menuView);this.addChild(menuView);}
b.div(otherMenuSectionDiv);menuView=new GoMenuView().init(otherMenuSectionDiv,"Company","/store/page?about");this.menuViews.push(menuView);this.addChild(menuView);menuView.addChildMenuView(new GoMenuView().init(null,"About","/store/page?about"));menuView.addChildMenuView(new GoMenuView().init(null,"Contact","/store/page?contact"));menuView.addChildMenuView(new GoMenuView().init(null,"Privacy","/store/page?privacy"));}});function HomeView()
{View.call(this);}
HomeView.define(View,{},{initView:function(element,params)
{this.backgroundFixedFrameElement=params.backgroundFixedFrameElement;this.sales=params.sales;this.stories=params.stories;this.features=params.features;},destroyView:function()
{View.prototype.destroyView.call(this);$(this.backgroundFixedFrameElement).hide();},renderView:function(element)
{View.prototype.renderView.call(this,element);$(this.backgroundFixedFrameElement).show();},createControls:function()
{var shopDiv,journalDiv;var i,el;var sales=this.sales;var stories=this.stories;var features=this.features;var b=new ElementBuilder();this.root=b.div(null,"home_view");shopDiv=b.div(this.root,null,{id:"shop"});journalDiv=b.div(this.root,null,{id:"journal"});b.clearer(this.root);if((sales.length===0)&&(features.length===0))
{$(shopDiv).addClass("empty");}
for(i=0;i<features.length;++i)
{this.addChild(new HomeFeatureView().init(shopDiv,features[i],i===0));}
for(i=0;i<sales.length;++i)
{this.addChild(new HomeSaleView().init(shopDiv,sales[i],i===0&&features.length===0));}
for(i=0;i<stories.length;++i)
{this.addChild(new HomeStoryView().init(journalDiv,stories[i],i===0));}}});function HomeSaleView()
{View.call(this);}
HomeSaleView.define(View,{},{init:function(element,sale,isFirst)
{this.sale=sale;this.isFirst=isFirst;return View.prototype.init.call(this,element);},createControls:function()
{var b=new ElementBuilder();var headingsDiv;var headingSaleName;var el;var endsInDiv;var aboutDiv;var aboutA;var anchor;var saleHash;var startTimeEst;var sale=this.sale;saleHash="#/store/sale?"+sale.id.toString();var saleDiv=this.root=b.div(null,this.isFirst?"home_sale_view first_home_sale_view":"home_sale_view");headingsDiv=b.div(saleDiv,null,{id:"headings"});headingSaleName=b.div(headingsDiv,"sale_name");if(sale.hasStarted())
{b.a(headingSaleName,null,{href:saleHash,html:sale.name});}
else
{b.text(headingSaleName,sale.name);}
endsInDiv=b.div(headingsDiv,null,{id:"ends_in"});startTimeEst=new Date(sale.start_time_est);if(sale.hasStarted())
{this.addChild(new CountdownView().init(endsInDiv,{endsIn:sale.getCurrentEndsIn(),timer:app.timer,prefix:"Sale ends in ",expiredText:"Sale ended"}));}
else if(sale.startsTodayEst())
{b.text(endsInDiv,"Sale begins at "+
new Date(startTimeEst).friendlyTime()+" EST");}
else
{b.text(endsInDiv,"Sale begins on "+
(startTimeEst.getUTCMonth()+1).toString()+"/"+
startTimeEst.getUTCDate().toString());}
anchor=null;if(sale.hasStarted())
{anchor=b.a(saleDiv,null,{href:saleHash});}
b.img(anchor||saleDiv,null,{sale:sale,src:app.createAbsoluteAssetUrl(sale.image_url_315),alt:sale.name});aboutDiv=b.div(saleDiv,null,{id:"about_the_brand"});aboutA=b.a(aboutDiv,"clickable",{html:"About the Brand"});aboutA.onclick=this.aboutAOnClick.bind(this);this.vendorView=new HomeVendorView().init(saleDiv,sale.vendor);this.addChild(this.vendorView);},aboutAOnClick:function()
{this.vendorView.toggle();}});function HomeFeatureView()
{View.call(this);}
HomeFeatureView.define(View,{},{init:function(element,feature,isFirst)
{this.feature=feature;this.isFirst=isFirst;this.aboutVisible=false;return View.prototype.init.call(this,element);},createControls:function()
{var b=new ElementBuilder();var headingsDiv;var aboutADiv;var aboutA;var feature=this.feature;var featureDiv=this.root=b.div(null,this.isFirst?"home_feature_view first_home_feature_view":"home_feature_view");headingsDiv=b.div(featureDiv,null,{id:"headings"});if(feature.title){b.div(headingsDiv,null,{id:"title",html:feature.title});}
if(feature.subtitle){b.div(headingsDiv,null,{id:"subtitle",html:feature.subtitle});}
b.img(featureDiv,null,{src:app.createAbsoluteAssetUrl(feature.image_url_315),alt:feature.title});if(feature.about){aboutADiv=b.div(featureDiv,null,{id:"about_link"});aboutA=b.a(aboutADiv,"clickable",{html:"About"});aboutA.onclick=this.aboutAOnClick.bind(this);this.aboutDiv=b.div(featureDiv,null,{id:"about",html:feature.about});$(this.aboutDiv).hide();}},aboutAOnClick:function()
{this.aboutVisible=!this.aboutVisible;$(this.aboutDiv)[this.aboutVisible?"show":"hide"]("fast");}});function HomeStoryView()
{View.call(this);}
HomeStoryView.define(View,{},{init:function(element,story,isFirst)
{this.story=story;this.isFirst=isFirst;return View.prototype.init.call(this,element);},createControls:function()
{var b=new ElementBuilder();var headlineDiv;var anchor;var h2;var fullStoryDiv;var story=this.story;var storyDiv=this.root=b.div(null,this.isFirst?"home_story_view first_home_story_view":"home_story_view");var storyUrl="#/journal?story_id="+story.id;b.div(storyDiv,null,{id:"bar"});anchor=b.a(storyDiv,null,{href:storyUrl});b.img(anchor,null,{src:app.createAbsoluteAssetUrl(story.image_url_410),alt:story.title});b.clearer(storyDiv);headlineDiv=b.div(storyDiv,null,{id:"headline"});h2=b.h2(headlineDiv);b.a(h2,null,{html:story.title,href:storyUrl});b.div(headlineDiv,null,{id:"published_at",html:Formatters.longUTCDateFromTicks(story.published_at_est,{comma:false})});fullStoryDiv=b.div(headlineDiv,null,{id:"full_story"});b.a(fullStoryDiv,null,{html:"Full Story",href:storyUrl});if(story["abstract"]){b.div(storyDiv,null,{id:"abstract",html:story["abstract"]});}}});function HomeVendorView()
{View.call(this);}
HomeVendorView.define(View,{},{init:function(element,vendor)
{this.visible=false;this.vendor=vendor;return View.prototype.init.call(this,element);},toggle:function()
{this.visible?this.hide():this.show();},show:function()
{this.visible=true;$(this.root).slideDown("fast");},hide:function()
{this.visible=false;$(this.root).slideUp("fast");},createControls:function()
{var i;var b=new ElementBuilder();var vendor=this.vendor;var skus,sku,sale_sku;var publications;var section,content,subsection,subcontent;var skuA;var root=this.root=b.div(null,"home_vendor_view");$(root).hide();if(vendor.category){section=b.div(root,"section");b.div(section,"heading",{html:"Category"});content=b.div(section,"content",{html:vendor.category});}
skus=vendor.featured_skus;if(skus.length>0){section=b.div(root,"section");b.div(section,"heading",{html:"Top Sellers"});content=b.div(section,"subcontent");for(i=0;i<skus.length;++i){skuA=null;sku=skus[i];sale_sku=sku.current_sale_sku;if(sale_sku){skuA=b.a(content,null,{href:"#/store/sale?"+sale_sku.sale_id+"/sale_sku?"+sale_sku.id});}
b.text(skuA||content,sku.product.full_name);b.br(content);}}
if(vendor.celebrity_fans){section=b.div(root,"section");b.div(section,"heading",{html:"Celebrity Fans"});content=b.div(section,"content",{html:vendor.celebrity_fans});}
if(vendor.press_clippings.length>0)
{publications=vendor.press_clippings.collect(function(clipping){return clipping.publication;}).uniq().join(", ");section=b.div(root,"section");b.div(section,"heading",{html:"Press"});content=b.div(section,"content",{html:publications});}
if(vendor.story_abstract)
{section=b.div(root,"section");b.div(section,"heading",{html:"Brand Story"});b.div(section,"content",{html:vendor.story_abstract});}
section=b.div(root,"section",{id:"more_section"});b.a(section,null,{html:"More",href:"#/store/vendor?"+vendor.id.toString()});}});function VendorView()
{View.call(this);}
VendorView.define(View,{},{initView:function(element,params)
{this.vendor=params.vendor;},createControls:function()
{var i;var el;var section,heading,content;var pageHeaderDiv,saleTimeDiv,clippingDiv,imageA;var table,tbody,tr,td;var b=new ElementBuilder();var sale,skus,sku,sale_sku,clipping,fans,startDate;var vendor=this.vendor;var press_clippings=vendor.press_clippings;var root=this.root=b.div(null,"vendor_view");pageHeaderDiv=b.div(root,"page_header");b.div(pageHeaderDiv,"heading1",{html:vendor.name});if(vendor.featured_sale)
{sale=Sale.fromAttrs(vendor.featured_sale);saleTimeDiv=b.div(pageHeaderDiv,null,{id:"sale_time"});if(sale.hasStarted())
{this.addChild(new CountdownView().init(saleTimeDiv,{endsIn:sale.getCurrentEndsIn(),timer:app.timer,prefix:"Sale ends in ",expiredText:"Sale ended"}));}
else
{startDate=new Date(sale.start_time);b.text(saleTimeDiv,"Sale begins on "+
(startDate.getMonth()+1).toString()+"/"+
startDate.getDate().toString());}}
b.img(root,null,{id:"vendor_image",alt:vendor.name,src:app.createAbsoluteAssetUrl(vendor.image_url_450)});section=b.div(root,"section",{id:"vitals"});heading=b.div(section,"heading");b.h2(heading,"first",{html:"At a Glance"});content=b.div(section,"content");b.div(content,"clearer");this.textAttribute(content,"Category",vendor.category,b);this.textAttribute(content,"Year Founded",vendor.year_founded,b);this.textAttribute(content,"Founders",vendor.founders,b);this.textAttribute(content,"Based In",vendor.based_in,b);if(vendor.retail_price_range_min&&vendor.retail_price_range_max){var priceRange="$"+
Math.floor(vendor.retail_price_range_min/100).toString()+" - "+
Math.ceil(vendor.retail_price_range_max/100).toString();this.textAttribute(content,"Retail Price Range",priceRange,b);}
this.textAttribute(content,"Point of Difference",vendor.point_of_difference,b);skus=vendor.featured_skus;if(skus.length>0){el=b.div();for(i=0;i<skus.length;++i){skuA=null;sku=skus[i];sale_sku=sku.current_sale_sku;if(sale_sku){skuA=b.a(el,null,{href:"#/store/sale?"+sale_sku.sale_id+"/sale_sku?"+sale_sku.id});}
b.text(skuA||el,sku.product.full_name);b.br(el);}
this.attribute(content,"Top Sellers",el,b);}
this.listAttribute(content,"Celebrity Fans",vendor.celebrity_fans,b);if(vendor.testimonials_html){el=b.div(null,null,{innerHTML:vendor.testimonials_html});this.attribute(content,"Testimonials",el,b);}
this.listAttribute(content,"Where to Buy",vendor.where_to_buy,b);if(vendor.website_url){el=b.a(null,null,{html:vendor.website_url,href:vendor.website_url});this.attribute(content,"Website",el,b);}
if(press_clippings.length>0)
{section=b.div(root,"section");heading=b.div(section,"heading");b.h2(heading,"first",{html:"Press"});content=b.div(section,"content");for(i=0;i<press_clippings.length;++i)
{clipping=press_clippings[i];clippingDiv=b.div(content,"press_clipping");table=b.table(clippingDiv,"images");tbody=b.tbody(table);tr=b.tr(tbody);td=b.td(tr,"first");b.img(td,null,{alt:clipping.publication,src:app.createAbsoluteAssetUrl(clipping.image_url_215)});sku=clipping.sku;if(sku&&sku.view)
{sale_sku=sku.current_sale_sku;imageA=null;td=b.td(tr);if(sale_sku){imageA=b.a(td,null,{href:"#/store/sale?"+sale_sku.sale_id+"/sale_sku?"+sale_sku.id});}
b.img(imageA||td,null,{alt:clipping.sku.full_name,src:app.createAbsoluteAssetUrl(clipping.sku.view.image_url_215)});}}}
if(vendor.story_html)
{section=b.div(root,"section");heading=b.div(section,"heading");b.h2(heading,"first",{html:"Brand Story"});content=b.div(section,"content",{innerHTML:vendor.story_html});}},attribute:function(parent,name,valueElement,builder)
{parent=parent||null;var b;var valueDiv;var attributeDiv=null;b=builder||new ElementBuilder;attributeDiv=b.div(parent,"attribute");b.div(attributeDiv,null,{id:"name",html:name});valueDiv=b.div(attributeDiv,null,{id:"value"});valueDiv.appendChild(valueElement);return attributeDiv;},listAttribute:function(parent,name,value,builder)
{var items;if(value)
{var b=builder||new ElementBuilder();items=value.splitAndTrim(",");el=b.div();for(i=0;i<items.length;++i)
{b.text(el,items[i]);b.br(el);}
return this.attribute(parent,name,el,b);}
return null;},textAttribute:function(parent,name,value,builder)
{if(value)
{var b=builder||new ElementBuilder();return this.attribute(parent,name,b.text(null,value),builder);}
return null;}});function InviteView()
{View.call(this);}
InviteView.define(View,{},{createControls:function()
{var formDiv;var formView;var b=new ElementBuilder();var root=this.root=b.div(null,"invite_view");b.h1(root,"first",{html:"Invite"});b.div(root,"instructions",{innerHTML:"Invite friends to join Market for Drama and receive a\
     $10 credit when they make their first purchase."});b.p(root,null,{innerHTML:"Enter one email per line or separate with commas or semicolons.<br/><br/>"});formDiv=b.div(root);formView=this.formView=new FormView().init(formDiv);this.addChild(formView);formView.textArea("emails","");formView.action("Send","send_invitations",{important:true});},setFocus:function()
{this.formView.focus();}});function AccountView()
{View.call(this);}
AccountView.define(View,{},{initView:function(element,params)
{this.member=params.member;},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"account_view");var drawerView;var drawersView=new DrawersView().init(root);this.addChild(drawersView);this.accountInfoView=new AccountInfoView().init(null,{member:this.member});drawerView=drawersView.createDrawer("Account Information");drawerView.addContentChild(this.accountInfoView);drawerView=drawersView.createDrawer("Account History");drawerView.addContentChild(new AccountHistoryView().init(null,{transactions:this.member.transactions}));drawerView=drawersView.createDrawer("Invitations");drawerView.addContentChild(new AccountInvitationsView().init(null,{invitations:this.member.sent_invitations}));}});function AccountInfoView()
{View.call(this);}
AccountInfoView.define(View,{},{initView:function(element,params)
{this.member=params.member;},showAttrs:function()
{this.attrsView.toggle(true);this.formView.toggle(false);this.changePasswordFormView.toggle(false);},showForm:function()
{this.attrsView.toggle(false);this.formView.toggle(true);this.changePasswordFormView.toggle(false);},showChangePasswordForm:function()
{this.attrsView.toggle(false);this.formView.toggle(false);this.changePasswordFormView.toggle(true);},createControls:function()
{var b=new ElementBuilder();var member=this.member;var root=this.root=b.div(null,"account_info_view");var formView=this.formView=new FormView().init(root);this.addChild(formView);formView.text("first_name",member.value("first_name"),"First");formView.text("last_name",member.value("last_name"),"Last");formView.text("email",member.value("email"),"Email");formView.text("postal_code",member.value("postal_code"),"Zip");formView.date("birthday",member.value("birthday"),"Birthday");formView.action("Update","update_account_info",{important:true});formView.action("Cancel","cancel_edit_account_info");var changePasswordFormView=this.changePasswordFormView=new FormView().init(root);this.addChild(changePasswordFormView);changePasswordFormView.password("password","","New Password");changePasswordFormView.password("password_confirm","","Confirm New Password");changePasswordFormView.action("Update","update_password",{important:true});changePasswordFormView.action("Cancel","cancel_change_password");var attrsView=this.attrsView=new AttributesTableView().init(root);this.addChild(attrsView);attrsView.add(member.value("full_name"),"Name");attrsView.add(member.value("email"),"Email");attrsView.add(member.value("postal_code"),"Zip");attrsView.add(member.value("birthday"),"Birthday",Formatters.longUTCDateFromTicks);attrsView.add(member.value("created_at"),"Member Since",Formatters.longUTCMonthAndYearFromTicks);attrsView.add(member.value("balance"),"Account Balance",Formatters.money);attrsView.action("Edit","edit_account_info");attrsView.action("Change Password","change_password");this.showAttrs();}});function AccountHistoryView()
{View.call(this);}
AccountHistoryView.define(View,{},{initView:function(element,params)
{this.transactions=params.transactions;},createControls:function()
{var formatType=function(type)
{switch(type)
{case"Purchase":return"Order";case"CreditCardPayment":return"Payment";case"InvitationCredit":return"Credit";default:return type;}};var tx;var i;var txDiv,txDetailsLinkDiv,txDetailsLink,txDetailsDiv;var orderDetailsView;var table,thead,tbody,row;var b=new ElementBuilder();var root=this.root=b.div(null,"account_history_view");table=b.div(root,"table1",{id:"transactions"});thead=b.div(table,"head");tbody=b.div(table,"body");row=b.div(thead,"row");b.div(row,"cell date_cell",{html:"Date"});b.div(row,"cell type_cell",{html:"Transaction"});b.div(row,"cell description_cell",{html:"Description"});b.div(row,"cell right_cell numeric_cell amount_cell",{html:"Amount"});b.clearer(row);for(i=0;i<this.transactions.length;++i)
{tx=this.transactions[i];txDiv=b.div(tbody,"row transaction");b.div(txDiv,"cell date_cell",{html:formatDateShort(new Date(tx.created_at))});b.div(txDiv,"cell type_cell",{html:formatType(tx.type)});b.div(txDiv,"cell description_cell fill",{html:tx.summary});b.div(txDiv,"cell right_cell numeric_cell amount_cell",{html:formatPrice(tx.amount)});b.clearer(txDiv);if(tx.type==="Purchase")
{txDetailsLinkDiv=b.div(txDiv,null,{id:"details_link"});txDetailsLink=b.a(txDetailsLinkDiv,"clickable",{html:"Details"});txDetailsDiv=b.div(txDiv,null,{id:"details"});$(txDetailsDiv).hide();txDetailsLink.onclick=function(details){var visible=false;return function(){$(details)[visible?"slideUp":"slideDown"]("fast");visible=!visible;};}(txDetailsDiv);orderDetailsView=new AccountHistoryOrderDetailsView().init(txDetailsDiv,{order:new Order().init(tx.order)});this.addChild(orderDetailsView);}}}});function AccountHistoryOrderDetailsView()
{View.call(this);}
AccountHistoryOrderDetailsView.define(View,{},{initView:function(element,params)
{this.order=params.order;},createControls:function()
{var b=new ElementBuilder();var orderLineTableView,orderTotalsView;var root=this.root=b.div(null,"account_history_order_details_view");var linesDiv=b.div(root,null,{id:"lines_frame"});var totalsDiv=b.div(root,null,{id:"totals_frame"});orderLineTableView=new OrderLineTableView().init(linesDiv,{order:this.order,allowChanges:false,showExpiresIn:false});this.addChild(orderLineTableView);orderTotalsView=new OrderTotalsView().init(totalsDiv,{order:this.order,hide:["subtotalWithRetailPrice"]});this.addChild(orderTotalsView);}});function AccountInvitationsView()
{View.call(this);}
AccountInvitationsView.define(View,{},{initView:function(element,params)
{this.invitations=params.invitations;},createControls:function()
{var table,thead,tbody,tr,th,td;var invitation;var i;var b=new ElementBuilder();var root=this.root=b.div(null,"account_invitations_view");table=b.table(root,"style1");thead=b.thead(table);tbody=b.tbody(table);tr=b.tr(thead);b.th(tr,null,{html:"Sent On"});b.th(tr,null,{html:"Recepient"});b.th(tr,null,{html:"Accepted"});b.th(tr,"right",{html:"Credit Earned"});for(i=0;i<this.invitations.length;++i)
{invitation=this.invitations[i];tr=b.tr(tbody);b.td(tr,"date_cell",{html:formatDateShort(new Date(invitation.created_at))});b.td(tr,"recipient_cell fill",{html:invitation.recipient_email});b.td(tr,"accepted_cell right_cell",{html:formatYesNo(invitation["accepted?"])});b.td(tr,"accepted_cell right",{html:formatYesNo(invitation["credit_given?"])});}}});function CartDetailsView()
{View.call(this);}
CartDetailsView.define(View,{},{init:function(element,controller)
{this.controller=controller;return View.prototype.init.call(this,element);},renderView:function(element)
{this.update(false);this.attachCart();View.prototype.renderView.apply(this,arguments);},attachCart:function()
{var cart=this.controller.cart;this.addResource(cart.updated.attach(this.cartUpdated.bind(this)));this.addResource(cart.lineExpired.attach(this.cartLineExpired.bind(this)));},cartUpdated:function()
{this.update(true);},cartLineExpired:function()
{this.update(true);},createControls:function()
{this.root=document.createElement("div");this.root.id="cart_details";this.itemCountLabel=document.createElement("div");this.root.appendChild(this.itemCountLabel);this.countdown=new CountdownView().init(this.root,{endsAt:new Date(),timer:app.timer,showDot:true,warningMsecs:300000,expiredText:null});this.addChild(this.countdown);},update:function(animate)
{if(animate===undefined)
animate=false;var cart=this.controller.cart;if((cart===null)||(cart.isEmpty()))
{if(!this.hidden)
{this.hidden=true;if(animate)$(this.root).slideUp("fast");else $(this.root).hide();}}
else
{var quantity=cart.getTotalQuantity();this.itemCountLabel.innerHTML=quantity.toString()+" "+
((quantity==1)?"Item":"Items");var soonest=cart.getOrderLineWithSoonestExpiration();this.countdown.setEndsIn(soonest.getCurrentExpiresIn());if(this.hidden)
{this.hidden=false;if(animate)$(this.root).slideDown("fast");else $(this.root).show();}}}});function SaleMenuView()
{View.call(this);}
SaleMenuView.define(View,{},{init:function(element,sale)
{this.sale=sale;return View.prototype.init.call(this,element);},updateSelection:function(location)
{this.menuView.updateSelection(location);},createControls:function()
{var i;var menuView;var b=new ElementBuilder();var sale=this.sale;var startDate=new Date(sale.start_time);var root=this.root=b.div(null,"sales_menu_view");var url=sale.hasStarted()?"/store/sale?"+sale.id.toString():"/store/vendor?"+sale.vendor.id.toString();this.menuView=menuView=new GoMenuView().init(root,sale.short_name||sale.name,url);this.addChild(menuView);var sublabel=b.div(menuView.contentsDiv,"sublabel");if(sale.hasStarted())
{this.addChild(new CountdownView().init(sublabel,{timer:app.timer,endsIn:sale.getCurrentEndsIn()}));}
else
{b.text(sublabel,(startDate.getMonth()+1).toString()+"/"+
startDate.getDate().toString());}
menuView.addChildMenuView(new GoMenuView().init(null,"About","/store/vendor?"+sale.vendor.id.toString()));if(sale.hasStarted())
{menuView.addChildMenuView(new GoMenuView().init(null,"All Products","/store/sale?"+sale.id.toString()));if(sale.has_top_sellers){menuView.addChildMenuView(new GoMenuView().init(null,"Top Sellers","/store/sale?"+sale.id.toString()+"&top_sellers=1"));}
if(sale.has_mfd_picks){menuView.addChildMenuView(new GoMenuView().init(null,"MFD Picks","/store/sale?"+sale.id.toString()+"&mfd_picks=1"));}
for(i=0;i<sale.categories.length;++i)
{category=sale.categories[i];menuView.addChildMenuView(new GoMenuView().init(null,category.name,"/store/sale?"+sale.id.toString()+"&sale_category="+category.id.toString()));}}}});function BigSaleImageView()
{View.apply(this,arguments);}
BigSaleImageView.define(View,{},{initView:function(element,params)
{this.controller=params.controller;this.sale=params.sale;this.saleSku=params.saleSku||null;},getSaleSkuHash:function(saleSku)
{var location=this.controller.getLocation().appendHash("sale_sku?"+saleSku.id.toString());return"#"+location.toHash();},createControls:function()
{var b=new ElementBuilder();var root=this.root=b.div(null,"big_sale_image_view");var anchor;if(this.saleSku){anchor=b.a(root,null,{href:this.getSaleSkuHash(this.saleSku)});}
b.img(anchor||root,null,{src:this.sale.big_image_url_430,alt:this.saleSku?this.saleSku.sku.full_name:""});}});function SaleSkuView()
{View.apply(this,arguments);}
SaleSkuView.define(View,{},{initView:function(element,params)
{this.saleSku=params.saleSku;this.controller=params.controller;this.cartInfoView=null;this.moreInfoVisible=false;},createControls:function()
{var i;var saleSku=this.saleSku;var sku=saleSku.sku;var product=sku.product;var member;var moreInfoFrameDiv,moreInfoDiv,imagesDiv,infoDiv,cartDiv;var leftDiv,rightDiv;var viewsDiv,thumbsDiv;var nameDiv,pricesDiv;var tab,tabGroup;var thumbGrid,thumbCell,imageDiv,img,cell,thumbDiv,aligner;var familyDiv,membersDiv,shadeGrid,shadeCell,shadeA,shadeDiv;var b=new ElementBuilder();var root=this.root=b.div(null,"sale_sku_view");moreInfoFrameDiv=this.moreInfoFrameDiv=b.div(root,null,{id:"more_info_frame"});imagesDiv=b.div(root,null,{id:"images"});infoDiv=b.div(root,null,{id:"info"});moreInfoLinksDiv=b.div(root,null,{id:"more_info_links"});leftDiv=b.div(infoDiv,null,{id:"left"});rightDiv=b.div(infoDiv,null,{id:"right"});b.div(infoDiv,"clearer");viewsDiv=b.div(leftDiv,null,{id:"views"});thumbsDiv=b.div(viewsDiv,null,{id:"thumbs"});b.span(viewsDiv,"small",{html:"Views"});familyDiv=b.div(leftDiv,null,{id:"family"});membersDiv=b.div(familyDiv,null,{id:"members"});if(saleSku.family.length>1){if(sku.shades){shadeGrid=new Grid((saleSku.family.length===4)?2:3);shadeGrid.render(membersDiv);for(i=0;i<saleSku.family.length;++i){member=saleSku.family[i];if(member.sku.shades.length>0){shadeCell=shadeGrid.createCell();shadeA=b.a(shadeCell,null,{href:this.getFamilyMemberSaleSkuHash(member)});shadeDiv=b.div(shadeA,"shade");shadeDiv.style.backgroundColor=member.sku.shades[0];}}
b.span(familyDiv,"small",{html:"Shades"});}else{for(i=0;i<saleSku.family.length;++i){member=saleSku.family[i];b.a(membersDiv,null,{html:member.sku.name||"No Name",href:this.getFamilyMemberSaleSkuHash(member)});b.br(membersDiv);}
b.span(familyDiv,"small",{html:"Options"});}}
nameDiv=b.div(rightDiv,null,{id:"name"});b.span(nameDiv,"big",{html:sku.product.name});if(sku.product.subname){b.br(nameDiv);b.text(nameDiv,sku.product.subname);}
if(sku.name){b.br(nameDiv);b.text(nameDiv,sku.name);}
pricesDiv=b.div(rightDiv,null,{id:"prices"});b.span(pricesDiv,"cancelled",{html:formatPrice(sku.retail_price)});b.span(pricesDiv,"biggest",{id:"price",html:formatPrice(sku.price)});cartDiv=b.div(rightDiv);this.cartInfoView=new SaleSkuCartInfoView().init(cartDiv,{controller:this.controller,saleSku:this.saleSku});this.addChild(this.cartInfoView);this.moreInfoLinkSpan=b.span(moreInfoLinksDiv,"action",{id:"more_info_link",html:"More Information",onclick:this.moreInfoSpanOnClick.bind(this)});moreInfoDiv=this.moreInfoDiv=b.div(moreInfoFrameDiv,null,{id:"more_info"});if(product.description_html){b.h1(moreInfoDiv,"",{html:"Description"});b.div(moreInfoDiv,null,{innerHTML:product.description_html});}
if(product.application_html){b.h1(moreInfoDiv,"",{html:"Application"});b.div(moreInfoDiv,null,{innerHTML:product.application_html});}
b.h1(moreInfoDiv,"",{html:"Shipping"});b.div(moreInfoDiv,null,{html:"Ships in 3-5 business days.\
    Please allow an additional 3-5 business days for transit."});b.h1(moreInfoDiv,"",{html:"Returns"});b.div(moreInfoDiv,null,{html:"All items are FINAL SALE. No\
    returns, refunds or exchanges."});if(product.ingredients_html){b.h1(moreInfoDiv,"",{html:"Ingredients"});b.div(moreInfoDiv,null,{innerHTML:product.ingredients_html});}
tabGroup=new TabGroup();thumbGrid=new Grid((sku.views.length===4)?2:3);thumbGrid.render(thumbsDiv);for(i=0;i<sku.views.length;++i)
{skuView=sku.views[i];if(skuView.image_url_30&&skuView.image_url_320&&skuView.image_url_1600)
{imageDiv=b.div(imagesDiv,"sku_view_view_frame");this.addChild(new SkuViewView().init(imageDiv,{skuView:skuView,fixedFrameElement:this.element}));thumbCell=thumbGrid.createCell();thumbDiv=b.div(thumbCell,"view clickable");img=b.img(null,null,{src:app.createAbsoluteAssetUrl(skuView.image_url_30),alt:sku.full_name});this.addChild(new BottomAlignmentView().init(thumbDiv,{content:img}));tab=new Tab(thumbDiv,imageDiv);tabGroup.addTab(tab);this.addResource(tab.labelClick.attach(function(){this.toggleMoreInfoVisibility(false);}.bind(this)));}}
b.div(thumbsDiv,"clearer");tabGroup.selectFirstTab();},getFamilyMemberSaleSkuHash:function(saleSku)
{var location=this.controller.getLocation().pop().appendHash("sale_sku?"+saleSku.id.toString());return"#"+location.toHash();},moreInfoSpanOnClick:function()
{this.toggleMoreInfoVisibility();},toggleMoreInfoVisibility:function(visible)
{if((visible!==undefined)&&(visible===this.moreInfoVisible)){return;}
visible=this.moreInfoVisible=!this.moreInfoVisible;$(this.moreInfoLinkSpan).toggleClass("selected",visible);if(visible)
{this.moreInfoFrameDiv.style.zIndex=2;$(this.moreInfoDiv).animate({left:"0px"},200,"swing");}
else
{$(this.moreInfoDiv).animate({left:"320px"},200,"swing",function(){this.moreInfoFrameDiv.style.zIndex=0;}.bind(this));}}});function SkuViewView()
{View.apply(this,arguments);}
SkuViewView.define(View,{ZOOM_FACTOR:5},{initView:function(element,params)
{this.skuView=params.skuView;this.fixedFrameElement=params.fixedFrameElement;this.zooming=false;this.zoomImageLoaded=false;},destroyView:function()
{View.prototype.destroyView.apply(this,arguments);if(this.zoomViewport){this.zoomViewport.parentNode.removeChild(this.zoomViewport);}},createControls:function()
{var skuView=this.skuView;var b=new ElementBuilder();var root=this.root=b.div(null,"sku_view_view");this.zoomInInstructionDiv=b.div(root,"zoom_instruction",{html:"Click to zoom in"});$(this.zoomInInstructionDiv).hide();this.zoomOutInstructionDiv=b.div(root,"zoom_instruction",{html:"Click to zoom out"});$(this.zoomOutInstructionDiv).hide();var imageDiv=b.div(root,null,{id:"image"});var img=this.img=b.img(null,null,{src:app.createAbsoluteAssetUrl(skuView.image_url_320)});this.addChild(new BottomAlignmentView().init(imageDiv,{content:img}));this.zoomBoxDiv=b.div(root,null,{id:"zoom_box"});this.zoomBoxDiv.width=0;this.zoomBoxDiv.height=0;$(this.zoomBoxDiv).hide();var mouseEventSinkDiv=b.div(root,null,{id:"mouse_event_sink"});mouseEventSinkDiv.style.backgroundImage="url('"+
app.assetUrl("images/transparent.gif")+"')";var zoomViewport=this.zoomViewport=b.div(this.fixedFrameElement,"sku_view_zoom_viewport");$(zoomViewport).hide();this.addResource(app.viewport.resized.attach(this.appViewportOnResized.bind(this)));this.resizeZoomViewport();this.resizeZoomBox();this.zoomImg=b.img(zoomViewport);$(this.zoomImg).hide();this.zoomImgLow=b.img(zoomViewport,null,{src:app.createAbsoluteAssetUrl(skuView.image_url_1600_low)});$(mouseEventSinkDiv).click(this.mouseEventSinkDivOnClick.bind(this));$(mouseEventSinkDiv).mousemove(this.mouseEventSinkDivOnMouseMove.bind(this));$(mouseEventSinkDiv).mouseenter(this.mouseEventSinkDivOnMouseEnter.bind(this));$(mouseEventSinkDiv).mouseleave(this.mouseEventSinkDivOnMouseLeave.bind(this));},setZooming:function(zooming)
{this.zooming=zooming;$(this.zoomViewport).toggle(zooming);$(this.zoomBoxDiv).toggle(zooming);if(zooming&&!this.zoomImageLoaded){this.loadZoomImage();}},loadZoomImage:function()
{var src=app.createAbsoluteAssetUrl(this.skuView.image_url_1600);new ImageLoader().init(src).load(function(){this.zoomImageLoaded=true;this.zoomImg.src=src;$(this.zoomImgLow).fadeOut(500);$(this.zoomImg).fadeIn(500);}.bind(this),function(){}.bind(this));},showInstruction:function(zooming)
{$(this.zoomInInstructionDiv).toggle(!zooming);$(this.zoomOutInstructionDiv).toggle(zooming);},hideInstructions:function()
{$(this.zoomInInstructionDiv).hide();$(this.zoomOutInstructionDiv).hide();},resizeZoomViewport:function()
{var w=this.zoomViewport.width=430;var h=this.zoomViewport.height=app.viewport.height;this.zoomViewport.style.width=w.toString()+"px";this.zoomViewport.style.height=h.toString()+"px";},resizeZoomBox:function()
{var s=SkuViewView.ZOOM_FACTOR;var wv=this.zoomViewport.width;var hv=this.zoomViewport.height;var w=this.zoomBoxDiv.width=Math.floor(wv/s);var h=this.zoomBoxDiv.height=Math.floor(hv/s);this.zoomBoxDiv.style.width=w.toString()+"px";this.zoomBoxDiv.style.height=h.toString()+"px";},positionZoomImg:function(mousePageX,mousePageY)
{var s=SkuViewView.ZOOM_FACTOR;var wv=this.zoomViewport.width;var hv=this.zoomViewport.height;var imgOffset=$(this.img).offset();var a=mousePageX-imgOffset.left;var b=mousePageY-imgOffset.top;var dx=-Math.floor(s*a-wv/2);var dy=-Math.floor(s*b-hv/2);this.zoomImg.style.left=this.zoomImgLow.style.left=dx.toString()+"px";this.zoomImg.style.top=this.zoomImgLow.style.top=dy.toString()+"px";},positionZoomBox:function(mousePageX,mousePageY)
{var viewOffset=$(this.root).offset();var a_view=mousePageX-viewOffset.left;var b_view=mousePageY-viewOffset.top;this.zoomBoxDiv.style.left=Math.floor(a_view-this.zoomBoxDiv.width/2).toString()+"px";this.zoomBoxDiv.style.top=Math.floor(b_view-this.zoomBoxDiv.height/2).toString()+"px";},appViewportOnResized:function()
{this.resizeZoomViewport();this.resizeZoomBox();},mouseEventSinkDivOnClick:function(event)
{this.positionZoomImg(event.pageX,event.pageY);this.positionZoomBox(event.pageX,event.pageY);this.showInstruction(!this.zooming);this.setZooming(!this.zooming);},mouseEventSinkDivOnMouseEnter:function(event)
{this.showInstruction(false);},mouseEventSinkDivOnMouseLeave:function(event)
{this.hideInstructions();this.setZooming(false);},mouseEventSinkDivOnMouseMove:function(event)
{if(this.zooming)
{this.positionZoomImg(event.pageX,event.pageY);this.positionZoomBox(event.pageX,event.pageY);}}});function SaleSkuListView()
{View.apply(this,arguments);}
SaleSkuListView.define(View,{},{initView:function(element,params)
{this.listItemViews=[];this.saleSkus=params.saleSkus;this.controller=params.controller;},createControls:function()
{var i;var grid;var listItemView;var b=new ElementBuilder();var root=this.root=b.div(null,"sale_sku_list_view");grid=new Grid(2);grid.render(root);for(i=0;i<this.saleSkus.length;++i){listItemView=new SaleSkuListItemView().init(grid.createCell(),{saleSku:this.saleSkus[i],controller:this.controller});this.listItemViews.push(listItemView);this.addChild(listItemView);}}});function SaleSkuListItemView()
{View.apply(this,arguments);}
SaleSkuListItemView.define(View,{},{init:function(element,params)
{View.prototype.init.apply(this,arguments);this.addResource(this.saleSku.soldOutChanged.attach(this.saleSkuSoldOutChanged.bind(this)));return this;},initView:function(element,params)
{this.saleSku=params.saleSku;this.controller=params.controller;},getSaleSkuHash:function(saleSku)
{var location=this.controller.getLocation().appendHash("sale_sku?"+saleSku.id.toString());return"#"+location.toHash();},saleSkuSoldOutChanged:function()
{this.updateSoldOut();},updateSoldOut:function()
{var method=this.saleSku.sold_out?"show":"hide";$(this.soldOutLineDiv)[method]();},createControls:function()
{var i;var imageDiv,infoDiv,anchor,pricesDiv,soldOutLineDiv;var table,tbody,tr,td;var saleSku=this.saleSku;var sku=saleSku.sku;var b=new ElementBuilder();var root=this.root=b.div(null,"sale_sku_list_item_view");imageDiv=b.div(root,null,{id:"image"});infoDiv=b.div(root,"info");soldOutLineDiv=this.soldOutLineDiv=b.div(imageDiv,null,{id:"sold_out_line"});anchor=b.a(soldOutLineDiv,null,{href:this.getSaleSkuHash(saleSku)});b.img(anchor,null,{src:app.assetUrl("images/sold_out_line.png"),alt:"Sold out"});this.updateSoldOut();table=b.table(imageDiv,"image");tbody=b.tbody(table);tr=b.tr(tbody);td=b.td(tr);if((sku.views.length>0)&&(sku.views[0].image_url_205))
{anchor=b.a(td,null,{href:this.getSaleSkuHash(saleSku)});b.img(anchor,null,{src:app.createAbsoluteAssetUrl(sku.views[0].image_url_205)});}
anchor=b.a(infoDiv,null,{href:this.getSaleSkuHash(saleSku)});if(sku.product.name){b.text(anchor,sku.product.name);b.br(anchor);}
if(sku.product.subname){b.text(anchor,sku.product.subname);b.br(anchor);}
if(sku.name&&sku["siblings?"]){b.text(anchor,sku.name);}
pricesDiv=b.div(infoDiv,"prices");b.span(pricesDiv,"cancelled",{html:formatPrice(sku.retail_price)});b.span(pricesDiv,"big",{id:"price",html:formatPrice(sku.price)});}});function SaleSkuCartInfoView()
{View.apply(this,arguments);}
SaleSkuCartInfoView.define(View,{},{init:function(element,params)
{View.prototype.init.apply(this,arguments);this.addResource(this.saleSku.soldOutChanged.attach(this.saleSkuSoldOutChanged.bind(this)));return this;},initView:function(element,params)
{this.controller=params.controller;this.saleSku=params.saleSku;this.changingQuantity=false;this.attachedLine=null;this.lineExpiredBinding=null;},renderView:function()
{View.prototype.renderView.apply(this,arguments);this.update();},destroy:function()
{this.detachLine();this.element.removeChild(this.root);},attachLine:function(line)
{this.detachLine();this.attachedLine=line;this.lineExpiredBinding=this.lineExpired.bind(this);line.expired.attach(this.lineExpiredBinding);},detachLine:function()
{if(this.attachedLine!==null)
{this.attachedLine.expired.detach(this.lineExpiredBinding);this.attachedLine=null;this.lineExpiredBinding=null;}},lineExpired:function()
{this.changingQuantity=false;this.update(true);},getLine:function()
{return this.getCart().getOrderLineBySaleSku(this.saleSku);},getCart:function()
{return this.controller.insideRoot().cart;},saleSkuSoldOutChanged:function()
{this.updateSoldOut();},updateSoldOut:function()
{$(this.addToCartDiv).toggle(!this.saleSku.sold_out);$(this.soldOutDiv).toggle(this.saleSku.sold_out);},update:function(animate)
{animate=animate||false;var line=this.getLine();this.updateSoldOut();if(null!==line)
{this.attachLine(line);this.quantitySpan.innerHTML=line.quantity.toString();this.quantityInput.value=line.quantity.toString();$(this.quantitySpan).toggle(!this.changingQuantity);$(this.changeQuantitySpan).toggle(!this.changingQuantity);$(this.quantityInput).toggle(this.changingQuantity);$(this.updateQuantitySpan).toggle(this.changingQuantity);if(animate)
{$(this.notInCartDiv).slideUp("fast",function(){$(this.inCartDiv).slideDown("fast");}.bind(this));}
else
{$(this.inCartDiv).show();$(this.notInCartDiv).hide();}}
else
{this.detachLine();if(animate)
{$(this.inCartDiv).slideUp("fast",function(){$(this.notInCartDiv).slideDown("fast");}.bind(this));}else{$(this.inCartDiv).hide();$(this.notInCartDiv).show();}}},createControls:function()
{var el;var b=new ElementBuilder();var root=this.root=b.div(null,"sale_sku_cart_info_view");var inCartDiv=this.inCartDiv=b.div(root);var notInCartDiv=this.notInCartDiv=b.div(root);var addToCartDiv=this.addToCartDiv=b.div(notInCartDiv);b.span(addToCartDiv,"action",{html:"Add to Cart",onclick:this.addToCartSpanOnClick.bind(this)});var soldOutDiv=this.soldOutDiv=b.div(notInCartDiv,null,{id:"sold_out"});b.text(soldOutDiv,"Sold Out");this.quantitySpan=b.span(inCartDiv);var quantityInput=this.quantityInput=b.input(inCartDiv,null,{id:"quantity",type:"text"});$(quantityInput).keypress(this.quantityInputKeyPress.bind(this));b.text(inCartDiv," in cart");this.changeQuantitySpan=b.span(inCartDiv,"action",{id:"change_quantity",html:"Change",onclick:this.changeQuantitySpanOnClick.bind(this)});this.updateQuantitySpan=b.span(inCartDiv,"action",{id:"update_quantity",html:"Update",onclick:this.updateQuantitySpanOnClick.bind(this)});},addToCartSpanOnClick:function(event)
{new Command("add_to_cart",{saleSku:this.saleSku}).raise(this);},quantityInputKeyPress:function(event)
{if(event.which===13)
{this.raiseChangeQuantityCommand();return true;}},updateQuantitySpanOnClick:function(event)
{this.raiseChangeQuantityCommand();},changeQuantitySpanOnClick:function(event)
{this.changingQuantity=true;this.update();$(this.quantityInput).focus().select();},raiseChangeQuantityCommand:function()
{var quantity=parseInt(this.quantityInput.value,10);if(isNaN(quantity))
{window.alert("Enter a number");}
else
{new Command("change_quantity",{saleSku:this.saleSku,quantity:quantity}).raise(this);}}});function CartView()
{View.call(this);}
CartView.define(View,{},{initView:function(element,params)
{this.cart=params.cart;},updateView:function()
{var empty=this.cart.isEmpty();var hasPromotion=this.cart.hasPromotion();var promotion;$(this.emptyCartDiv).toggle(empty);$(this.fullCartDiv).toggle(!empty);$(this.applyPromoCodeDiv).toggle(!hasPromotion);$(this.removePromoCodeDiv).toggle(hasPromotion);if(hasPromotion){promotion=this.cart.promotions[0];this.promoCodeSpan.innerHTML=h(promotion.code+" ("+promotion.description+")");}else{this.promoCodeSpan.innerHTML="";}},createControls:function()
{var i;var cart=this.cart;var actionDiv;var emptyCartActionsDiv;var table,tbody,tr,td;var promoCodeDiv,applyPromoCodeDiv,removePromoCodeDiv,promoCodeInput;var b=new ElementBuilder(document);var root=this.root=b.div(null,"cart_view");var emptyCartDiv=this.emptyCartDiv=b.div(root,null,{id:"empty"});var fullCartDiv=this.fullCartDiv=b.div(root);b.h1(emptyCartDiv,"first",{html:"Cart"});b.text(emptyCartDiv,"Your cart is empty");emptyCartActionsDiv=b.div(emptyCartDiv,"checkout_actions");actionDiv=b.div(emptyCartActionsDiv,"action important_action");b.a(actionDiv,null,{html:"Return to Shop",href:"#/store"});var orderLinesTableDiv=b.div(fullCartDiv);var footerDiv=b.div(fullCartDiv,"checkout_footer");var actionsDiv=b.div(fullCartDiv,"checkout_actions");this.addChild(new OrderLineTableView().init(orderLinesTableDiv,{order:this.cart,allowChanges:true}));promoCodeDiv=b.div(footerDiv,null,{id:"promo_code"});applyPromoCodeDiv=this.applyPromoCodeDiv=b.div(promoCodeDiv);removePromoCodeDiv=this.removePromoCodeDiv=b.div(promoCodeDiv);b.text(applyPromoCodeDiv,"Promo Code: ");promoCodeInput=this.promoCodeInput=b.input(applyPromoCodeDiv,null,{id:"promo_code_input",type:"text"});$(promoCodeInput).keypress(this.promoCodeInputKeyPress.bind(this));b.br(applyPromoCodeDiv);b.span(applyPromoCodeDiv,"action",{html:"Apply",onclick:this.applyPromoCodeButtonOnClick.bind(this)});b.text(removePromoCodeDiv,"Promo Code: ");this.promoCodeSpan=b.span(removePromoCodeDiv);b.br(removePromoCodeDiv);b.span(removePromoCodeDiv,"action",{html:"Remove",onclick:this.removePromoCodeButtonOnClick.bind(this)});var totalsDiv=b.div(footerDiv,"totals");this.addChild(new OrderTotalsView().init(totalsDiv,{order:this.cart,hide:["shipping","tax","amountDue","subtotal"]}));actionDiv=b.div(actionsDiv,"action important_action");b.a(actionDiv,null,{html:"Check Out",href:"#/store/checkout/checkout_shipping"});actionDiv=b.div(actionsDiv,"action");b.a(actionDiv,null,{html:"Return to Shop",href:"#/store"});},focusPromoCodeInput:function()
{$(this.promoCodeInput).focus();},promoCodeInputKeyPress:function(event)
{if(event.which===13){this.raiseApplyPromotionCommand();return true;}},applyPromoCodeButtonOnClick:function(event)
{this.raiseApplyPromotionCommand();},removePromoCodeButtonOnClick:function(event)
{app.doCommand("remove_promotion");},raiseApplyPromotionCommand:function()
{app.doCommand("apply_promotion",{code:this.promoCodeInput.value});}});function OrderLineTableView()
{View.call();}
OrderLineTableView.define(View,{},{initView:function(element,params)
{this.order=params.order;this.showExpiresIn=(params.showExpiresIn===undefined)?true:params.showExpiresIn;this.allowChanges=(params.allowChanges===undefined)?true:params.allowChanges;},updateView:function()
{var i;var children,child;var line;children=this.children.toArray();for(i=0;i<children.length;++i)
{child=children[i];line=this.order.getOrderLineBySaleSku(child.line.sale_sku);if(null===line)
{this.removeChild(child);child.destroy();}
else
{child.line=line;}}},createControls:function()
{var head,body,row;var b=new ElementBuilder();var tableDiv=this.root=b.div(null,"table1 order_line_table_view table",{id:"lines"});head=b.div(tableDiv,"head");body=b.div(tableDiv,"body");row=b.div(head,"row");b.div(row,"cell left_cell image_cell",{innerHTML:"&nbsp;"});b.div(row,"cell name_cell",{innerHTML:"&nbsp;"});b.div(row,"cell quantity_cell",{innerHTML:"Quantity"});b.div(row,"cell unit_price_cell",{innerHTML:"Unit Price"});if(this.showExpiresIn){b.div(row,"cell expires_in_cell",{innerHTML:"Expires In"});}
b.div(row,"cell right_cell price_and_actions_cell");b.div(row,"clearer");for(i=0;i<this.order.lines.length;++i)
{this.addChild(new OrderLineView().init(body,{line:this.order.lines[i],allowChanges:this.allowChanges,showExpiresIn:this.showExpiresIn}));}}});function OrderLineView()
{View.call();}
OrderLineView.define(View,{},{initView:function(element,params)
{this.line=params.line;this.showExpiresIn=(params.showExpiresIn===undefined)?true:params.showExpiresIn;this.allowChanges=(params.allowChanges===undefined)?true:params.allowChanges;},renderView:function(element)
{View.prototype.renderView.apply(this,arguments);this.toggleQuantityInput(false);},updateView:function()
{var line=this.line;this.quantityInput.value=line.quantity.toString();this.quantitySpan.innerHTML=line.quantity.toString();this.totalSpan.innerHTML=h(formatPrice(line.getTotal()));this.totalRetailSpan.innerHTML=h(formatPrice(line.getTotalRetail()));},toggleQuantityInput:function(changing)
{if(this.allowChanges){$(this.changeDiv).toggle(!changing);$(this.updateDiv).toggle(changing);$(this.cancelDiv).toggle(changing);}
$(this.quantitySpan).toggle(!changing);$(this.quantityInput).toggle(changing);if(changing){$(this.quantityInput).focus().select();}},createControls:function()
{var cell,el;var countdown;var view,thumbnail;var e=new ElementBuilder(document);var line=this.line;var row=this.root=e.div(this.element,"row order_line_view");cell=e.div(row,"cell left_cell image_cell");if(line.sale_sku.sku.views.length>0)
{view=line.sale_sku.sku.views[0];if(view.image_url_70)
{e.img(cell,null,{src:Application.instance.createAbsoluteAssetUrl(view.image_url_70)});}}
cell=e.div(row,"cell name_cell");el=e.span(cell,"big",{innerHTML:line.sale_sku.sku.product.name});if(line.sale_sku.sku.product.subname)
{e.br(cell);e.text(cell,line.sale_sku.sku.product.subname);}
if(line.sale_sku.sku.name)
{e.br(cell);e.text(cell,line.sale_sku.sku.name);}
cell=e.div(row,"cell quantity_cell");el=e.div(cell,null,{id:"quantity"});this.quantitySpan=e.span(el,null,{innerHTML:line.quantity.toString()});this.quantityInput=e.input(el,"text_input",{type:"text",size:"2",maxLength:2,value:line.quantity.toString()});$(this.quantityInput).keypress(this.quantityInputOnKeypress.bind(this));if(this.allowChanges)
{var actionsDiv=e.div(cell,null,{id:"actions"});this.changeDiv=e.div(actionsDiv,"action",{innerHTML:"Change"});this.changeDiv.onclick=this.changeDivOnClick.bind(this);this.updateDiv=e.div(actionsDiv,"action",{innerHTML:"Update",onclick:this.updateDivOnClick.bind(this)});this.cancelDiv=e.div(actionsDiv,"secondary_action",{innerHTML:"Cancel",onclick:this.cancelDivOnClick.bind(this)});}
cell=e.div(row,"cell unit_price_cell");e.text(cell,formatPrice(line.unit_price));if(this.showExpiresIn)
{cell=e.div(row,"cell expires_in_cell");this.addChild(new CountdownView().init(cell,{endsIn:line.getCurrentExpiresIn(),timer:app.timer,showDot:true,warningMsecs:300000,expiredText:"Expired"}));}
cell=e.div(row,"cell right_cell price_and_actions_cell");if(this.allowChanges){el=e.div(cell,"action",{innerHTML:"Remove"});el.onclick=this.removeDivOnClick.bind(this);}
el=e.div(cell,null,{id:"prices"});this.totalRetailSpan=e.span(el,"cancelled");this.totalSpan=e.span(el,"biggest",{id:"price"});},quantityInputOnKeypress:function(event)
{if(event.which===13){this.updateDivOnClick();}},updateDivOnClick:function()
{var quantityValue=this.quantityInput.value;if(quantityValue.match(/\d+/))
{this.quantitySpan.innerHTML=quantityValue;this.toggleQuantityInput(false);app.doCommand("change_quantity",{saleSku:this.line.sale_sku,quantity:parseInt(quantityValue,10)});}
else
{this.raiseError(new ApplicationError("Enter a number"));}},cancelDivOnClick:function()
{this.toggleQuantityInput(false);this.update();},changeDivOnClick:function()
{this.toggleQuantityInput(true);},removeDivOnClick:function()
{app.doCommand("remove_from_cart",{saleSku:this.line.sale_sku});}});function OrderTotalsView()
{View.call();}
OrderTotalsView.define(View,{rows:["mfdPrice","promoSavings","subtotal","shipping","tax","amountDue","subtotalWithRetailPrice"]},{initView:function(element,params)
{this.order=params.order;this.hide=params.hide||[];},updateView:function()
{var order=this.order;var i,row;this.mfdPriceCell.innerHTML=formatPrice(order.getLinesTotal());this.promoSavingsCell.innerHTML="- "+formatPrice(order.getDiscount());this.subtotalCell.innerHTML=formatPrice(order.getSubtotal());this.amountDueCell.innerHTML=formatPrice(order.getTotal());this.totalRetailSpan.innerHTML=formatPrice(order.getTotalRetail());this.subtotalSpan.innerHTML=formatPrice(order.getSubtotal());this.shippingCell.innerHTML=order.calculating?"...":formatPrice(order.shipping);this.taxCell.innerHTML=order.calculating?"...":formatPrice(order.tax);for(i=0;i<this.klass.rows.length;++i){row=this.klass.rows[i];$(this[row+"Row"]).toggle(!this.hide.contains(row));}
$(this.promoSavingsRow).toggle(order.getDiscount()>0);$(this.mfdPriceRow).toggle(order.hasPromotion());},createControls:function()
{var table,tbody,tr,td;var b=new ElementBuilder();var root=this.root=b.div(null,"order_totals_view");table=b.table(root);tbody=b.tbody(table);tr=this.mfdPriceRow=b.tr(tbody);b.td(tr,"label",{html:"MFD Price"});this.mfdPriceCell=b.td(tr,"numeric");tr=this.promoSavingsRow=b.tr(tbody);b.td(tr,"label",{html:"Promo Savings"});this.promoSavingsCell=b.td(tr,"numeric highlight");tr=this.subtotalRow=b.tr(tbody);td=b.td(tr,"label",{html:"Subtotal"});this.subtotalCell=td=b.td(tr,"numeric");tr=this.subtotalWithRetailPriceRow=b.tr(tbody);b.td(tr,"label",{html:"Subtotal"});td=b.td(tr,"numeric");this.totalRetailSpan=b.span(td,"cancelled");this.subtotalSpan=b.span(td,"biggest",{id:"subtotal"});tr=this.shippingRow=b.tr(tbody);td=b.td(tr,"label",{html:"Shipping"});this.shippingCell=td=b.td(tr,"numeric");tr=this.taxRow=b.tr(tbody);td=b.td(tr,"label",{html:"Tax"});this.taxCell=td=b.td(tr,"numeric");tr=this.amountDueRow=b.tr(tbody);td=b.td(tr,"label",{html:"Total"});this.amountDueCell=td=b.td(tr,"numeric",{id:"total"});}});function CheckoutShippingView()
{View.apply(this,arguments);}
CheckoutShippingView.define(View,{},{initView:function(element,params)
{this.checkout=params.checkout;},setFocus:function()
{this.formView.focus();},createControls:function()
{var b=new ElementBuilder();var actionsDiv,actionDiv,formDiv;var el,table,tbody,tr,td;var address=this.checkout.shipping_address||{};this.root=b.div(null,"checkout_shipping_view");b.h1(this.root,null,{innerHTML:"Check Out"});stepsDiv=b.div(this.root,"checkout_steps");formDiv=this.formDiv=b.div(this.root,"form checkout_body");actionsDiv=b.div(this.root,"checkout_actions");b.div(stepsDiv,"step selected_step",{innerHTML:"1. Shipping"});b.div(stepsDiv,"step",{innerHTML:"2. Payment"});b.div(stepsDiv,"step",{innerHTML:"3. Review &amp; Purchase"});b.h2(formDiv,null,{innerHTML:"Shipping Address"});var formView=this.formView=new FormView().init(formDiv);this.addChild(formView);formView.text("name",address.name,"Name");formView.text("street1",address.street1,"Street 1");formView.text("street2",address.street2,"Street 2");formView.text("city",address.city,"City");formView.text("region",address.region,"State");formView.text("postal_code",address.postal_code,"Zip");formView.text("phone",address.phone,"Phone");b.div(actionsDiv,"action important_action",{html:"Continue",onclick:this.continueDivOnClick.bind(this)});actionDiv=b.div(actionsDiv,"action");b.a(actionDiv,null,{html:"Back",href:"#/store/cart"});},continueDivOnClick:function()
{app.doCommand("submit");}});function CheckoutPaymentView()
{View.apply(this,arguments);}
CheckoutPaymentView.define(View,{},{initView:function(element,params)
{this.message=params.message;this.checkout=params.checkout;this.order=params.order;},setFocus:function()
{this.formView.focus();},createControls:function()
{var stepsDiv,errorsDiv,formDiv,footerDiv,actionsDiv,actionDiv;var totalsDiv;var table,tbody,tr,td,label,input;var checkout=this.checkout;var order=this.order;var creditCard=checkout.credit_card||{};var b=new ElementBuilder();this.root=b.div(null,"checkout_payment_view");b.h1(this.root,null,{innerHTML:"Check Out"});stepsDiv=b.div(this.root,"checkout_steps");errorsDiv=b.div(this.root,"errors");formDiv=this.formDiv=b.div(this.root,"form checkout_body");footerDiv=b.div(this.root,"checkout_footer");actionsDiv=b.div(this.root,"checkout_actions");b.div(stepsDiv,"step",{innerHTML:"1. Shipping"});b.div(stepsDiv,"step selected_step",{innerHTML:"2. Payment"});b.div(stepsDiv,"step",{innerHTML:"3. Review &amp; Purchase"});if(this.message){b.div(errorsDiv,"error",{html:this.message.body});}
b.h2(formDiv,null,{innerHTML:"Credit Card"});var formView=this.formView=new FormView().init(formDiv);this.addChild(formView);formView.text("number",creditCard.number,"Number");formView.monthAndYear("expiration_month","expiration_year",creditCard.expiration_month,creditCard.expiration_year,"Expires (MM/YY)");formView.text("billing_address_postal_code",creditCard.billing_address_postal_code,"Billing Zip");formView.text("verification_value",creditCard.verification_value,"Security Code");totalsDiv=b.div(footerDiv,"totals");this.addChild(new OrderTotalsView().init(totalsDiv,{order:this.order,hide:["subtotalWithRetailPrice"]}));b.div(actionsDiv,"action important_action",{innerHTML:"Continue",onclick:this.continueDivOnClick.bind(this)});actionDiv=b.div(actionsDiv,"action");b.a(actionDiv,null,{html:"Back",href:"#/store/checkout/checkout_shipping"});},continueDivOnClick:function()
{app.doCommand("submit");}});function CheckoutReviewView()
{}
CheckoutReviewView.define(View,{},{initView:function(element,params)
{this.checkout=params.checkout;this.order=params.order;this.message=params.message;},createControls:function()
{var actionsDiv,actionDiv,bodyDiv,footerDiv,stepsDiv,errorsDiv;var totalsDiv;var el,table,tr,td;var order=this.order;var address=this.checkout.shipping_address;var credit_card=this.checkout.credit_card;var b=new ElementBuilder();this.root=b.div(null,"checkout_review_view");b.h1(this.root,null,{innerHTML:"Check Out"});stepsDiv=b.div(this.root,"checkout_steps");errorsDiv=b.div(this.root,"errors");bodyDiv=b.div(this.root,"form");footerDiv=b.div(this.root,"checkout_footer");actionsDiv=b.div(this.root,"checkout_actions");b.div(stepsDiv,"step",{innerHTML:"1. Shipping"});b.div(stepsDiv,"step",{innerHTML:"2. Payment"});b.div(stepsDiv,"step selected_step",{innerHTML:"3. Review &amp; Purchase"});if(this.message){b.div(errorsDiv,"error",{html:this.message.body});}
var shippingDiv=b.div(bodyDiv,null,{id:"shipping"});var paymentDiv=b.div(bodyDiv,null,{id:"payment"});b.div(bodyDiv,"clearer");var orderLineTableViewDiv=b.div(bodyDiv);b.h2(shippingDiv,"first",{html:"Shipping"});b.text(shippingDiv,address.name);b.br(shippingDiv);b.text(shippingDiv,address.street1);if(address.street2){b.br(shippingDiv);b.text(shippingDiv,address.street2);}
b.br(shippingDiv);b.text(shippingDiv,address.city+", "+address.region+" "+address.postal_code);if(address.phone){b.br(shippingDiv);b.text(shippingDiv,address.phone);}
b.h2(paymentDiv,"first",{html:"Payment"});table=b.table(paymentDiv);tr=b.tr(table);td=b.td(tr,"label",{html:CreditCardType.find(credit_card.type_id).name});td=b.td(tr,"value",{html:credit_card.number});tr=b.tr(table);td=b.td(tr,"label",{html:"Expires"});td=b.td(tr,"value",{html:credit_card.expiration_month.toString()+"/"+
credit_card.expiration_year.toString()});tr=b.tr(table);td=b.td(tr,"label",{html:"Billing Zip"});td=b.td(tr,"value",{html:credit_card.billing_address_postal_code});if(credit_card.verification_value){tr=b.tr(table);td=b.td(tr,"label",{html:"Security Code"});td=b.td(tr,"value",{html:credit_card.verification_value});}
this.orderLineTableView=new OrderLineTableView().init(orderLineTableViewDiv,{order:this.order,allowChanges:false});this.addChild(this.orderLineTableView);totalsDiv=b.div(footerDiv,"totals");this.orderTotalsView=new OrderTotalsView().init(totalsDiv,{order:this.order,hide:["subtotalWithRetailPrice"]});this.addChild(this.orderTotalsView);b.div(actionsDiv,"action important_action",{id:"purchase_action",innerHTML:"Purchase",onclick:this.purchaseDivOnClick.bind(this)});actionDiv=b.div(actionsDiv,"action");b.a(actionDiv,null,{html:"Back",href:"#/store/checkout/checkout_payment"});},purchaseDivOnClick:function()
{app.doCommand("confirm");}});function CheckoutCompleteView()
{View.apply(this,arguments);}
CheckoutCompleteView.define(View,{},{createControls:function()
{var b=new ElementBuilder();var actionsDiv,actionDiv;var root=this.root=b.div(null,"checkout_complete_view");b.h1(root,"first",{html:"Complete"});b.p(root,null,{html:"Thank you for order. You will receive an email\
            confirmation shortly."});actionsDiv=b.div(root,"checkout_actions");actionDiv=b.div(actionsDiv,"action important_action");b.a(actionDiv,null,{html:"Return to Shop",href:"#/store"});}});function StoryIndexView()
{View.call(this);}
StoryIndexView.define(View,{},{initView:function(element,params)
{this.viewsByStoryId={};this.stories=params.stories;},createControls:function()
{var i;var story;var storyView;for(i=0;i<this.stories.length;++i)
{story=this.stories[i];storyView=new StoryView().init(this.element,{story:story,index:i});this.addChild(storyView);this.viewsByStoryId[story.id]=storyView;}},scrollToStoryById:function(storyId)
{var view=this.viewsByStoryId[storyId];if(view){view.scrollIntoView(100);}}});function StoryView()
{View.call(this);}
StoryView.define(View,{},{initView:function(element,params)
{this.clipViews=[];this.story=params.story;this.index=params.index;},createControls:function()
{var i;var clip;var clipView;var headingDiv;var clipsDiv;var story=this.story;var b=new ElementBuilder();var root=this.root=b.div(null,(this.index===0)?"story_view first_story_view":"story_view");headingDiv=b.div(root,null,{id:"heading"});b.div(headingDiv,null,{id:"bar"});b.div(headingDiv,null,{id:"published_at",html:Formatters.longUTCDateFromTicks(story.published_at_est,{comma:false})});clipsDiv=b.div(root,null,{id:"clips"});clipsDiv.style.height=this.toPixelStyle(story.getHeight());for(i=0;i<story.clips.length;++i)
{clip=story.clips[i];clipView=ClipView.create(clipsDiv,clip,this);clipView.clicked.attach(this.clipViewClicked.bind(this));this.clipViews.push(clipView);this.addChild(clipView);}},getMaxClipZ:function()
{return this.clipViews.findMax(function(a,b){return(a.z-b.z);}).z;},getMinClipZ:function()
{return this.clipViews.findMax(function(a,b){return(b.z-a.z);}).z;},clipViewClicked:function(clipView)
{if(clipView.isUnderAny())
{clipView.moveToTop();}
else if(clipView.isOverAny())
{clipView.moveToBottom();}},toPixels:function(x)
{return x*100;},toPixelStyle:function(x)
{return this.toPixels(x).toString()+"px";}});function ClipView()
{View.call(this);}
ClipView.define(View,{create:function(element,clip,storyView)
{var klass=clip.type+"View";return new window[klass]().init(element,{clip:clip,storyView:storyView});}},{initView:function(element,params)
{this.clicked=new Event();this.storyView=params.storyView;this.clip=params.clip;this.z=null;},createControls:function()
{var clip=this.clip;var storyView=this.storyView;var root=this.root=document.createElement("div");root.onclick=this.rootOnClick.bind(this);root.className="clip_view";root.style.left=storyView.toPixelStyle(clip.x);root.style.top=storyView.toPixelStyle(clip.y);root.style.width=storyView.toPixelStyle(clip.width);root.style.height=storyView.toPixelStyle(clip.height);this.z=parseInt(clip.z,10);this.root.style.zIndex=clip.z;this.augmentRoot(root);},augmentRoot:function(root)
{},setZ:function(z)
{this.z=z;this.root.style.zIndex=z.toString();},moveToTop:function()
{this.setZ(this.storyView.getMaxClipZ()+1);},moveToBottom:function()
{this.setZ(this.storyView.getMinClipZ()-1);},isOver:function(other)
{return this.intersects(other)&&(this.z>other.z);},isUnder:function(other)
{return this.intersects(other)&&(this.z<other.z);},intersects:function(other)
{return(this.clip.intersects(other.clip));},isUnderAny:function()
{var me=this;return this.storyView.clipViews.trueForAny(function(other){return me.isUnder(other);});},isOverAny:function()
{var me=this;return this.storyView.clipViews.trueForAny(function(other){return me.isOver(other);});},rootOnClick:function()
{this.clicked.fire(this);}});function TextClipView()
{ClipView.call(this);}
TextClipView.define(ClipView,{},{augmentRoot:function(root)
{var fontSize;var b=new ElementBuilder();$(root).addClass("text_clip_view");fontSize=this.clip.font_size||24;root.style.fontSize=fontSize.toString()+"px";root.innerHTML=this.clip.text_html;}});function ImageClipView()
{ClipView.call(this);}
ImageClipView.define(ClipView,{},{augmentRoot:function(root)
{var fontSize;var b=new ElementBuilder();$(root).addClass("image_clip_view");b.img(root,null,{src:app.createAbsoluteAssetUrl(this.clip.image_url),alt:this.clip.alternative_text||""});}});function BottomAlignmentView()
{View.call(this);}
BottomAlignmentView.define(View,{},{init:function(element,params)
{this.content=params.content;return View.prototype.init.apply(this,arguments);},createControls:function()
{var table,tbody,tr,td;var b=new ElementBuilder();var root=this.root=b.div(null,"bottom_alignment_view");table=b.table(root,"");tbody=b.tbody(table);tr=b.tr(tbody);td=b.td(tr);td.appendChild(this.content);}});function RectangleSwatchView()
{View.apply(this,arguments);}
RectangleSwatchView.define(View,{},{initView:function(element,params)
{this.colors=params.colors||[];this.width=params.width||100;this.height=params.height||100;this.vertical=params.vertical?true:false;},createControls:function()
{var i;var slab;var box=this.root=document.createElement("div");box.style.position="relative";box.style.width=this.width.toString()+"px";box.style.height=this.height.toString()+"px";var xAttr=this.vertical?"top":"left";var widthAttr=this.vertical?"height":"width";var heightAttr=this.vertical?"width":"height";var slabWidth=Math.floor(this[widthAttr]/this.colors.length);for(i=0;i<this.colors.length;++i)
{slab=document.createElement("div");box.appendChild(slab);slab.style.position="absolute";slab.style.backgroundColor=this.colors[i].toHexTriplet();slab.style[xAttr]=(i*slabWidth).toString()+"px";slab.style[heightAttr]="100%";slab.style[widthAttr]=slabWidth.toString()+"px";}}});function Controller(parent)
{this.parent=parent;this.resources=new ArrayList();this.destroyed=false;}
Controller.prototype={addResource:function(resource)
{this.resources.add(resource);},removeResource:function(resource)
{this.resources.remove(resource);},destroy:function()
{var i;for(i=0;i<this.resources.getLength();++i)
{this.resources.get(i).destroy();}
this.resources.clear();this.destroyed=true;},root:function()
{var child=this;while(child.parent!==null)
{child=child.parent;}
return child;},handleError:function(error)
{if(!this.doHandleError(error))
{if(this.parent!==null)
{this.parent.handleError(error);}}},doHandleError:function(error)
{return false;},routeCommand:function(command)
{if(!this.doCommand(command))
{if(this.parent!==null)
{this.parent.routeCommand(command);}}},doCommand:function(command)
{var method;var result;if(!this.isBusy)
{method=this.findDefaultCommandMethod(command);if(method)
{result=method.call(this,command);return(result===undefined)?true:result;}}
return false;},findDefaultCommandMethod:function(command)
{var functionName="do"+constantToUpperCamelCase(command.type);if(typeof this[functionName]=="function")
{return this[functionName];}
return null;}};function MfdController(parent,activator,isDefault)
{Controller.call(this,parent);this.isDefault=isDefault||false;this.activator=activator||null;this.activated=false;this.locationNode=null;this.childController=null;}
MfdController.define(Controller,{sslRequired:false,sslAllowed:false,childControllers:[]},{leaf:function()
{return(this.childController===null)?this:this.childController.leaf();},insideRoot:function()
{if(this instanceof InsideController)
{return this;}
else if(this.parent===null)
{return false;}
else
{return this.parent.insideRoot();}},getLocation:function()
{if(this.parent===null)
{return new Location([this.locationNode]);}
else
{return this.parent.getLocation().push(this.locationNode);}},sslRequired:function()
{return this.klass.sslRequired||((this.childController!==null)&&this.childController.sslRequired());},sslAllowed:function()
{return this.klass.sslAllowed||((this.childController!==null)&&this.childController.sslAllowed());},createControllerChain:function(locationIterator)
{var child=null;var keepCurrentChild=false;var childNode;this.locationNode=this.isDefault?this.createDefaultLocationNode():locationIterator.next();childNode=locationIterator.peek();if(((childNode===null)&&this.childController&&this.childController.isDefault)||((childNode!==null)&&this.childController&&this.childController.locationNode.match(childNode,true)))
{child=this.childController;keepCurrentChild=true;}
else
{child=this.createChildController(childNode);if(((child===null)||child.isDefault)&&this.childController&&this.childController.isDefault)
{child=this.childController;keepCurrentChild=true;}}
if(child)
{if(!keepCurrentChild)
{this.setChildController(child);}
return child.createControllerChain(locationIterator);}
else if(childNode===null)
{if(this.childController)
{this.childController.destroy();this.childController=null;}
return true;}
else
{return false;}},activate:function(element,params,success,error,complete)
{var activateInternalSuccess=function()
{this.activated=true;if(this.childController)
{if(this.childController.activator)
{this.childController.activator(this.childController,success,error,complete);}
else
{this.childController.activate(this.element,{},success,error,complete);}}
else
{if(success)success();if(complete)complete();}};var activateInternalError=function(e)
{if(error)error(e);if(complete)complete();};if(!this.activated)
{this.activateInternal(element,params,activateInternalSuccess.bind(this),activateInternalError.bind(this));}
else
{activateInternalSuccess.bind(this)();}},start:function()
{this.startInternal();if(this.childController){this.childController.start();}},startInternal:function()
{},activateInternal:function(element,params,success,error)
{this.element=element;success();},createChildControllerInternal:function(locationNode)
{var type=locationNode.type;if(this.klass.childControllers.contains(type))
{return this.createChildControllerByType(type,false);}
return null;},createDefaultChildController:function()
{var type=this.klass.defaultChildController;if(type)
{return this.createChildControllerByType(type,true);}
return null;},createChildController:function(locationNode)
{if(locationNode===null)
{return this.createDefaultChildController();}
else
{return this.createChildControllerInternal(locationNode)||this.createDefaultChildController();}},createChildControllerByType:function(type,isDefault)
{var childKlass;var childKlassName;var activator;var activatorName;isDefault=isDefault||false;childKlassName=constantToUpperCamelCase(type)+"Controller";childKlass=window[childKlassName];activatorName="activate"+childKlassName;activator=this[activatorName]?this[activatorName].bind(this):null;return new childKlass(this,activator,isDefault);},createDefaultLocationNode:function()
{var params=this.parent?this.parent.locationNode.params:{};return new LocationNode(this.klass.controllerName,true,params);},setChildController:function(controller)
{if(this.childController)
{this.childController.destroy();}
this.addResource(controller);this.childController=controller;},scrollToTop:function()
{window.document.body.scrollTop="0";}});function MessageController(parent)
{MfdController.apply(this,arguments);}
MessageController.define(MfdController,{controllerName:"message"},{activateInternal:function(element,params,success,error)
{var id=this.locationNode.params.id;var message=Messages[id];var view;if(message){view=new MessageView().init(element,{message:message});this.addResource(view);view.render();}
success();}});function FrontController(parent)
{MfdController.call(this,parent);this.renderView();}
FrontController.define(MfdController,{controllerName:"front",childControllers:["welcome","inside"],defaultChildController:"inside"},{renderView:function()
{this.view=new FrontView().init(window.document.body);this.addResource(this.view);this.view.render();},doSignOut:function()
{var success=false;app.work(Session.destroy.bind(Session),function(){success=true;},null,function(){if(success){Member.current=null;app.go("/welcome");}});},doHandleError:function(error)
{if((error instanceof ApplicationError)&&(error.code==="AccessDenied"))
{app.go("/welcome");}
else
{this.view.showError(error.message);}
return true;},showThrobber:function()
{this.view.showThrobber();},hideThrobber:function()
{this.view.hideThrobber();}});function WelcomeController(parent)
{MfdController.call(this,parent);}
WelcomeController.define(MfdController,{controllerName:"welcome",childControllers:["login","page","forgot_password","reset_password"],defaultChildController:"login",sslRequired:true},{activateInternal:function(element,params,success,error)
{this.element=element;this.view=new WelcomeView().init(this.element,{leftImageUrl:app.site.home_left_image_url});this.addResource(this.view);this.view.render();success();},activatePageController:function(controller,success,error,complete)
{this.activateControllerInContentDiv.apply(this,arguments);},activateLoginController:function(controller,success,error,complete)
{this.activateControllerInContentDiv.apply(this,arguments);},activateResetPasswordController:function(controller,success,error,complete)
{this.activateControllerInContentDiv.apply(this,arguments);},activateForgotPasswordController:function(controller,success,error,complete)
{this.activateControllerInContentDiv.apply(this,arguments);},activateControllerInContentDiv:function(controller,success,error,complete)
{controller.activate(this.view.contentDiv,{},success,error,complete);}});function LoginController()
{MfdController.apply(this,arguments);}
LoginController.define(MfdController,{controllerName:"login",sslRequired:true},{activateInternal:function(element,params,success,error)
{this.element=element;this.view=new LoginView().init(this.element,this.locationNode.params);this.addResource(this.view);this.view.render();success();},doSignUp:function()
{var invitationCode=this.locationNode.params.invitation_code||null;var attrs=this.view.signupFormView.getValues();if(attrs.password!==attrs.password_confirm){this.view.signupFormView.showErrors({password_confirm:["Passwords do not match"]});}else{delete attrs.password_confirm;app.work(Member.create.bind(Member).curry(attrs,invitationCode),function(member){if(member.validated){app.go("/store");}else{this.view.showValidationRequestMessage();}}.bind(this),function(error){if(error instanceof DataInvalidError){this.view.signupFormView.showErrors(error.errors);}else if(error.code==="DuplicateMemberEmail"){if(error.member_validated){this.view.signupFormView.showErrors({email:["Email is already in use"]});}else{this.view.signupFormView.showErrors({email:["You have already signed up with this email address, but you have not validated it. We have sent you another validation request. Please check your email for this message and click the enclosed link."]});}}else{this.handleError(error);}}.bind(this));}},doLogIn:function()
{var credentials=this.view.loginFormView.getValues();app.work(Session.create.bind(Session).curry(credentials),function(member){app.go("/store");},function(error){if(error.code==="LoginFailed"){this.view.loginFormView.showErrors({email:["Login failed"]});}else{this.handleError(error);}}.bind(this));},doForgotPassword:function()
{app.go("/welcome/forgot_password");}});function ForgotPasswordController(parent)
{MfdController.apply(this,arguments);}
ForgotPasswordController.define(MfdController,{controllerName:"forgot_password",sslRequired:true},{activateInternal:function(element,params,success,error)
{this.element=element;this.view=new ForgotPasswordView().init(this.element);this.addResource(this.view);this.view.render();success();},doBack:function()
{app.go("/welcome/login");},doInitiatePasswordReset:function()
{var formValues=this.view.formView.getValues();app.work(Member.initiatePasswordReset.bind(Member).curry(formValues.email),function(member){this.view.showSuccessMessage();}.bind(this),function(error){if(error.code==="DataInvalid"){this.view.formView.showErrors({email:["No member with that email address"]});}else{this.handleError(error);}}.bind(this));}});function ResetPasswordController(parent)
{MfdController.apply(this,arguments);}
ResetPasswordController.define(MfdController,{controllerName:"reset_password",sslRequired:true},{activateInternal:function(element,params,success,error)
{this.element=element;this.view=new ResetPasswordView().init(this.element);this.addResource(this.view);this.view.render();success();},doResetPassword:function()
{var code=this.locationNode.params.code;var formValues=this.view.formView.getValues();var formView=this.view.formView;if(formValues.password!==formValues.password_confirm)
{formView.showErrors({password_confirm:["Passwords do not match"]});}
else
{app.work(Member.resetPassword.bind(Member).curry(code,formValues.password),function(){app.go("/store");}.bind(this),function(error)
{if(error.code==="InvalidPasswordResetCode"){formView.showErrors({password:["Your password reset link has expired. Please try again"]});}
else if(error.code==="DataInvalid")
{formView.showErrors(error.errors);}
else
{this.handleError(error);}}.bind(this));}}});function InsideController()
{MfdController.apply(this,arguments);}
InsideController.define(MfdController,{controllerName:"inside",childControllers:["journal","store"],defaultChildController:"store"},{setBackgroundColor:function(white)
{this.view.setBackgroundColor(white);},activateInternal:function(element,params,success,error)
{this.element=element;invokeAsyncParallel([[Order,Order.findSingleton],[Member,Member.findNamedSingleton,["current_member_public"]]],function(returns)
{this.cart=returns[0];Member.current=returns[1];this.view=new InsideView().init(this.element,{controller:this});this.addResource(this.view);this.view.render();success();}.bind(this),error);},activateJournalController:function(controller,success,error,complete)
{controller.activate(this.view.contentContainer,{menuDiv:this.view.menuDiv,fixedFrame:this.view.fixedFrame,backgroundFixedFrame:this.view.backgroundFixedFrame},success,error,complete);},activateStoreController:function(controller,success,error,complete)
{controller.activate(this.view.contentContainer,{menuDiv:this.view.menuDiv,fixedFrameElement:this.view.fixedFrame,backgroundFixedFrameElement:this.view.backgroundFixedFrame},success,error,complete);}});function StoreController()
{MfdController.apply(this,arguments);}
StoreController.define(MfdController,{controllerName:"store",defaultChildController:"home",childControllers:["home","sale","page","cart","checkout","invite","account","vendor","message"]},{activateInternal:function(element,params,success,error)
{this.element=element;this.menuDiv=params.menuDiv;this.fixedFrameElement=params.fixedFrameElement;this.backgroundFixedFrameElement=params.backgroundFixedFrameElement;Sale.findFeatured(function(sales){this.sales=sales;this.createView();success();}.bind(this),function(e){error(e);});},createView:function()
{this.storeMenuView=new StoreMenuView().init(this.menuDiv,this);this.addResource(this.storeMenuView);this.storeMenuView.render();},activateHomeController:function(controller,success,error,complete)
{controller.activate(this.element,{backgroundFixedFrameElement:this.backgroundFixedFrameElement},success,error,complete);},activateCartController:function(controller,success,error,complete)
{controller.activate(this.element,{cart:this.parent.cart},success,error,complete);},activateSaleController:function(controller,success,error,complete)
{controller.activate(this.element,{fixedFrameElement:this.fixedFrameElement},success,error,complete);}});function PageController(parent)
{MfdController.apply(this,arguments);}
PageController.define(MfdController,{controllerName:"page"},{activateInternal:function(element,params,success,error)
{this.element=element;Page.find(this.locationNode.params.id,function(html)
{this.scrollToTop();this.view=new HtmlView().init(this.element,{html:html});this.addResource(this.view);this.view.render();success();}.bind(this),function(e)
{error(e);});}});function InviteController()
{MfdController.apply(this,arguments);}
InviteController.define(MfdController,{controllerName:"invite"},{activateInternal:function(element,params,success,error)
{this.element=element;this.view=new InviteView().init(this.element);this.addResource(this.view);this.view.render();success();},doSendInvitations:function(command)
{var formValues=this.view.formView.getValues();var emails=formValues.emails.trim();if(emails.length===0)
{this.handleError(new ApplicationError("Enter one or more email addresses"));return;}
app.work(Invitation.createManyFromEmails.bind(Invitation).curry(emails),function(data){alert(data.toString()+
((data===1)?" invite was sent.":" invites were sent.")+" Thank you.");});}});function AccountController()
{MfdController.apply(this,arguments);}
AccountController.define(MfdController,{controllerName:"account",sslRequired:true},{activateInternal:function(element,params,success,error)
{this.element=element;Member.findCurrent(function(member){this.member=member;this.view=new AccountView().init(this.element,{member:member});this.addResource(this.view);this.view.render();success();}.bind(this),error);},doUpdateAccountInfo:function()
{var formView=this.view.accountInfoView.formView;if(!formView.isValid())
{formView.showValidationErrors();}
else
{var formValues=formView.getValues();app.work(this.member.update.bind(this.member).curry(formValues),function(){this.view.accountInfoView.showAttrs();Member.current.refreshSingleton();formView.reset();}.bind(this),function(error){if(error instanceof DataInvalidError){formView.showErrors(error.errors);}else{this.handleError(error);}}.bind(this));}},doEditAccountInfo:function()
{this.view.accountInfoView.showForm();this.view.accountInfoView.formView.focus();},doCancelEditAccountInfo:function()
{this.view.accountInfoView.showAttrs();this.view.accountInfoView.formView.reset();},doUpdatePassword:function()
{var formView=this.view.accountInfoView.changePasswordFormView;var attrs=formView.getValues();if(attrs.password!==attrs.password_confirm){formView.showErrors({password:["Passwords do not match"]});}
else
{app.work(this.member.updatePassword.bind(this.member).curry(attrs.password),function(){this.view.accountInfoView.showAttrs();formView.reset();}.bind(this),function(error){if(error instanceof DataInvalidError){formView.showErrors(error.errors);}else{this.handleError(error);}}.bind(this));}},doChangePassword:function()
{this.view.accountInfoView.showChangePasswordForm();this.view.accountInfoView.changePasswordFormView.focus();},doCancelChangePassword:function()
{this.view.accountInfoView.showAttrs();this.view.accountInfoView.changePasswordFormView.reset();}});function HomeController()
{MfdController.apply(this,arguments);}
HomeController.define(MfdController,{controllerName:"home"},{activateInternal:function(element,params,success,error)
{this.element=element;invokeAsyncParallel([[Sale,Sale.findFeatured],[Story,Story.findAll],[Feature,Feature.findCurrent]],function(returns)
{this.sales=returns[0];this.stories=returns[1];this.features=returns[2];this.scrollToTop();this.view=new HomeView().init(this.element,{backgroundFixedFrameElement:params.backgroundFixedFrameElement,sales:this.sales,stories:this.stories,features:this.features});this.addResource(this.view);this.view.render();success();}.bind(this),error);}});function SaleController()
{MfdController.apply(this,arguments);}
SaleController.define(MfdController,{controllerName:"sale",childControllers:["sale_sku"]},{activateInternal:function(element,params,success,error)
{this.element=element;this.fixedFrameElement=params.fixedFrameElement;this.updatingSoldOutSaleSkus=false;var saleSkuFinder;var category;var urlParams=this.locationNode.params;var sale=Sale.fromId(urlParams.id);if(urlParams.sale_category)
{category=SaleCategory.fromId(urlParams.sale_category);saleSkuFinder=category.findAssociated.bind(category).curry(SaleSku);}
else if(urlParams.mfd_picks)
{saleSkuFinder=sale.findAssociatedNamedSet.bind(sale).curry("mfd_picks",SaleSku);}
else if(urlParams.top_sellers)
{saleSkuFinder=sale.findAssociatedNamedSet.bind(sale).curry("top_sellers",SaleSku);}
else
{saleSkuFinder=sale.findAssociated.bind(sale).curry(SaleSku);}
invokeAsyncParallel([[Sale,Sale.find,[urlParams.id]],[null,saleSkuFinder]],function(returns)
{this.sale=returns[0];this.saleSkus=returns[1];this.scrollToTop();this.createView();this.initializeSoldOutTimer();success();}.bind(this),error);},activateSaleSkuController:function(controller,success,error,complete)
{var saleSkuId=controller.locationNode.params.id;var saleSku=this.saleSkus.findFirst(function(element){return element.id==saleSkuId;});controller.activate(this.fixedFrameElement,{saleSku:saleSku},success,error,complete);},createView:function()
{var view;var hasBigImage=this.sale.big_image_url_430!=="";if(hasBigImage){view=new BigSaleImageView().init(this.element,{controller:this,sale:this.sale,saleSku:this.saleSkus[0]});this.addResource(view);view.render();}else{view=new SaleSkuListView().init(this.element,{saleSkus:this.saleSkus,controller:this});this.addResource(view);view.render();}},initializeSoldOutTimer:function()
{var timer=new Timer(30000);this.addResource(timer.tick.attach(this.soldOutTimerTick.bind(this)));this.addResource(timer);timer.start();this.soldOutTimerTick();},soldOutTimerTick:function()
{this.updateSoldOutSaleSkus();},updateSoldOutSaleSkus:function()
{var i,saleSku;if(this.updatingSoldOutSaleSkus){return;}
this.updatingSoldOutSaleSkus=true;this.sale.findSoldOutSaleSkuIds(function(soldOutSaleSkuIds){if(!this.destroyed){for(i=0;i<this.saleSkus.length;++i){saleSku=this.saleSkus[i];saleSku.setSoldOut(soldOutSaleSkuIds.contains(saleSku.id));}}}.bind(this),null,function(){this.updatingSoldOutSaleSkus=false;}.bind(this));}});function SaleSkuController()
{MfdController.apply(this,arguments);}
SaleSkuController.define(MfdController,{controllerName:"sale_sku"},{activateInternal:function(element,params,success,error)
{this.element=element;this.saleSku=params.saleSku;this.saleSku.populate(function(){this.createView();success();}.bind(this),error);},createView:function()
{this.view=new SaleSkuView().init(this.element,{saleSku:this.saleSku,controller:this});this.addResource(this.view);this.view.render();},getCart:function()
{return this.insideRoot().cart;},doAddToCart:function()
{var cart=this.getCart();app.work(cart.add.bind(cart).curry(this.saleSku),function(){this.view.cartInfoView.update(true);}.bind(this));},doChangeQuantity:function(command)
{var cart=this.getCart();app.work(cart.changeQuantity.bind(cart).curry(this.saleSku,command.quantity),function(){this.view.cartInfoView.changingQuantity=false;this.view.cartInfoView.update(true);}.bind(this),function(error){this.view.cartInfoView.changingQuantity=false;this.view.cartInfoView.update(true);this.handleError(error);}.bind(this));}});function CartController()
{MfdController.apply(this,arguments);}
CartController.define(MfdController,{controllerName:"cart"},{activateInternal:function(element,params,success,error)
{this.element=element;this.cart=params.cart;this.view=new CartView().init(this.element,{cart:this.cart});this.addResource(this.view);this.view.render();this.attachCart();success();},attachCart:function()
{this.addResource(this.cart.lineExpired.attach(this.cartLineExpired.bind(this)));},cartLineExpired:function()
{this.view.update();},doApplyPromotion:function(command)
{var cart=this.cart;app.work(cart.applyPromotion.bind(cart).curry(command.code),null,null,function(){this.view.update();}.bind(this));},doRemovePromotion:function(command)
{var cart=this.cart;app.work(cart.clearPromotions.bind(cart),null,null,function(){this.view.update();this.view.focusPromoCodeInput();}.bind(this));},doChangeQuantity:function(command)
{var cart=this.cart;app.work(cart.changeQuantity.bind(cart).curry(command.saleSku,command.quantity),null,null,function(){this.view.update();}.bind(this));},doRemoveFromCart:function(command)
{var cart=this.cart;app.work(cart.remove.bind(cart).curry(command.saleSku),null,null,function(){this.view.update();}.bind(this));}});function CheckoutController()
{MfdController.apply(this,arguments);}
CheckoutController.define(MfdController,{controllerName:"checkout",childControllers:["checkout_shipping","checkout_payment","checkout_review","checkout_complete"],defaultChildController:"checkout_shipping",sslRequired:true},{activateInternal:function(element,params,success,error)
{this.element=element;Checkout.findSingleton(function(checkout){this.checkout=checkout;if(success)success();}.bind(this),function(e){error(e);});}});function CheckoutShippingController()
{MfdController.apply(this,arguments);}
CheckoutShippingController.define(MfdController,{controllerName:"checkout_shipping"},{activateInternal:function(element,params,success,error)
{this.element=element;this.checkout=this.parent.checkout;this.view=new CheckoutShippingView().init(this.element,{checkout:this.checkout});this.addResource(this.view);this.view.render();success();},startInternal:function()
{var cart=this.insideRoot().cart;if(!this.leaveIfCartEmpty()){this.attachCart();app.work(cart.calculate.bind(cart));}},attachCart:function()
{var cart=this.insideRoot().cart;this.addResource(cart.lineExpired.attach(this.cartLineExpired.bind(this)));},cartLineExpired:function()
{var cart=this.insideRoot().cart;if(!this.leaveIfCartEmpty()){this.view.update();app.work(cart.calculate.bind(cart));}},leaveIfCartEmpty:function()
{var cart=this.insideRoot().cart;if(cart.isEmpty())
{app.go("/store/message?all_items_expired");return true;}
return false;},doSubmit:function()
{var formValues=this.view.formView.getValues();var cart=this.insideRoot().cart;app.work(this.checkout.updateUnsavedShippingAddress.bind(this.checkout).curry(formValues),function(){cart.setAttributes(this.checkout.order);}.bind(this),function(error){if(error instanceof DataInvalidError){this.view.formView.showErrors(error.errors);}else{this.handleError(error);}}.bind(this),null,function(){app.go("../checkout_payment");}.bind(this));}});function CheckoutPaymentController()
{MfdController.apply(this,arguments);}
CheckoutPaymentController.define(MfdController,{controllerName:"checkout_payment"},{activateInternal:function(element,params,success,error)
{this.element=element;this.checkout=this.parent.checkout;var cart=this.insideRoot().cart;var message=Messages[this.locationNode.params.message];this.view=new CheckoutPaymentView().init(this.element,{message:message,checkout:this.checkout,order:cart});this.addResource(this.view);this.view.render();success();},startInternal:function()
{var cart=this.insideRoot().cart;if(!this.leaveIfCartEmpty()){this.attachCart();app.work(cart.calculate.bind(cart));}},attachCart:function()
{var cart=this.insideRoot().cart;this.addResource(cart.lineExpired.attach(this.cartLineExpired.bind(this)));this.addResource(cart.updated.attach(this.cartUpdated.bind(this)));},cartUpdated:function()
{this.view.update();},cartLineExpired:function()
{var cart=this.insideRoot().cart;if(!this.leaveIfCartEmpty()){this.view.update();app.work(cart.calculate.bind(cart));}},leaveIfCartEmpty:function()
{var cart=this.insideRoot().cart;if(cart.isEmpty())
{app.go("/store/message?all_items_expired");return true;}
return false;},doSubmit:function()
{var formValues=this.view.formView.getValues();var cart=this.insideRoot().cart;app.work(this.checkout.updateUnsavedCreditCard.bind(this.checkout).curry(formValues),function(){cart.setAttributes(this.checkout.order);}.bind(this),function(error){if(error instanceof DataInvalidError){this.view.formView.showErrors(error.errors);}else{this.handleError(error);}}.bind(this),null,function(){app.go("../checkout_review");});}});function CheckoutReviewController()
{MfdController.apply(this,arguments);}
CheckoutReviewController.define(MfdController,{controllerName:"checkout_review"},{activateInternal:function(element,params,success,error)
{this.element=element;this.checkout=this.parent.checkout;var cart=this.insideRoot().cart;var message=Messages[this.locationNode.params.message];this.view=new CheckoutReviewView().init(element,{message:message,order:cart,checkout:this.checkout});this.addResource(this.view);this.view.render();success();},startInternal:function()
{var cart=this.insideRoot().cart;if(!this.leaveIfCartEmpty()){this.attachCart();app.work(cart.calculate.bind(cart));}},attachCart:function()
{var cart=this.insideRoot().cart;this.addResource(cart.lineExpired.attach(this.cartLineExpired.bind(this)));this.addResource(cart.updated.attach(this.cartUpdated.bind(this)));},cartUpdated:function()
{this.view.update();},cartLineExpired:function()
{var cart=this.insideRoot().cart;if(!this.leaveIfCartEmpty()){this.view.update();app.work(cart.calculate.bind(cart));}},leaveIfCartEmpty:function()
{var cart=this.insideRoot().cart;if(cart.isEmpty())
{app.go("/store/message?all_items_expired");return true;}
return false;},doConfirm:function()
{var cart=this.insideRoot().cart;app.work(this.checkout.confirm.bind(this.checkout).curry(cart.digest()),this.checkoutConfirmSuccess.bind(this),this.checkoutConfirmError.bind(this));},checkoutConfirmSuccess:function()
{var cart=this.insideRoot().cart;app.work(cart.refreshSingleton.bind(cart),function(){app.go("../checkout_complete");});},checkoutConfirmError:function(error)
{switch(error.code)
{case"OrderDigestMismatch":{app.go("../checkout_review?message=reconfirm");break;}
case"PaymentGatewayTransactionFailed":{app.go("../checkout_payment?message=payment_failed");break;}
default:{this.handleError(error);break;}}}});function CheckoutCompleteController()
{MfdController.apply(this,arguments);}
CheckoutCompleteController.define(MfdController,{controllerName:"checkout_complete"},{activateInternal:function(element,params,success,error)
{this.view=new CheckoutCompleteView().init(element);this.addResource(this.view);this.view.render();success();}});function JournalController()
{MfdController.apply(this,arguments)}
JournalController.define(MfdController,{controllerName:"journal",childControllers:["story_index"],defaultChildController:"story_index"},{activateInternal:function(element,params,success,error)
{this.element=element;this.menuDiv=params.menuDiv;this.backgroundFixedFrameElement=params.backgroundFixedFrameElement;this.insideRoot().setBackgroundColor(false);success();},destroy:function()
{this.insideRoot().setBackgroundColor(true);MfdController.prototype.destroy.apply(this);}});function StoryIndexController()
{MfdController.apply(this,arguments);}
StoryIndexController.define(MfdController,{controllerName:"story_index"},{activateInternal:function(element,params,success,error)
{params=params||{};this.element=element;Story.findAll(function(stories){var storyId;var selectedStory;this.stories=stories;this.createView();storyId=parseInt(this.locationNode.params["story_id"],10);if(storyId&&(stories.length>0)&&(storyId!==stories[0].id))
{this.view.scrollToStoryById(storyId);}
else
{this.scrollToTop();}
success();}.bind(this),function(e){error(e);});},createView:function()
{this.view=new StoryIndexView().init(this.element,{stories:this.stories});this.addResource(this.view);this.view.render();}});function VendorController()
{MfdController.apply(this,arguments);}
VendorController.define(MfdController,{controllerName:"vendor"},{activateInternal:function(element,params,success,error)
{this.element=element;Vendor.find(this.locationNode.params.id,function(vendor){this.vendor=vendor;this.scrollToTop();this.createView();success();}.bind(this),function(e){error(e);});},createView:function()
{this.view=new VendorView().init(this.element,{vendor:this.vendor});this.addResource(this.view);this.view.render();}});