LFM.set("Observable",Class.create({GUI_ACTION_CLASS_PREFIX:"lfmradio",identifier:"You-forgot-to-override-the-identifier-didnt-you?",initialize:function(){this.observers=[];},notifyObservers:function(event){for(var i=0;i<this.observers.length;i++){this.observers[i].notify(event);}},addObserver:function(subscriber){this.observers.push(subscriber);},addGUIActionListener:function(parentElementID){$(parentElementID).observe("click",this._GUIActionHandler.bindAsEventListener(this));},_GUIActionHandler:function(event){var element=event.element();var className="";element=LFM.DomSearch.findParentByClassName(element,/lfmradio\:/);if(element){className=element.className;}if(!className){return false;}var matches=className.match(new RegExp(this.GUI_ACTION_CLASS_PREFIX+":([^ ]+)","g"));if(matches&&matches.length){var called=[];for(var i=0,ilen=matches.length;i<ilen;i++){var match=matches[i].replace(new RegExp(this.GUI_ACTION_CLASS_PREFIX+":"),"");var handler="_GUIActionHandler"+match.capitalize();if(this[handler]){called.push(match);this[handler](event,element);}else{this.log("No handler implemented for: "+match);}}}if(called.length){return called;}return false;},log:function(){var args=[this.identifier+":"];for(var i=0,ilen=arguments.length;i<ilen;i++){args.push(arguments[i]);}LFM.log.apply(this,args);}}));LFM.set("Observer",Class.create({notify:function(event){}}));LFM.set("Event",Class.create({}));LFM.set("Event",{ShoutComplete:Class.create(LFM.Event,{initialize:function(){this.identifier="ShoutComplete";}}),ShoutCaptchaShown:Class.create(LFM.Event,{initialize:function(){this.identifier="ShoutCaptchaShown";}})});LFM.set("Activityfeed",{DeleteListener:Class.create({initialize:function(){document.observe("click",this.bin.bindAsEventListener(this));},bin:function(event){var link=event.findElement("a.removeActivity");if(!link){return;}event.stop();var itemNameContainer=link.up("li");new Ajax.Request("/ajax/deleteActivity",{parameters:{ajax:1,activities:itemNameContainer.id,formtoken:LFM.Session.formtoken},onComplete:function(resp){var ajaxResponse=new LFM.Ajax.Response(resp);if(ajaxResponse.isSuccess()){itemNameContainer.remove();}}});}})});LFM.set("Activity",{buildFeedItem:function(data){var activity=new Element("ul",{"class":"minifeedSmall"});var li=new Element("li",{"class":data.action});if(data.icon){li.insert(data.icon);}li.insert(data.message);activity.update(li);return activity;}});LFM.set("Util",{AdblockDetector:Class.create({initialize:function(){},isBlocking:function(){if(LFM.Session.language!="en"){return false;}return this.isABP();},isABP:function(){return this.isEasyList();},isEasyList:function(){if($("footer_ads")&&$("footer_ads").visible()&&$("footer_ads").getStyle("-moz-binding")){return $("footer_ads").getStyle("-moz-binding").include("abp-elemhidehit");}}})});LFM.set("Library",{AddListener:Class.create({options:{},initialize:function(bindTo,options){this.bindTo=$(bindTo);this.bindTo.observe("click",this._onClick.bindAsEventListener(this));Object.extend(this.options,options||{});},_onClick:function(e){var element=e.element();if(!element||!element.hasClassName("lfmAddButton")){return true;}e.stop();this._showDialog(this.options.resource||{url:element.getAttribute("href")});},_showDialog:function(resource){var dialogURL="/ajax/dialog/add";var dialogOptions={resource:resource,onConfirm:this._onConfirmDialog.bindAsEventListener(this)};this._dialog=new LFM.Dialog(dialogOptions);this._dialog.show(dialogURL);},_onConfirmDialog:function(e){}})});LFM.set("Adserver",{getSponsoredByBranding:function(pixelTracker,brandLogo,clickThrough,hidePresentedBy){var brand=new Element("div",{"class":"brand"});if(!hidePresentedBy){var sponsored=new Element("img",{"class":"sponsored",src:LFM.Session.staticHost+"/promotions/notifications_presented_grey.gif",width:88,height:5}).setStyle({padding:"2px 0"});}var tracker=new Element("img",{src:pixelTracker,width:1,height:1}).setStyle({position:"absolute",top:0,left:0,visibility:"hidden"});if(brandLogo){var logo=new Element("img",{src:brandLogo,width:88,height:31});if(clickThrough){logo=logo.wrap(new Element("a",{href:clickThrough,target:"_blank"}));}if(sponsored){brand.insert(sponsored);}brand.insert(logo);}brand.insert(tracker);return brand;}});LFM.set("Library",{AlbumStrip:Class.create({initialize:function(albumstrip){this._albumstrip=$(albumstrip);this._albumstrip.addClassName("js");this._wrapper=this._albumstrip.down("div.wrapper");this._wrapper.setStyle({overflow:"hidden"});this._list=this._wrapper.down("ul");if(this._list){this._listItems=this._list.childElements();}this._currentFilterName=false;this._leftButton=new Element("a",{"class":"leftButton",href:"#"});this._rightButton=new Element("a",{"class":"rightButton",href:"#"});this._albumstrip.insert(this._leftButton);this._albumstrip.insert(this._rightButton);this._offset=0;this._itemcount=this._listItems?this._listItems.length:0;var what=Prototype.Browser.WebKit?window:document;var when=Prototype.Browser.WebKit?"load":"dom:loaded";Event.observe(what,when,function(){this._itemwidth=this._list.down("li").getWidth();this._reflow();Event.observe(window,"resize",this._reflow.bindAsEventListener(this));this._leftButton.observe("click",this.scrollLeft.bindAsEventListener(this));this._rightButton.observe("click",this.scrollRight.bindAsEventListener(this));}.bind(this));},setUpFilter:function(container){this._filteredTable=$(container);startTimer("setUpFilter");this._filterDataTable={};this._filterDataTable.albums=[];this._filterDataTable.everything=this._filteredTable.select("tbody tr");this._filterDataTable.everything.each(function(row){var classNames=row.className.split(" ");classNames.each(function(className){if(className.substring(0,5)=="album"){if(!this._filterDataTable.albums[className]){this._filterDataTable.albums[className]=[];}this._filterDataTable.albums[className].push(row);}}.bind(this));}.bind(this));stopTimer("setUpFilter");this._albumstrip.observe("click",this._filter.bindAsEventListener(this));},_filter:function(event){if(!this._maxHeight){this._maxHeight=this._filteredTable.up().getHeight();this._filteredTable.up().setStyle({height:this._maxHeight+"px"});var tdCells=this._filterDataTable.everything.first().select("td");var thCells=this._filteredTable.down("thead tr").select("th");for(var i=thCells.length-1;i>=0;i--){var width=tdCells[i].getWidth();var width=width-20;thCells[i].setStyle({width:width+"px"});}}var link=event.findElement("a");if(!link){return;}event.stop();if(link.up("h3")){link.up("h3").addClassName("current");this._listItems.invoke("removeClassName","selected");if(!this._currentFilterName){return;}else{this._currentFilterName=false;this._filteredTable.show();$("noTracksMessage").hide();this._filterDataTable.everything.invoke("show");LFM.Display.candyStripe(this._filteredTable);}}else{var classNames=link.up("li").className.split(" ");var albumIdentifier="";classNames.each(function(className){if(className.substring(0,5)=="album"){albumIdentifier=className;}}.bind(this));if(albumIdentifier){this._albumstrip.down("h3").removeClassName("current");this._listItems.invoke("removeClassName","selected");link.up("li").addClassName("selected");this._currentFilterName=albumIdentifier;this._filterDataTable.everything.invoke("hide");if(this._filterDataTable.albums[albumIdentifier]){this._filterDataTable.albums[albumIdentifier].invoke("show");LFM.Display.candyStripe(this._filterDataTable.albums[albumIdentifier]);this._filteredTable.show();$("noTracksMessage").hide();}else{this._filteredTable.hide();$("noTracksMessage").show();}}else{return;}}},scrollRight:function(event){if(event){event.stop();}var newOffset=this._offset-this._itemwidth;if(newOffset*-1>this._list.getWidth()-this._wrapper.getWidth()){newOffset=this._wrapper.getWidth()-this._list.getWidth();}this._offset=newOffset;new Effect.Morph(this._list,{style:{left:newOffset+"px"},duration:0.3,queue:{position:"end",scope:"scrollscope"}});},scrollLeft:function(event){if(event){event.stop();}var newOffset=this._offset+this._itemwidth;if(newOffset>0){newOffset=0;}this._offset=newOffset;new Effect.Morph(this._list,{style:{left:newOffset+"px"},duration:0.3,queue:{position:"end",scope:"scrollscope"}});},_reflow:function(){var paginationNeeded=true;var availableWidth=this._albumstrip.getWidth()-this._leftButton.getWidth()-this._rightButton.getWidth();log(availableWidth);var numberOfItems=Math.floor(availableWidth/this._itemwidth);if(numberOfItems>=this._itemcount){paginationNeeded=false;numberOfItems=this._itemcount;}var optimumWidth=numberOfItems*this._itemwidth;this._wrapper.setStyle({width:optimumWidth+"px"});if(paginationNeeded){this._leftButton.show();this._rightButton.show();}else{this._leftButton.hide();this._rightButton.hide();}}})});LFM.set("Analytics",{Tracker:Class.create({ATTRIBUTE_FLAG_CANCEL_EVENT:"data-x-cancel-event",pageIdentifier:null,hostname:null,taggingSource:"",initialize:function(pageIdentifier,hostname){this.pageIdentifier=pageIdentifier;this.hostname=hostname;},bindOutboundLinkListener:function(){$(document).observe("mousedown",this._outboundLinkListener.bind(this));$(document).observe("click",this._clickListener.bind(this));},bindEventListener:function(){$(document).observe("click",this._eventListener.bind(this));},_track:function(action,label,value){var event=["eT._trackEvent"];event.push(this.pageIdentifier);event.push(action);event.push(label||"");if(value){event.push(parseInt(value));}LFM.log("GA Event:",event);_gaq.push(event);},_eventListener:function(event){var elm=$(event.target);if(!elm.readAttribute("data-analytics-action")){elm=elm.up("[data-analytics-action]");}if(!elm){return;}var action=elm.readAttribute("data-analytics-action");var label=elm.readAttribute("data-analytics-label");var value=elm.readAttribute("data-analytics-value");if(action){this._track(action,label,value);}},_outboundLinkListener:function(event){var elm=$(event.target);var type=elm.tagName.toLowerCase();if(type=="a"){var href=elm.readAttribute("href");if(this.isOutboundLink(href)&&!elm.readAttribute("onclick")){this.outboundClick(href);var isKeyModifier=event.altKey||event.ctrlKey||event.shiftKey||event.metaKey;var isRadio=window.location.pathname.match(/^\/listen/)?true:false;var isTargetBlank=elm.readAttribute("target")&&elm.readAttribute("target").toLowerCase()=="_blank";var isDisabled=elm.readAttribute("data-analytics-redirect")=="false"?true:false;if(event.isLeftClick()&&!isKeyModifier&&!isRadio&&!isTargetBlank&&!isDisabled){event.stop();elm.writeAttribute(this.ATTRIBUTE_FLAG_CANCEL_EVENT,true);(function(){document.location=href;}).delay(0.3);return false;}}}return true;},_clickListener:function(event){var elm=$(event.target);if(elm.readAttribute(this.ATTRIBUTE_FLAG_CANCEL_EVENT)){event.preventDefault();elm.writeAttribute(this.ATTRIBUTE_FLAG_CANCEL_EVENT,"");}},isOutboundLink:function(href){var regexIsAbsolute=new RegExp("^(https?://|//)","i");var regexIsInternal=new RegExp("^(https?://|//)"+this.hostname,"i");if(href.match(regexIsAbsolute)&&!href.match(regexIsInternal)){return true;}return false;},outboundClick:function(url){this._track("OutboundClick",url);},storeTagSource:function(taggingSource){LFM.log("store tagging source",this.taggingSource);this.taggingSource=taggingSource;},retrieveTagSource:function(){LFM.log("retrieve tagging source",this.taggingSource);return this.taggingSource;},eventAddToLibrary:function(location){this._track("AddToLibrary",location);},eventRemoveFromLibrary:function(location){this._track("RemoveFromLibrary",location);},eventAddFriend:function(count){count=count||1;this._track("AddFriend",null,count);},eventDeleteFriend:function(count){count=count||1;this._track("DeleteFriend",null,count);},eventRejectFriend:function(count){count=count||1;this._track("RejectFriend",null,count);},eventJoinGroup:function(){this._track("JoinGroup");},eventLeaveGroup:function(){this._track("LeaveGroup");},eventMultiBuy:function(){this._track("MultiBuy");},eventAddToPlaylist:function(location){this._track("AddToPlaylist",location);},eventRadioProblem:function(){this._track("RadioProblem");},eventShareByEmail:function(){this._track("ShareByEmail");},eventRadioStillListening:function(){this._track("RadioStillListening");},eventAddTags:function(){this._track("AddTags");},eventClientDownload:function(platform){this._track("ClientDownload",platform);},eventSendMessage:function(){this._track("SendMessage");},eventDeletePlaylist:function(){this._track("DeletePlaylist");},eventShoutPost:function(){this._track("ShoutPost");},eventCommentPost:function(){this._track("CommentPost");},eventPlayTrack:function(type){this._track("PlayTrack",type);},eventEventAttendance:function(status){this._track("EventAttendance",status);},eventLoveTrack:function(source){this._track("LoveTrack",source);},eventBanTrack:function(source){this._track("BanTrack",source);},eventSkipTrack:function(source){this._track("SkipTrack",source);},eventPauseTrack:function(source){this._track("PauseTrack",source);},eventStartStation:function(){this._track("StartStation");},eventRadioMetadataClick:function(location){this._track("RadioMetadataClick",location);},eventRadioPaneSwitch:function(pane){this._track("RadioPaneSwitch",pane);},eventRadioError:function(error){this._track("RadioError",error);},eventRadioVideoAdStart:function(type){this._track("RadioVideoAdStart",type);},eventRadioVideoAdComplete:function(type){this._track("RadioVideoAdComplete",type);},eventPromobarLink:function(barName){this._track("PromobarLink",barName);},eventPromobarDismiss:function(barName){this._track("PromobarDismiss",barName);},eventFacebookBootstrapEdit:function(){this._track("FacebookBootstrapEdit");},eventFacebookBootstrapImageToggle:function(){this._track("FacebookBootstrapImageToggle");},eventPaintItBlack:function(){this._track("ColourToggle","PaintItBlack");},eventSimplyRed:function(){this._track("ColourToggle","SimplyRed");},eventGoingToEvent:function(){this._track("GoingToEvent");},eventInterestedInEvent:function(){this._track("InterestedInEvent");},eventNotGoingToOrInterestedInEvent:function(){this._track("NotGoingToOrInterestedInEvent");},eventDiscoverShareEmail:function(){this._track("DiscoverShareEmail");},eventDiscoverShareFacebook:function(){this._track("DiscoverShareFacebook");},eventDiscoverShareTwitter:function(){this._track("DiscoverShareTwitter");},eventDiscoverJumpListClick:function(){this._track("DiscoverJumpListClick");},eventDiscoverPinnedButtonClick:function(){this._track("DiscoverJumpListClick");},eventDiscoverClickClimp:function(){this._track("DiscoverClickClimp");},eventDiscover:function(name,value){if(typeof value=="undefined"){this._track("Discover"+name);}else{this._track("Discover"+name,value);}},eventWikiReadMore:function(){this._track("ReadMore","Wiki");}})});LFM.set("Form",{Attachbutton:Class.create({initialize:function(button,options){this.button=$(button);if(!options){options={};}this.options=options;this._bindToButton();},_bindToButton:function(){Event.observe(this.button,"click",function(e){Event.stop(e);var picker=new LFM.Form.ResourcePicker({onSelect:this._onSelect.bind(this)});picker.show();}.bindAsEventListener(this));},_onSelect:function(res){if(res){this._appendAttachment(res.type,res.id);}},_appendAttachment:function(type,id){if(!this.itemcontainer&&this.options.itemcontainer){this.itemcontainer=$(this.options.itemcontainer);}if(this.itemcontainer){this.itemcontainer.show();this.itemcontainer.down("img.progress").show();new Ajax.Request("/ajax/attachment",{method:"get",parameters:"type="+type+"&id="+id,onComplete:this._appendAttachmentCallback.bind(this)});}var form=this.button.up("form");if(form){var attachmenttypeInput=form.down("input[name=attachmenttype]");var attachmentidInput=form.down("input[name=attachmentid]");if(!attachmenttypeInput){var attachmenttypeInput=document.createElement("input");attachmenttypeInput.setAttribute("type","hidden");attachmenttypeInput.setAttribute("name","attachmenttype");var attachmentidInput=document.createElement("input");attachmentidInput.setAttribute("type","hidden");attachmentidInput.setAttribute("name","attachmentid");attachmenttypeInput.setAttribute("value",type);attachmentidInput.setAttribute("value",id);form.appendChild(attachmenttypeInput);form.appendChild(attachmentidInput);}else{attachmenttypeInput.setAttribute("value",type);attachmentidInput.setAttribute("value",id);}}},_appendAttachmentCallback:function(req){var result=req.responseText.evalJSON();if(this.itemcontainer){this.itemcontainer.insert({top:result.attachment});this.itemcontainer.down("img.progress").hide();}}})});LFM.set("Button",{MultiButton:{setup:function(){this.activeButton=false;this.menu=$("multiButtonMenu");this.loadedInfo=$H();this.menu.observe("click",this.observeMenu.bindAsEventListener(this));$("page").observe("click",this.observeDocument.bindAsEventListener(this));this.clickOffObserver=this.clickOff.bindAsEventListener(this);this.parentIsUser=LFM.ParentResource&&LFM.ParentResource.type==4;this.parentIsLoggedInUser=LFM.Session.loggedIn&&this.parentIsUser&&LFM.ParentResource.name==LFM.Session.userName;},observeDocument:function(e){var button=e.findElement("a.lfmMultiButton");if(!button){return false;}e.stop();if(this.activeButton&&this.activeButton!=button){this.clickOff();}else{if(this.activeButton&&this.activeButton==button){this.clickOff();return;}}this.activeButton=button;if(this.activeButton.hasClassName("lfmSmallButton")){this.activeButton.addClassName("lfmSmallActiveMultiButton");}else{this.activeButton.addClassName("lfmBigActiveMultiButton");}if(this.activeButton.hasClassName("mBuy")){this.updatePriceFromAjax();}if(LFM.Session.loggedIn&&!this.parentIsLoggedInUser&&button.hasClassName("lfmButtonFortrack")){this.updateMenuFromAjax(this.activeButton);}else{this.showMenu(this.activeButton);}document.observe("click",this.clickOffObserver);},clickOff:function(){this.hideMenu(this.activeButton);this.activeButton.removeClassName("lfmSmallActiveMultiButton");this.activeButton.removeClassName("lfmBigActiveMultiButton");this.activeButton=false;var firstChild=this.menu.down("li.mBuy a span");if(firstChild){firstChild.remove();}document.stopObserving("click",this.clickOffObserver);},updatePriceFromAjax:function(){this.menu.down("li.mBuy a").insert(' <img class="loading" src="'+LFM.Session.staticHost+'/flatness/spinner_13x13.gif" height="7" />');var request=new Ajax.Request("/ajax/affiliableprice",{parameters:{url:this.activeButton.href,cachebuster:Math.round(Math.random()*100)},method:"get",onComplete:function(response){this.menu.down("li.mBuy a img").remove();if(response.responseText){this.menu.down("li.mBuy a").insert(" "+response.responseText);}}.bind(this)});},updateMenuFromAjax:function(button){var button=button;if(this.loadedInfo.get(button.href)){button.className=this.loadedInfo.get(button.href);this.sortOutClassNames(button);this.showMenu(button);}else{var request=new Ajax.Request("/ajax/library/gettrackinfo",{parameters:{url:button.href,cachebuster:Math.round(Math.random()*100)},method:"get",onComplete:function(response){var ajaxResponse=new LFM.Ajax.Response(response);if(ajaxResponse.isSuccess()){if(ajaxResponse.get("loved")){button.removeClassName("mLove");button.addClassName("mUnlove");}else{button.addClassName("mLove");button.removeClassName("mUnlove");}if(ajaxResponse.get("banned")){button.removeClassName("mBan");button.addClassName("mUnban");}else{if(button.hasClassName("lfmMultiButtonAllowBan")){button.addClassName("mBan");}button.removeClassName("mUnban");}if(button.hasClassName("lfmMultiButtonFull")){if(ajaxResponse.get("playcount")!==null){button.addClassName("mRemoveFromLibrary");button.removeClassName("mAddToLibrary");}else{button.removeClassName("mRemoveFromLibrary");button.addClassName("mAddToLibrary");}}this.loadedInfo.set(button.href,button.className);}if(button==this.activeButton&&!request.shown){this.sortOutClassNames(button);this.showMenu(button);}}.bind(this)});(function checkTimeout(){if(!(request&&request.getStatus()==200)&&button==this.activeButton){request.shown=true;this.sortOutClassNames(button);this.showMenu(button);}}).bind(this).delay(0.5);}},showMenu:function(button,options){var options=options||{};var position=button.cumulativeOffset();var pagePosition=$("page").cumulativeOffset();position.left=position.left-7-pagePosition.left;position.top=position.top+button.getHeight()-pagePosition.top;var minwidth=this.activeButton.getWidth();if(Prototype.Browser.IE){if(window.external&&typeof window.XMLHttpRequest=="undefined"){position.left=position.left-35;}else{if(button.hasClassName("lfmSmallMultiButton")&&button.up("div.module")){position.left=position.left-15;}}}this.menu.setStyle({top:position.top+"px",left:position.left+"px"});var list=this.menu.down("ul");minwidth=minwidth-list.getStyle("border-left-width").toPixels()-list.getStyle("border-right-width").toPixels()-list.getStyle("padding-left").toPixels()-list.getStyle("padding-right").toPixels();list.setStyle({minWidth:minwidth+"px"});$w("tr li").each(function(nodeName){var element=button.up(nodeName);if(element){element.addClassName("open");}});var customClass=options.showLoadingState?"mLoading":false;this.sortOutClassNames(button,customClass);this.menu.show();},hideMenu:function(button){$w("tr li").each(function(nodeName){var element=button.up(nodeName);if(element){element.removeClassName("open");}});this.menu.down("ul").setStyle({minWidth:"0px"});this.menu.hide();},sortOutClassNames:function(button,custom){if(custom){this.menu.className=custom;this.menu.down("div").className=custom;}else{var innerClass=button.className.match(/\blfmButtonFor([a-z]*)\b/)[1];innerClass+="MultiMenu";this.menu.className=innerClass;var containerClass=button.className;this.menu.down("div").className=containerClass;}},observeMenu:function(e){e.stop();var clickSource=this.activeButton.hasClassName("lfmBigMultiButton")?"moreBtn":"multiBtn";LFM.Page.Tracker.storeTagSource(clickSource);var action=e.findElement("li").className;if(Prototype.Browser.IE){action=action.replace(/\b\w*hover_/gi,"").strip();}switch(action){case"mSave":LFM.Save({url:this.activeButton.href});break;case"mObsess":LFM.Obsess({url:this.activeButton.href});break;case"mAddToPlaylist":LFM.Playlist({url:this.activeButton.href});break;case"mAddTags":LFM.Tag({url:this.activeButton.href});break;case"mAddToFriends":case"mAddToLibrary":LFM.Add({url:this.activeButton.href});break;case"mRemoveFromLibrary":LFM.RemoveFromLibrary({url:this.activeButton.href},{onDone:function(response){var LibraryDeleteListener=LFM.get("Page","LibraryDeleteListener");var LibraryRemoveTagFromItemListener=LFM.get("Page","LibraryRemoveTagFromItemListener");if(LibraryDeleteListener){LibraryDeleteListener.onDone(response);}if(LibraryRemoveTagFromItemListener){LibraryRemoveTagFromItemListener.onSuccess(response);}}});break;case"mSend":LFM.Send({url:this.activeButton.href});break;case"mEditDetails":location.href=LFM.ParentResource.url+"/settings";break;case"mMessageAll":location.href=LFM.ParentResource.url+"/messageall";break;case"mEditPermissions":location.href=LFM.ParentResource.url+"/permissions";break;case"mAbdicate":location.href=LFM.ParentResource.url+"/abdicate";break;case"mLeave":LFM.Leave({url:this.activeButton.href},{parameters:{leave:1}});break;case"mLove":this.love.bind(this)(this.activeButton,true);break;case"mUnlove":this.love.bind(this)(this.activeButton,false);break;case"mBan":this.ban.bind(this)(this.activeButton,true);break;case"mUnban":this.ban.bind(this)(this.activeButton,false);break;case"mBuy":LFM.BuyDialog({url:this.activeButton.href});break;default:LFM.Page.Tracker.storeTagSource("");break;}this.clickOff();},love:function(href,loved){var button=this.activeButton;new Ajax.Request("/ajax/library/love",{parameters:{ajax:true,url:button.href,loved:loved,formtoken:LFM.Session.formtoken},onSuccess:function(response){var ajaxResponse=new LFM.Ajax.Response(response);if(ajaxResponse.isSuccess()){var tableRow=button.up("tr");var listItem=button.up("li");if(tableRow){if(tableRow.hasClassName("odd")&&tableRow.up("table").hasClassName("chart")){var endcolor="#f4f4f4";}else{var endcolor="#ffffff";}}if((!this.parentIsUser||this.parentIsLoggedInUser)&&tableRow){var lovedContainer=tableRow.down("td.lovedCell");}else{if(LFM.ParentResource&&LFM.ParentResource.type==9&&$("lovedIndicator")){if(loved){if(LFM.Page.onAddToLibrary){LFM.Page.onAddToLibrary(ajaxResponse);}$("lovedIndicator").show();}else{$("lovedIndicator").hide();}}}this.loadedInfo.unset(button.href);if(loved){LFM.Page.Tracker.eventLoveTrack("Page");button.removeClassName("mLove");button.addClassName("mUnlove");if(lovedContainer){lovedContainer.insert({top:LFM.Element.icon_loved_indicator});}if(listItem){listItem.addClassName("loved");}}else{button.addClassName("mLove");button.removeClassName("mUnlove");if(lovedContainer){var lovedIcon=lovedContainer.down("img.loved_indicator_icon");if(lovedIcon){lovedIcon.remove();}}if(listItem){listItem.removeClassName("loved");}}if(lovedContainer){new Effect.Highlight(tableRow,{endcolor:endcolor,afterFinish:function(object){object.element.removeAttribute("style");}});}}}.bind(this)});},ban:function(href,banned){var button=this.activeButton;new Ajax.Request("/ajax/library/ban",{parameters:{ajax:true,url:button.href,banned:banned,formtoken:LFM.Session.formtoken},onSuccess:function(response){var ajaxResponse=new LFM.Ajax.Response(response);if(ajaxResponse.isSuccess()){var tableRow=button.up("tr");if(tableRow){if(tableRow.hasClassName("odd")&&tableRow.up("table").hasClassName("chart")){var endcolor="#f4f4f4";}else{var endcolor="#ffffff";}}if(LFM.ParentResource){if(this.parentIsLoggedInUser&&tableRow){var bannedContainer=tableRow.down("td.bannedCell");}else{if(LFM.ParentResource.type==9&&$("bannedIndicator")){if(banned){$("bannedIndicator").show();}else{$("bannedIndicator").hide();}}}}this.loadedInfo.unset(button.href);if(banned){if(bannedContainer){bannedContainer.insert({top:LFM.Element.icon_banned_indicator});}}else{if(bannedContainer){var bannedIcon=bannedContainer.down("img.banned_indicator_icon");if(bannedIcon){bannedIcon.remove();}}}if(tableRow){new Effect.Fade(tableRow,{duration:0.5});}}}.bind(this)});}},affiliations:{"suppliers[]":[],"restypes[]":[],"resids[]":[]},pushAffiliation:function(supplier,restype,resid){LFM.Button.affiliations["suppliers[]"].push(supplier);LFM.Button.affiliations["restypes[]"].push(restype);LFM.Button.affiliations["resids[]"].push(resid);}});LFM.set("Input",{Captcha:Class.create({captchaId:null,initialize:function(id){this.captchaId=id;$("recaptcha_response_field").observe("focus",function(){$(id).select(".fieldstatus").invoke("show");});},show:function(callback){$(this.captchaId).blindDown({duration:0.5,afterFinish:function(){$("recaptcha_response_field").focus();callback&&callback();}});},hide:function(){$(this.captchaId).blindUp();},isVisible:function(){return $(this.captchaId).visible();},reload:function(){if(typeof Recaptcha==="object"){Recaptcha.reload();}},destroy:function(){Recaptcha.destroy();$("recaptcha_response_field").stopObserving();}})});LFM.set("Charts",{Switch:Class.create({initialize:function(container,parameters){this.container=$(container);this.parameters=parameters;this.morelink=this.container.select("span.moduleOptions a")[0]||false;this.cachedcharts=new Hash();this.container.down("div.horizontalOptions").observe("click",this.switchChartEvent.bindAsEventListener(this));this.container.select("div.chart").each(function(chart){var rangetype=this.getRangeTypeFromClassName(chart.className);if(rangetype){this.cachedcharts.set(rangetype,chart);}}.bind(this));},switchChartEvent:function(event){var clickedLink=event.element();if(!clickedLink.match("a")){return;}event.stop();var listItem=clickedLink.up("li");if(listItem.hasClassName("current")){return;}this.container.down("div.horizontalOptions ul").childElements().invoke("removeClassName","current");listItem.addClassName("current");var rangetype=this.getRangeTypeFromClassName(listItem.className);this.switchChart(rangetype);},refresh:function(){this.cachedcharts=new Hash();this.switchChart();},switchChart:function(rangetype){if(rangetype&&this.cachedcharts.get(rangetype)){this.cachedcharts.each(function(pair){pair.value.hide();});this.cachedcharts.get(rangetype).show();if(this.morelink){this.morelink.href=this.container.down("ul li.chart"+rangetype+" a").href;}}else{var parameters=Object.extend(this.parameters,{rangetype:rangetype,ajax:1,cachebuster:Math.round(Math.random()*100)});new Ajax.Request("/module",{method:"get",parameters:parameters,onComplete:function(t){var response=new LFM.Ajax.Response(t);if(response.isSuccess()){this.container.insert({bottom:response.get("content").strip()});var reset=!rangetype;var newChart=this.container.childElements().last();ieHover.add(newChart);if(!rangetype){rangetype=this.getRangeTypeFromClassName(newChart.className);this.container.down("div.horizontalOptions ul").childElements().invoke("removeClassName","current");this.container.down("div.horizontalOptions ul li.chart"+rangetype).addClassName("current");}this.cachedcharts.set(rangetype,newChart);if(this.morelink){this.morelink.up().insert({before:this.cachedcharts.get(rangetype)});}if(reset){this.container.select("div.chart").each(function(chart){if(chart!=newChart){chart.remove();}}.bind(this));}this.cachedcharts.each(function(pair){if(pair.key!=rangetype){pair.value.hide();}});this.cachedcharts.get(rangetype).show().setStyle({visibility:"visible"});if(this.morelink){this.morelink.href=this.container.down("ul li.chart"+rangetype+" a").href;}this.container.removeClassName("loading");}}.bind(this),onCreate:function(){this.container.addClassName("loading");}.bind(this),onFailure:function(){this.container.removeClassName("loading");}.bind(this)});}},getRangeTypeFromClassName:function(className){var rangetype=className.match(/chart[^ ]+/)[0];return rangetype.substr(5);}})});LFM.set("Display",{CollapsibleBox:Class.create({initialize:function(){var targets=$$(".collapsibleBox");targets.each(function(target){var heading=target.down(".collapsibleBox-heading");target.observe("click",this.clickHandler.bindAsEventListener(this));target.observe("mouseover",this.focusHandler.bindAsEventListener(this));target.observe("mouseout",this.blurHandler.bindAsEventListener(this));var body=target.down(".collapsibleBox-body");var bodyInner=target.down(".collapsibleBox-body-inner");body.observe("transitionend",this.transitionEndHandler.bindAsEventListener(this));body.observe("oTransitionEnd",this.transitionEndHandler.bindAsEventListener(this));body.observe("webkitTransitionEnd",this.transitionEndHandler.bindAsEventListener(this));body.setStyle({height:bodyInner.getHeight()+"px"});if(target.hasClassName("s-closed")){this.deactivate(bodyInner);this.close(target);}else{this.activate(bodyInner);this.open(target);}},this);},open:function(target){var bodyInner=target.select(".collapsibleBox-body-inner")[0];this.activate(bodyInner);target.removeClassName("s-closed");target.addClassName("s-open");Event.fire(target,"CollapsibleBox:open");},close:function(target){if(!Modernizr.csstransitions&&!target.hasClassName("s-hover")){var bodyInner=target.select(".collapsibleBox-body-inner")[0];this.deactivate(bodyInner);}target.removeClassName("s-open");target.addClassName("s-closed");Event.fire(target,"CollapsibleBox:close");},deactivate:function(target){$(target).setStyle({display:"none"});},activate:function(target){$(target).setStyle({display:"block"});},clickHandler:function(e){var target=$(e.target);if(target.hasClassName(".collapsibleBox")){var container=target;}else{var container=target.up(".collapsibleBox");}if(container&&container.hasClassName("s-closed")){e.stop();this.open(container);}else{if(target.hasClassName(".collapsibleBox-heading")||target.up(".collapsibleBox-heading")){e.stop();if(container&&container.hasClassName("s-open")){this.close(container);}else{if(container){this.open(container);}}}}},focusHandler:function(e){var target=$(e.target);if(target.hasClassName("collapsibleBox")){var container=target;}else{var container=target.up(".collapsibleBox");}if(container){var bodyInner=container.select(".collapsibleBox-body-inner")[0];this.activate(bodyInner);container.addClassName("s-hover");}},blurHandler:function(e){var target=$(e.target);if(target.hasClassName("collapsibleBox")){var container=target;}else{var container=target.up(".collapsibleBox");}if(container){if(!Modernizr.csstransitions&&container.hasClassName("s-closed")){var bodyInner=container.select(".collapsibleBox-body-inner")[0];this.deactivate(bodyInner);}container.removeClassName("s-hover");}},transitionEndHandler:function(e){var target=$(e.target);var container=target.up(".collapsibleBox");if(container.hasClassName("s-closed")){if(!container.hasClassName("s-hover")){var bodyInner=container.select(".collapsibleBox-body-inner")[0];this.deactivate(bodyInner);}}}})});document.observe("dom:loaded",function(){new LFM.Display.CollapsibleBox();});LFM.set("Display",{candyStripe:function(container,options){var options=options||false;if(is_array(container)){var rows=container;}else{container=$(container);if(options.selector){var rows=container.select(options.selector);}else{if(container.tagName=="TABLE"){container=container.down("tbody");}var rows=container.childElements();}}if(rows.length>0){rows[0].up("table").addClassName("candyStriped");rows.each(function(row,i){if(i%2){row.removeClassName("odd");}else{row.addClassName("odd");}row.removeClassName("first");row.removeClassName("last");if(options.renumber){var position=row.down("td.position");if(position){position.update(i+1);}}});rows.first().addClassName("first");rows.last().addClassName("last");}},toggleSelector:function(selector){var els=$$(selector);if(els){els.each(function(e){e.toggle();});}}});LFM.set("DomSearch",{findParentByClassName:function(element,regex){if(element==null){return null;}if(element.className&&element.className.match(regex)){return element;}else{return this.findParentByClassName(element.parentNode,regex);}}});document.observe("dom:loaded",function(event){$$(".downloadDriver").each(function(container){container.observe("click",function(e){var el=e.findElement("a");if(el&&el.match("a")){var hasManualAdded=LFM.get("Page","hasManualAdded");var linkName="New user download CTA ("+(hasManualAdded?"after":"before")+" library add)";}});});});LFM.set("Display",{DropDown:Class.create({initialize:function(container,toggler,ddbody,options){this.container=$(container);this.toggler=$(toggler);this.ddbody=$(ddbody);this.ddbody.hide();this.ddbody.setStyle({position:"absolute",zIndex:999999});this.use_iframe=/Linux/.test(navigator.platform);if(this.use_iframe){this.iframe=new Element("iframe",{"src":"javascript: false","frameborder":0,"scrolling":"no","allowtransparency":"true"}).setStyle({position:"absolute",zIndex:999998,border:0});}this.shownOnce=false;this.options=options||{};this.container.addClassName("toggle");this.offBinding=this.clickOff.bindAsEventListener(this);this.toggler.observe("click",this.toggle.bindAsEventListener(this));},hide:function(){if(this.options.onHide){this.options.onHide(this);}if(this.use_iframe){this.iframe.setStyle({"display":"none"});}this.ddbody.hide();this.container.removeClassName("expanded");this.ddbody.removeClassName("lfmDropDown-expanded");Event.stopObserving(document,"click",this.offBinding,true);if(LFM.Display.openDropDown&&LFM.Display.openDropDown==this){LFM.Display.openDropDown=false;}},show:function(){if(LFM.Display.openDropDown){LFM.Display.openDropDown.hide(this);}if(!this.shownOnce){if(this.use_iframe){$("page").insert(this.iframe);}$("page").insert(this.ddbody);this.shownOnce=true;}var position=this.container.cumulativeOffset();var pagePosition=$("page").cumulativeOffset();position.left=position.left-pagePosition.left;position.top=position.top+this.container.getHeight()-pagePosition.top;if(Prototype.Browser.IE&&this.container.getStyle("display")=="inline-block"){var minwidth=this.toggler.getWidth();}else{var minwidth=this.container.getWidth();}var documentWidth=$("page").getWidth();if((this.options.align&&this.options.align=="right")||((position.left+this.ddbody.getWidth())>documentWidth)){var right=(documentWidth-minwidth-position.left)+"px";var left="auto";}else{var left=position.left+"px";var right="auto";if(Prototype.Browser.IE){if(window.external&&typeof window.XMLHttpRequest=="undefined"){left=(position.left-35)+"px";}}}if(!this.options.autoWidth){minwidth=minwidth-this.ddbody.getStyle("border-left-width").toPixels()-this.ddbody.getStyle("border-right-width").toPixels()-this.ddbody.getStyle("padding-left").toPixels()-this.ddbody.getStyle("padding-right").toPixels();this.ddbody.setStyle({minWidth:minwidth+"px"});if(this.use_iframe){this.iframe.setStyle({minWidth:minwidth+"px"});}}this.ddbody.setStyle({top:position.top+"px",left:left,right:right}).show();var body_position=this.ddbody.cumulativeOffset();if(this.use_iframe){this.iframe.clonePosition(this.ddbody);this.iframe.show();}if(this.options.onShow){this.options.onShow(this);}var tr=this.container.up("tr");if(tr){tr.addClassName("open");}LFM.Display.openDropDown=this;this.container.addClassName("expanded");this.ddbody.addClassName("lfmDropDown-expanded");Event.observe(document,"click",this.offBinding,true);},toggle:function(event){if(this.ddbody.visible()){this.hide();}else{this.show();}if(event.findElement("A")){event.findElement("A").blur();}event.stop();},clickOff:function(event){var target=Event.element(event);var cancel=false;while(target.parentNode){if(target==this.ddbody){return true;}else{if(target==this.toggler){cancel=true;}}target=target.parentNode;}this.hide();if(cancel){event.stop();}}})});Event.observe(document,"dom:loaded",function(){if($("message")&&$("editorSubmit")){LFM.set("Page",{editorMessage:$("message").value});window.onbeforeunload=function(){if($("message").value!=LFM.Page.editorMessage&&typeof LFM.Page.Captcha==="undefined"){return LFM.Page.editorWarning;}};Event.observe(document,"click",function(event){if(event.target&&event.target.id=="editorSubmit"){LFM.set("Page",{editorMessage:$("message").value});}});}});var EventCalendar={calendars:null,currentMonth:null,lastRequested:null,next:function(url,anchor,prev){anchor.blur();Element.addClassName(anchor,"busy");var c=EventCalendar.getCurrentMonth();var month=prev?EventCalendar.getPrevMonthAfterTable(c):EventCalendar.getNextMonthAfterTable(c);var next=null;var matches=null;if(!prev){matches=document.getElementsByClassName("month-"+month,$("calendar"));next=matches.length>0?matches[0]:false;}else{var m=EventCalendar.getPrevMonthAfterTable(c);matches=document.getElementsByClassName("month-"+m,$("calendar"));next=matches.length>0?matches[0]:false;}if(next){c.style.display="none";next.style.display="table";EventCalendar.currentMonth=next;Element.removeClassName(anchor,"busy");}else{if(next==-1){Element.removeClassName(anchor,"busy");}else{url=url.replace(/startdate=\d+-\d+-\d+(&)?/,"");url=EventCalendar.convertURL(url);var separator=/\?$/.test(url)?"":"&";EventCalendar.lastRequested=month;var ajax=new Ajax.Request(url+separator+"startdate="+month+"-01",{onSuccess:EventCalendar.receiveMonth.bind(anchor),onFailure:EventCalendar.receiveMonthFailed.bind(anchor)});}}},prev:function(url,anchor){EventCalendar.next(url,anchor,true);},convertURL:function(url){var match=/(events|festivals)/.exec(url);var namespace=new RegExp("^/"+match[1]);url=url.replace(namespace,"");return"/"+match[1]+"/calendar"+url;},receiveMonth:function(transport){if(transport.responseText.indexOf("calendar")==-1){var func=EventCalendar.receiveMonthFailed.bind(this);func();return;}Element.removeClassName(this,"busy");new Insertion.Bottom("calendar",transport.responseText);var matches=document.getElementsByClassName("calendar",$("calendar"));if(matches.length>0){EventCalendar.currentMonth.style.display="none";matches[matches.length-1].style.display="table";EventCalendar.currentMonth=matches[matches.length-1];}},receiveMonthFailed:function(){Element.removeClassName(this,"busy");},getNextMonthAfterTable:function(table){var month=EventCalendar.getMonthForTable(table);var bits=month.split("-");var nextYear=bits[0];var nextMonth=bits[1];if(nextMonth==12){nextMonth=1;nextYear++;}else{nextMonth++;}if(nextMonth<10){nextMonth="0"+nextMonth;}return nextYear+"-"+nextMonth;},getPrevMonthAfterTable:function(table){var month=EventCalendar.getMonthForTable(table);var bits=month.split("-");var prevYear=bits[0];var prevMonth=bits[1];if(prevMonth=="01"){prevMonth=12;prevYear--;}else{prevMonth--;}if(prevMonth<10){prevMonth="0"+prevMonth;}return prevYear+"-"+prevMonth;},getMonthForTable:function(table){if(table.month){return table.month;}var classes=$A(table.className.split(/\s+/));var c=classes.find(function(c){return c.substring(0,5)=="month";});table.month=c.substring(6);return table.month;},getCurrentMonth:function(){if(EventCalendar.currentMonth){return EventCalendar.currentMonth;}EventCalendar.calendars=$A(document.getElementsByClassName("calendar",$("calendar")));EventCalendar.currentMonth=EventCalendar.calendars.find(function(c){return Element.hasClassName(c,"first");});EventCalendar.lastRequested=EventCalendar.getMonthForTable(EventCalendar.currentMonth);return EventCalendar.currentMonth;}};LFM.set("Adserver",{"ExpandingAd":Class.create({inner_id:"",outer_id:"",embed_id:"",adExpandedHeight:0,adExpandedWidth:0,adCollapsedHeight:0,adCollapsedWidth:0,isCollapsing:false,toggleState:false,initialize:function(outer_id,inner_id,embed_id){this.inner_id=inner_id;this.outer_id=outer_id;this.embed_id=embed_id;this.getDimensions();this.setStyles();this.bindEventListeners();},getDimensions:function(){this.adExpandedHeight=$(this.embed_id).getHeight();this.adExpandedWidth=$(this.embed_id).getWidth();this.adCollapsedHeight=$(this.outer_id).getHeight();this.adCollapsedWidth=$(this.outer_id).getWidth();},setStyles:function(){$(this.outer_id).setStyle({"zIndex":0,"overflow":"visible","position":"relative"});$(this.inner_id).setStyle({"zIndex":0,"position":"relative","top":0,"text-align":"center"});},bindEventListeners:function(){var expander=this;$(document).observe("click",function(e){expander.collapse();});$(this.inner_id).observe("click",function(e){e.stop();});$(this.inner_id).observe("mouseover",function(e){expander.isCollapsing=false;if(expander.toggleState){expander.expand();}});$(this.inner_id).observe("mouseout",function(e){if(!expander.isCollapsing){expander.isCollapsing=true;setTimeout(function(){if(expander.isCollapsing){expander.collapse();expander.isCollapsing=false;}},2000);}});$(this.embed_id).observe("focus",function(e){expander.expand();expander.toggleState=true;});$(this.embed_id).observe("blur",function(e){expander.toggleState=false;});},collapse:function(){$(this.outer_id).setStyle({"zIndex":0});$(this.inner_id).setStyle({"zIndex":0,"width":this.adCollapsedWidth+"px","height":this.adCollapsedHeight+"px"});this.isCollapsing=false;},expand:function(){$(this.outer_id).setStyle({"zIndex":99999});$(this.inner_id).setStyle({"zIndex":99999,"width":this.adExpandedWidth+"px","height":this.adExpandedHeight+"px"});}})});LFM.set("Form",{Placeholder:Class.create({nativeSupport:Prototype.Browser.WebKit?true:false,required:true,initialize:function(element,required){if(typeof required!="undefined"){this.required=required;}if(element){this.element=$(element);}if(this.element){if(this.element.match("input")||this.element.match("textarea")){this.setUp(this.element);}else{this.element.select("input[placeholder]").each(function(input){this.setUp(input);}.bind(this));}}else{if(!this.element){$$("input[placeholder]").each(function(input){this.setUp(input);}.bind(this));}}},setText:function(input,text){input.setAttribute("placeholder",text);if(!this.nativeSupport||input.match("textarea")){if($F(input)==""||input.hasClassName("hint")){input.addClassName("hint");input.value=text;}}},clearPlaceholder:function(input,indicator){if($F(input)==input.getAttribute("placeholder")){input.removeClassName("hint");input.value="";}indicator.disabled=true;},resetPlaceholder:function(input,indicator){if(!$F(input).strip()){input.addClassName("hint");input.value=input.getAttribute("placeholder");indicator.disabled=false;}},setUp:function(input){this.setText(input,input.getAttribute("placeholder"));if(!this.nativeSupport||input.match("textarea")){var indicator=new Element("input",{"type":"hidden","name":"placeholder","value":1});input.insert({after:indicator});input.observe("focus",function(e){this.clearPlaceholder(input,indicator);}.bind(this));input.observe("blur",function(e){this.resetPlaceholder(input,indicator);}.bind(this));if(this.required){var form=input.up("form");form.observe("submit",function(e){this.clearPlaceholder(input,indicator);}.bind(this));}}}})});LFM.set("Form",{focusToRange:0,focusTo:function(element,selectFrom){if(typeof selectFrom=="undefined"){selectFrom=element.value.length;}if(element.createTextRange){if(LFM.Form.focusToRange==0){LFM.Form.focusToRange=element.createTextRange();}LFM.Form.focusToRange.moveEnd("character",element.value.length);LFM.Form.focusToRange.moveStart("character",selectFrom);setTimeout("LFM.Form.focusToRange.select()",10);}else{if(element.setSelectionRange){element.focus();element.select();element.setSelectionRange(selectFrom,element.value.length);}else{element.focus();}}}});LFM.set("Form",{CustomSelect:Class.create({config:{replacedClass:"customSelect-replaced",customSelectClass:"customSelect-dummy",customSelectWrapperClass:"customSelect-dummy-wrap",customSelectTextClass:"customSelect-text",activeClass:"s-active",wrapperElementClass:"customSelect-wrap"},initialize:function(target){if(!$$("body")[0].hasClassName("ie6")){if(typeof target=="string"){$$(target).each(function(selectElem){this._initializeOne(selectElem);},this);}else{if(target.each){target.each(function(selectElem){this._initializeOne(selectElem);},this);}else{this._initializeOne(target);}}}},_initializeOne:function(target){target.addClassName(this.config.replacedClass);target.wrap("div",{"class":this.config.wrapperElementClass});var span=new Element("span",{"class":this.config.customSelectClass,"aria-hidden":true}).insert({top:new Element("span",{"class":this.config.customSelectWrapperClass}).insert({top:new Element("span",{"class":this.config.customSelectTextClass})})});target.insert({after:span});target.observe("change",this.changeListener.bindAsEventListener(this));target.observe("keyup",this.changeListener.bindAsEventListener(this));target.observe("CustomSelect:change",this.changeListener.bindAsEventListener(this));target.observe("mouseenter",this.setActive.bindAsEventListener(this));target.observe("mouseleave",this.setInactive.bindAsEventListener(this));target.observe("focus",this.setActive.bindAsEventListener(this));target.observe("blur",this.setInactive.bindAsEventListener(this));this.update(target);this.setWidth(target);},update:function(target){var selectedOption=target.select("option:selected")[0];var val;if(selectedOption.hasAttribute("label")){val=selectedOption.readAttribute("label");}else{val=selectedOption.innerHTML;}var textElem=target.up().select("."+this.config.customSelectTextClass)[0];textElem.update(val);var customSelectElem=target.up().select("."+this.config.customSelectClass)[0];if(target.disabled){customSelectElem.addClassName("s-disabled");}else{customSelectElem.removeClassName("s-disabled");}},changeListener:function(e){var target=$(e.target);this.update(target);this.setWidth(target);},setActive:function(e){var target=$(e.target);target.up("."+this.config.wrapperElementClass).select("."+this.config.customSelectClass)[0].addClassName(this.config.activeClass);},setInactive:function(e){var target=$(e.target);target.up("."+this.config.wrapperElementClass).select("."+this.config.customSelectClass)[0].removeClassName(this.config.activeClass);},setWidth:function(target){target.setStyle({width:""});realWidth=target.getWidth();target.setStyle({width:realWidth+22+"px"});}})});document.observe("dom:loaded",function(){new LFM.Form.CustomSelect("select.customSelect");});LFM.set("Form",{MasterSlaveSelectBox:Class.create({initialize:function(target){if(typeof target=="string"){$$(target).each(function(selectElem){this._initializeOne(selectElem);},this);}else{if(target.each){target.each(function(selectElem){this._initializeOne(selectElem);},this);}else{this._initializeOne(target);}}},_initializeOne:function(target){var selectedOption=target.getValue();var selectedOptionElem=target.select("option:selected")[0];var selectedGroup=selectedOptionElem.up().readAttribute("label");var optgroups=target.select("optgroup");var groups=new Hash();optgroups.each(function(optgroupElem,index){var opts=optgroupElem.select("option");var optsCloned=[];opts.each(function(opt){clonedOpt=opt.clone(true);if(opt==selectedOptionElem){clonedOpt.writeAttribute("selected","selected");}optsCloned.push(clonedOpt);});groups.set(optgroupElem.readAttribute("label"),optsCloned);});var master=new Element("select",{"id":target.readAttribute("id")+"-master"});groups.each(function(group){var newOption=new Element("option");master.insert({bottom:newOption.update(group.key)});});master.setValue(selectedGroup);target.insert({after:master});var slave=new Element("select",{"id":target.readAttribute("id")+"-slave"});Element.hide(target);var targetId=target.readAttribute("id");$$('label[for="'+targetId+'"]')[0].writeAttribute("for","");master.insert({before:slave});target.store("MasterSlaveSelectBox.master",master);target.store("MasterSlaveSelectBox.slave",slave);master.store("MasterSlaveSelectBox.slave",slave);slave.store("MasterSlaveSelectBox.master",master);slave.store("MasterSlaveSelectBox.groups",groups);slave.store("MasterSlaveSelectBox.original",target);master.observe("change",this.masterChangeListener.bindAsEventListener(this));master.observe("keyup",this.masterChangeListener.bindAsEventListener(this));slave.observe("change",this.slaveChangeListener.bindAsEventListener(this));slave.observe("keyup",this.slaveChangeListener.bindAsEventListener(this));slave.observe("MasterSlaveSelectBox:change",this.slaveChangeListener.bindAsEventListener(this));this.update(master);},update:function(target){var selectedGroup=target.getValue();var slave=target.retrieve("MasterSlaveSelectBox.slave");var groups=slave.retrieve("MasterSlaveSelectBox.groups");slave.update();groups.get(selectedGroup).each(function(optionElem){slave.insert(optionElem);});this.updateOriginal(slave);Event.fire(slave,"CustomSelect:change");},updateOriginal:function(target){var original=target.retrieve("MasterSlaveSelectBox.original");original.setValue(target.getValue());},masterChangeListener:function(e){var target=$(e.target);this.update(target);},slaveChangeListener:function(e){var target=$(e.target);this.updateOriginal(target);}})});LFM.set("FullLengthPlayer",Class.create({soundManager:null,wrapperID:"fullLengthPreview",progressID:"fullLengthPreviewProgressBar",activeClass:"active",wrapperElement:null,progressElement:null,controlElement:null,oTrack:null,sound:null,oScrobbler:null,scrobblePoint:null,hasScrobbled:false,initialize:function(soundManager,oTrack,oScrobbler){this.soundManager=soundManager;this.oTrack=oTrack;this.oScrobbler=oScrobbler;this.soundManager.onready(this.apply.bind(this));},apply:function(){if(this.soundManager.supported()){this.wrapperElement=$(this.wrapperID);this.progressElement=$(this.progressID);if(this.wrapperElement&&this.progressElement){this.controlElement=this.wrapperElement.down("a");this.controlElement.observe("click",this.onClick.bindAsEventListener(this));this.scrobblePoint=this.oScrobbler.getScrobblePoint(this.oTrack);if(this.wrapperElement.hasClassName("autoplay")){this.play();}}}},show:function(){this.progressElement.slideDown({duration:0.4});},hide:function(){this.progressElement.slideUp({duration:0.4});},getAudioURL:function(){var audioURL=this.controlElement.getAttribute("href");if(!audioURL.endsWith(".mp3")){audioURL=this.decodeAudioURL(this.controlElement.getAttribute("data-track-scrabble"));}return audioURL;},decodeAudioURL:function(encoded){return"http://"+encoded.split("").reverse().join("")+".mp3";},play:function(){var trackID="sound_"+this.oTrack.id;this.soundManager.stopAll();this.setPlaybackCounter(0);this.hasScrobbled=false;this.show();this.wrapperElement.addClassName(this.activeClass);this.sound=this.soundManager.getSoundById(trackID);if(this.sound){this.sound.play();}else{this.sound=this.soundManager.createSound({id:trackID,url:this.getAudioURL(),onfinish:this.onStop.bind(this),ondataerror:this.onError.bind(this),onstop:this.onStop.bind(this),whileplaying:this.onPlayback.bind(this),autoPlay:true});}this.oScrobbler.sendNowPlaying(this.oTrack);LFM.Page.Tracker.eventPlayTrack("Full length");},stop:function(){this.sound.stop();this.sound=null;this.hide();this.wrapperElement.removeClassName(this.activeClass);},setPlaybackCounter:function(seconds){seconds=Math.min(seconds,this.oTrack.duration);this.progressElement.down(".duration").innerHTML=LFM.timeFormat(seconds);},onStop:function(){this.stop();},onClick:function(event){event.preventDefault();this.controlElement.blur();if(this.sound==null){this.play();}else{this.stop();}},onPlayback:function(){var position=this.sound.position/1000;var width=(100/this.oTrack.duration)*position;this.setPlaybackCounter(position);this.progressElement.down(".bar").setStyle({"width":width+"%"});if(!this.hasScrobbled&&position>this.scrobblePoint){this.oScrobbler.sendScrobble(this.oTrack,this.onScrobble.bind(this));this.hasScrobbled=true;}},onError:function(){this.stop();},onScrobble:function(){LFM.log("Scrobbled track");}}));document.observe("dom:loaded",function(){new LFM.FullLengthPlayer(LFM.SoundManager.getInstance(),LFM.ParentResource,LFM.Scrobbler);});LFM.set("Display",{setupHeader:function(){if(LFM.Session.loggedIn){$("idBadger").addClassName("withDropDown");LFM.set("Page",{navDropDown:new LFM.Display.DropDown("idBadger","idBadgerDropper","idBadgerDropDown",{align:"right"})});}new LFM.Form.Placeholder("siteSearchBox");LFM.Links.setupPost("logoutLink");},colourToggle:function(link){link=$(link);$(document.body).toggleClassName("lfmBlack");link.blur();var fromColour,toColour;if($(document.body).hasClassName("lfmBlack")){fromColour="red";toColour="black";link.update(LFM.String.toRedStr);LFM.Page.Tracker.eventPaintItBlack();}else{fromColour="black";toColour="red";link.update(LFM.String.toBlackStr);LFM.Page.Tracker.eventSimplyRed();}LFM.setCookie("LFM_Colour",toColour);return false;}});if((Math.round(Math.random()*100)>98)&&(LFM.get("Button","affiliations"))&&(LFM.Button.affiliations["suppliers[]"].length)){document.observe("dom:loaded",function(event){var url="/ajax/affiliableLookup?";new Ajax.Request(url,{method:"post",parameters:LFM.Button.affiliations});});}function log(){if(typeof console!=="undefined"&&LFM&&LFM.get("config","DEVELOPMENT_SERVER")){if(console.log.apply){console.log.apply(console,arguments);}else{console.log(arguments[0]);}}}LFM.set("Display",{setMinHeight:function(){document.observe("dom:loaded",function(){var secondaryNavigation=$("secondaryNavigation");if(secondaryNavigation){var minHeight=secondaryNavigation.getHeight()-2;var content=$("content");if(content&&content.getHeight()<minHeight){var container=$$("#content > .rightCol");container=container[0]||content;if(container.match(".rightCol")){content.setStyle("min-height: 0");}minHeight-=container.getStyle("padding-top").toPixels(container);minHeight-=container.getStyle("padding-bottom").toPixels(container);container.setStyle({minHeight:(minHeight>300?minHeight:300)+"px"});}}});},addImageOrientationClass:function(targetSelector){var isImageOk=function(img){if(!img.complete){return false;}if(typeof img.naturalWidth!="undefined"&&img.naturalWidth==0){return false;}return true;};var setOriantationClass=function(item,image){var dimensions=image.getDimensions();if(dimensions.width>dimensions.height){item.addClassName("landscape");}else{item.addClassName("portrait");}};$$(targetSelector).each(function(item){var image=item.select("img")[0];var checkImage=function(){if(isImageOk(image)){item.removeClassName("rankItem-imageCrop-hidden");setOriantationClass(item,image);}else{setTimeout(checkImage,500);}};checkImage();});}});if(LFM&&LFM.get("config","DEVELOPMENT_SERVER")){LFM.set("Timers",{});}function startTimer(name){if(LFM&&LFM.get("config","DEVELOPMENT_SERVER")){LFM.Timers[name]={};LFM.Timers[name].startTime=new Date();LFM.Timers[name].startTime=LFM.Timers[name].startTime.getTime();}}function stopTimer(name){if(LFM&&LFM.get("config","DEVELOPMENT_SERVER")){if(LFM.Timers[name]){LFM.Timers[name].endTime=new Date();LFM.Timers[name].endTime=LFM.Timers[name].endTime.getTime();log(LFM.Timers[name].endTime-LFM.Timers[name].startTime);}else{log("Timer "+name+" doesn’t exist.");}}}function loadStyleSheet(styleSheetURL){if(isset(document.createStyleSheet)){document.createStyleSheet(styleSheetURL);}else{var styleSheetLink=document.createElement("link");styleSheetLink.setAttribute("rel","stylesheet");styleSheetLink.setAttribute("type","text/css");styleSheetLink.setAttribute("href",styleSheetURL);document.getElementsByTagName("head")[0].appendChild(styleSheetLink);}}function is_array(obj){return obj.constructor==Array;}function isset(obj){return typeof obj!=="undefined";}String.prototype.pad=function(pad_length,pad_string,pad_type){if(pad_length){pad_length=pad_length-this.length;}else{return this;}var input=this;if(pad_string){pad_string=pad_string+"";}else{pad_string=" ";}if(!isset(pad_type)){pad_type="STR_PAD_LEFT";}if(pad_type=="STR_PAD_BOTH"){var odd=pad_length%2;var side=pad_length/2;side=Math.round(side);var left=pad_string.times(side);var right=pad_string.times(side-odd);input=left+input+right;}else{var pad_string=pad_string.times(pad_length);if(pad_type=="PAD_STR_RIGHT"){input=input+pad_string;}else{input=pad_string+input;}}return input;};Number.prototype.toPixels=function(){return this;};String.prototype.toPixels=function(reference){var size=this.match(/^(-?)(\d+(?:.\d+)?)(px|pt|em|)$/i);var negative=size[1]?-1:1;var value=size[2];var unit=size[3].toLowerCase();function rule(value,unit){var ruler=document.getElementById(unit+"Ruler");if(!ruler){ruler=document.createElement("div");document.getElementsByTagName("BODY")[0].appendChild(ruler);ruler.id=unit+"Ruler";}ruler.style.width=value+unit;return ruler.clientWidth*negative;}switch(unit){case"px":return value*negative;case"pt":return rule(value,unit);case"em":if(!reference){log("It’s better to give a reference element when calculating pixels from ems");return rule(value,unit);}else{var ruler=document.createElement(reference.tagName);ruler.style.display="block";ruler.style.position="absolute";ruler.style.left="-9999px";ruler.style.top="-9999px";ruler.style.height="0";ruler.style.padding="0";ruler.style.border="0";ruler.style.width=value+unit;reference.parentNode.appendChild(ruler);returnValue=ruler.clientWidth;reference.parentNode.removeChild(ruler);return returnValue*negative;}default:return value*negative;}};var CSSUtils={getCSSRule:function(ruleName,deleteFlag){ruleName=ruleName.toLowerCase();if(document.styleSheets){for(var i=0;i<document.styleSheets.length;i++){var styleSheet=document.styleSheets[i];var ii=0;var cssRule=false;do{if(styleSheet.cssRules){cssRule=styleSheet.cssRules[ii];}else{cssRule=styleSheet.rules[ii];}if(cssRule){if(cssRule.selectorText.toLowerCase()==ruleName){if(deleteFlag=="delete"){if(styleSheet.cssRules){styleSheet.deleteRule(ii);}else{styleSheet.removeRule(ii);}return true;}else{return cssRule;}}}ii++;}while(cssRule);}}return false;},killCSSRule:function(ruleName){return CSSUtils.getCSSRule(ruleName,"delete");},addCSSRule:function(ruleName){if(document.styleSheets){if(!CSSUtils.getCSSRule(ruleName)){if(document.styleSheets[0].addRule){document.styleSheets[0].addRule(ruleName,null,0);}else{document.styleSheets[0].insertRule(ruleName+" { }",0);}}}return CSSUtils.getCSSRule(ruleName);}};function actsAsAspect(object){object.yield=null;object.rv={};object.before=function(method,f){var original=eval("this."+method);this[method]=function(){f.apply(this,arguments);return original.apply(this,arguments);};};object.after=function(method,f){var original=eval("this."+method);this[method]=function(){this.rv[method]=original.apply(this,arguments);return f.apply(this,arguments);};};object.around=function(method,f){var original=eval("this."+method);this[method]=function(){this.yield=original;return f.apply(this,arguments);};};}var ieHover={selector:"tr, li",add:function(stuff){if(!(/MSIE (5|6|8)/).test(navigator.userAgent)){return;}var stuff=stuff||false;if(Object.isString(stuff)&&$(stuff)){$(stuff).select(ieHover.selector).each(function(item){ieHover.prepareItem(item);});}else{if(Object.isElement(stuff)){stuff=$(stuff);if(stuff.match("tr, li")){ieHover.prepareItem(stuff);}else{stuff.select(ieHover.selector).each(function(item){ieHover.prepareItem(item);});}}else{if(Object.isArray(stuff)){stuff.each(function(item){ieHover.prepareItem(item);});}}}},prepareItem:function(item){item.observe("mouseenter",ieHover.mouseOver);item.observe("mouseleave",ieHover.mouseOut);},mouseOver:function(event){this.className=this.className.replace(/(\S+)/g,"$1 $1hover_")+" hover_";},mouseOut:function(event){this.className=this.className.replace(/(\S+)?hover_(\S+)?/g,"").replace(/\s+/g," ");},setUp:function(){if(!(/MSIE (5|6|8)/).test(navigator.userAgent)){return;}var hoverStyleSheet=document.createStyleSheet();var rulesToAdd=[];var currentSheet;var sheets=document.styleSheets,l=sheets.length;for(var i=0;i<l;i++){parseStylesheet(sheets[i]);}function parseStylesheet(sheet){if(sheet.imports){try{var imports=sheet.imports,l=imports.length;for(var i=0;i<l;i++){parseStylesheet(sheet.imports[i]);}}catch(securityException){}}try{var rules=(currentSheet=sheet).rules;var l=rules.length;var select=false;var style=false;for(var j=0;j<l;j++){select=rules[j].selectorText;style=rules[j].style.cssText;if(select.match(/(tr|li)(\.(\w*))*:hover/ig)&&style){rulesToAdd.push([select.replace(/(tr|li)(\.(\w*))*:hover/ig,"$1.$3hover_"),style]);}}}catch(securityException){}}var cssText="";for(var i=rulesToAdd.length-1;i>=0;i--){cssText+=rulesToAdd[i][0]+"\n{ "+rulesToAdd[i][1]+"}\n";}hoverStyleSheet.cssText=cssText;var items=[];var page=$("page");ieHover.selector.split(",").each(function(weee){items.push($A(page.getElementsByTagName(weee.strip())));});items=items.flatten();var i=items.length-1;for(i;i>=0;i--){Event.observe(items[i],"mouseenter",ieHover.mouseOver);Event.observe(items[i],"mouseleave",ieHover.mouseOut);}}};LFM.set("Help",{popup:function(id){var url="/popups/faq/?id="+id;faq=window.open(url,"faq","toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=yes, resizable=yes, width=350, height=400");return false;}});HighlightEachOther=Class.create({initialize:function(el1,tag1,el2,tag2){this.els=[$(el1).select(tag1),$(el2).select(tag2)].flatten();this.els.each(function(el){el.observe("mouseover",function(e){this.highlight(el);}.bindAsEventListener(this));el.observe("mouseout",function(e){this.highlight(el);}.bindAsEventListener(this));}.bind(this));},highlight:function(el){var el=el;if(!el.relatives){this.getRelatives(el);}el.relatives.each(function(_1b4){Element.toggleClassName(_1b4,"highlight");});},getRelatives:function(el){el.relatives=new Array();var rel=el.readAttribute("class");this.els.each(function(item){if(item.readAttribute("class")==rel){el.relatives.push(item);}});}});LFM.set("Page",{"InlineTabSwitcher":Class.create({initialize:function(namespace){this.menu=$(namespace+"Tabs");this.namespace=namespace;if(!this.menu){LFM.log("couldn't find #"+namespace+"Tabs, InlineTabSwitcher not created");return;}var switcher=this;this.menu.observe("click",function(event){Event.stop(event);var li=event.findElement("li");if(li&&li.match("li")){switcher.switchTabs(li);var anchor=li.select("a");if(anchor&&anchor.length){anchor[0].blur();}}});var menuItems=this.menu.select("li");if(menuItems&&menuItems.length){var hash=window.location.hash?window.location.hash.replace(/#/,""):"";var activeTab=null;menuItems.each(function(menuItem){switcher._getContentContainerForTab(menuItem).hide();if(menuItem.hasClassName("current")){activeTab=menuItem;}else{if(menuItem.hasClassName("tabident-"+hash)){activeTab=menuItem;}}});if(!activeTab){activeTab=menuItems[0];}this.switchTabs(activeTab);}},switchTabs:function(li){var menuItems=this.menu.select("li");var switcher=this;menuItems.each(function(menuItem){if(menuItem==li){menuItem.addClassName("current");switcher._getContentContainerForTab(menuItem).show();}else{menuItem.removeClassName("current");switcher._getContentContainerForTab(menuItem).hide();}});var matches=li.className.match(/tabident-([^ "]+)/);if(matches&&matches.length>=2){var tabident=matches[1].replace(/hover_/g,"");var loc=window.location;var url=loc.toString().replace(/\#.*/,"");loc.replace(url+"#"+tabident);}},_getContentContainerForTab:function(li){var contentId=this.namespace+li.id.replace("Tab","").capitalize();return $(contentId);}})});Ajax.JSONRequest=Class.create(Ajax.Base,(function(){var id=0,head=document.getElementsByTagName("head")[0];return{initialize:function($super,url,options){$super(options);this.options.url=url;this.options.callbackParamName=this.options.callbackParamName||"callback";this.options.timeout=this.options.timeout||10;this.options.invokeImmediately=(!Object.isUndefined(this.options.invokeImmediately))?this.options.invokeImmediately:true;if(this.options.invokeImmediately){this.request();}},_cleanup:function(){if(this.timeout){clearTimeout(this.timeout);this.timeout=null;}if(this.transport&&Object.isElement(this.transport)){this.transport.remove();this.transport=null;}},request:function(){var response=new Ajax.JSONResponse(this);var key=this.options.callbackParamName,name="_prototypeJSONPCallback_"+(id++),complete=function(){if(Object.isFunction(this.options.onComplete)){this.options.onComplete.call(this,response);}Ajax.Responders.dispatch("onComplete",this,response);}.bind(this);this.options.parameters[key]=name;var url=this.options.url+((this.options.url.include("?")?"&":"?")+Object.toQueryString(this.options.parameters));window[name]=function(json){this._cleanup();window[name]=undefined;response.status=200;response.statusText="OK";response.setResponseContent(json);if(Object.isFunction(this.options.onSuccess)){this.options.onSuccess.call(this,response);}Ajax.Responders.dispatch("onSuccess",this,response);complete();}.bind(this);this.transport=new Element("script",{type:"text/javascript",src:url});if(Object.isFunction(this.options.onCreate)){this.options.onCreate.call(this,response);}Ajax.Responders.dispatch("onCreate",this);head.appendChild(this.transport);this.timeout=setTimeout(function(){this._cleanup();window[name]=Prototype.emptyFunction;if(Object.isFunction(this.options.onFailure)){response.status=504;response.statusText="Gateway Timeout";this.options.onFailure.call(this,response);}complete();}.bind(this),this.options.timeout*1000);},toString:function(){return"[object Ajax.JSONRequest]";}};})());Ajax.JSONResponse=Class.create({initialize:function(request){this.request=request;},request:undefined,status:0,statusText:"",responseJSON:undefined,responseText:undefined,setResponseContent:function(json){this.responseJSON=json;this.responseText=Object.toJSON(json);},getTransport:function(){if(this.request){return this.request.transport;}},toString:function(){return"[object Ajax.JSONResponse]";}});LFM.set("LiveSwitch",Class.create({initialize:function(element,options){this.element=$(element);this.options={selectedClass:"selected"};Object.extend(this.options,options);this.items=this.element.select("li");this.items.each(function(li){var a=li.down("a");a.observe("click",this.dispatchOnChange.bindAsEventListener(this));}.bind(this));},dispatchOnChange:function(event){event.stop();event.element().blur();var li=event.findElement("li");this.items.invoke("removeClassName",this.options.selectedClass);li.addClassName(this.options.selectedClass);this.options.onChange(li);}}));LFM.set("Module",{Buttons:Class.create({initialize:function(container,options){this.container=$(container);if(options){Object.extend(this,options);}if(!this.onComplete){this.onComplete=this._defaultOnComplete;}if(!this.resource){this.resource=LFM.ParentResource;}this.container.observe("click",this.observeMenu.bindAsEventListener(this));},observeMenu:function(event){var link=event.findElement("a");if(!link){return;}if(link.hasClassName("mEdit")){event.stop();var url="/ajax/dialog/moduleedit?module="+this.moduleName;this._dialog=new LFM.Dialog({action:url,classname:"modulePreferences",onConfirm:this._onConfirmDialog.bindAsEventListener(this)});this._dialog.show(url);}else{if(link.hasClassName("mFeeds")){event.stop();var params={module:this.moduleName,type:this.resource.type,id:this.resource.id};var url="/ajax/dialog/feeds?"+Object.toQueryString(params);this._dialog=new LFM.Dialog({classname:"feedDialog",onConfirm:function(event){event.stop();this.hide();}});this._dialog.show(url);}else{if(link.hasClassName("mPaste")){event.stop();var tablink=$$(".modulechartsartists li.current a")[0].getAttribute("href");var regex=/rangetype=([^&]*)/;var charttype=tablink.match(regex)[1];var params={module:this.moduleName,type:this.resource.type,id:this.resource.id,period:charttype};var url="/ajax/dialog/pasteyourtaste?"+Object.toQueryString(params);this._dialog=new LFM.Dialog({classname:"pasteDialog",onConfirm:function(event){event.stop();this.hide();}});this._dialog.show(url);}}}},_defaultOnComplete:function(){if(this.container.down(".module-body")){var url="/module";var params={method:"get",parameters:{name:this.moduleName,ajax:1},onComplete:this._defaultRefreshCallback.bind(this),onCreate:function(){this.container.addClassName("loading");}.bind(this),onFailure:function(){this.container.removeClassName("loading");}.bind(this)};new Ajax.Request(url,params);}},_onConfirmDialog:function(event,form){event.stop();if(form){form.action="/ajax/dialog/moduleedit?module="+this.moduleName;form.request({onComplete:this.onComplete.bind(this)});}else{this._dialog.hide();this._dialog.overlayForm.request({onComplete:this.onComplete.bind(this)});}},_defaultRefreshCallback:function(transport){var response=new LFM.Ajax.Response(transport);if(response.isSuccess()){this.container.down(".module-body").replace(response.get("content"));}else{this.container.removeClassName("loading");}}}),onRefresh:function(containerid,callback){if(!LFM.Module.refreshers){LFM.Module.refreshers={};}LFM.Module.refreshers[containerid]=callback;}});LFM.set("Button",{MultiButtonIcons:Class.create({initialize:function(){$$("body")[0].observe("click",this.clickHandler.bindAsEventListener(this));this.addBuyButtons();},clickHandler:function(e){var target=$(e.target);if(target.hasAttribute("data-source")){e.stop();var dataSource=$(target.getAttribute("data-source"));var resource={id:dataSource.getAttribute("data-res-id"),type:dataSource.getAttribute("data-res-type")};var container=dataSource;var className=target.up("li").className;var regex=/(multiButtonIcons-action-([^\s]+)\s?)/;var action=regex.exec(className)[2];switch(action){case"love":this.love(container,resource);break;case"unlove":this.unlove(container,resource);break;case"addLibrary":this.addLibrary(container,resource);break;case"removeLibrary":this.removeLibrary(container,resource);break;case"buy":this.buy(container,resource);break;case"tag":this.tag(container,resource);break;case"share":this.share(container,resource);break;case"playlist":this.playlist(container,resource);break;}}},love:function(container,resource){container.down(".multiButtonIcons-action-love").addClassName("multiButtonIcons-hidden");container.down(".multiButtonIcons-action-unlove").removeClassName("multiButtonIcons-hidden");if(resource){LFM.Love(resource,{onDone:function(){LFM.Page.Tracker.eventLoveTrack("Page");},onError:function(){this.unlove(container);}});}},unlove:function(container,resource){container.down(".multiButtonIcons-action-unlove").addClassName("multiButtonIcons-hidden");container.down(".multiButtonIcons-action-love").removeClassName("multiButtonIcons-hidden");if(resource){LFM.Unlove(resource,{onError:function(){this.love(container);}});}},addLibrary:function(container,resource){if(resource){LFM.Add(resource,{onDone:function(){container.down(".multiButtonIcons-action-addLibrary").addClassName("multiButtonIcons-hidden");container.down(".multiButtonIcons-action-removeLibrary").removeClassName("multiButtonIcons-hidden");}});}},removeLibrary:function(container,resource){if(resource){LFM.RemoveFromLibrary(resource,{onDone:function(){container.down(".multiButtonIcons-action-removeLibrary").addClassName("multiButtonIcons-hidden");container.down(".multiButtonIcons-action-addLibrary").removeClassName("multiButtonIcons-hidden");}});}},buy:function(container,resource){if(resource){LFM.BuyDialog(resource);}},tag:function(container,resource){if(resource){LFM.Tag(resource);}},share:function(container,resource){if(resource){LFM.Send(resource);}},playlist:function(container,resource){if(resource){LFM.Playlist(resource);}},addBuyButtons:function(){var buyButton=$$(".multiButtonIcons-action-buy");buyButton.each(function(item){var resource={};if(item.hasAttribute("data-res-id")){resource.id=item.getAttribute("data-res-id");}else{resource.id=item.up("*[data-res-id]").getAttribute("data-res-id");}if(item.hasAttribute("data-res-type")){resource.id=item.getAttribute("data-res-type");}else{resource.type=item.up("*[data-res-type]").getAttribute("data-res-type");}var params=Object.extend({cachebuster:Math.round(Math.random()*100)},resource);var request=new Ajax.Request("/ajax/affiliablepricejson",{parameters:params,method:"get",onComplete:function(response){if(response.responseJSON.data.affiliable){item.removeClassName("multiButtonIcons-hidden");if(typeof response.responseJSON.data.lowestPriceString=="string"){var textContainer=item.select(".tooltip-text")[0];textContainer.update(textContainer.innerHTML+" ("+response.responseJSON.data.lowestPriceString+")");}}}.bind(this)});});}})});document.observe("dom:loaded",function(){new LFM.Button.MultiButtonIcons();});LFM.set("Display",{MultiTuner:Class.create({initialize:function(form,options){this.uuid=Math.round(Math.random()*100000);this.form=$(form);this.restype=options.restype;this.sampleContent=$(options.sampleContent);this.slotID=options.slotID||"slot"+this.uuid;this.slotClass=options.slotClass||"";this.choices=$(options.choices);this.autocomplete=$(options.autocomplete);this.length=options.length||3;this.itemClass=options.itemClass||"";this.onSelect=options.onSelect;this.onDeselect=options.onDeselect;this.onResourceJSON=options.onResourceJSON;this.slots=this.setupSlots(this.length);this.selections=$H();this.matching_choices=$H();this.filled=0;this.setupListeners();},setupListeners:function(){if(!LFM.get("Session","prefersClient")&&!this.form.down("input[name=ajax]")){this.form.insert(new Element("input",{"type":"hidden","name":"ajax","value":1}));}if(this.choices){this.choices.observe("click",function(e){e.stop();var item=e.findElement("li");this.select(item.down("a").innerHTML.unescapeHTML());}.bind(this));}if(this.autocomplete){this.autocomplete.observe("submit",function(e){e.stop();var form_fields=this.autocomplete.serialize(true);if(!form_fields.placeholder&&form_fields.name){this.select(form_fields.name.unescapeHTML());this.autocomplete.down("input[name=name]").value="";}}.bind(this));}},setupSlots:function(slots){var that=this;var numbers=$A($R(1,slots));numbers.reverse(false).each(function(i){if(!$(that.slotID+i)){var slot=new Element("div",{"id":that.slotID+i,"class":that.slotClass});that.form.insert({top:slot});}});return numbers.inject($H(),function(hash,i){hash.set(i,false);return hash;});},generate_item_id:function(content){return"item"+this.uuid+"_"+content.toLowerCase().replace(/_/g,"__").replace(/ /g,"_");},updateSampleContent:function(){if(this.sampleContent&&this.restype){var sampleContentContainer=this.sampleContent.up("p");if(!this.filled){sampleContentContainer.hide();sampleContentContainer.next("p.noSampleContent").hide();this.sampleContent.update();}else{var that=this;new Ajax.Request("/listen/tune",{parameters:Object.extend({"ajax":1},this.form.serialize(true)),onComplete:function(transport){var response=new LFM.Ajax.Response(transport);if(response.isError()){var sampleContentContainer=that.sampleContent.up("p");that.sampleContent.update();sampleContentContainer.hide();sampleContentContainer.next("p.noSampleContent").hide();sampleContentContainer.next("p.sampleContentError").show();}else{var sampleData=response.get("sampleContent");var sampleContentContainer=that.sampleContent.up("p");if(sampleData&&sampleData.items&&sampleData.items.length){var sampleContent=sampleData.items.inGroupsOf(3)[0].collect(function(item){if(!item){throw $break;}return item.res.name;}).join(", ");that.sampleContent.update(sampleContent);sampleContentContainer.next("p.noSampleContent").hide();sampleContentContainer.next("p.sampleContentError").hide();sampleContentContainer.show();}else{that.sampleContent.update();sampleContentContainer.hide();sampleContentContainer.next("p.sampleContentError").hide();sampleContentContainer.next("p.noSampleContent").show();}}}});}}},fetchResourceJSON:function(content,slot_item){var that=this;new Ajax.Request("/ajax/getResource",{method:"get",parameters:{"type":this.restype,"name":content},onComplete:function(transport){var response=new LFM.Ajax.Response(transport);that.onResourceJSON(response,slot_item);}});},deselect:function(item_id){var slot=this.selections.unset(item_id);this.slots.set(slot,false);var slot_item=$(item_id);slot_item.remove();$(item_id+"_input").remove();this.filled--;var matching_choice=this.matching_choices.get(item_id);if(matching_choice){matching_choice.removeClassName("disabled");}this.updateSampleContent();if(this.onDeselect){this.onDeselect(slot_item);}},select:function(content){var item_id=this.generate_item_id(content);if(this.selections.get(item_id)){this.deselect(item_id);return false;}if(this.filled>=this.length){return false;}if(this.choices){var matching_choice=this.choices.select("li").find(function(item){return(item.down("a").innerHTML==content);});this.matching_choices.set(item_id,matching_choice);}this.form.insert(new Element("input",{"type":"hidden","name":"names[]","value":content,"id":item_id+"_input"}));var slot_item=new Element("a",{"href":"#","class":this.itemClass,"id":item_id}).observe("click",function(e){e.stop();this.deselect(item_id);}.bind(this));slot_item.insert(new Element("span").update(content));var next_slot_number=this.slots.find(function(item){return(item.value===false);}).key;var next_slot=$(this.slotID+next_slot_number);next_slot.insert(slot_item);this.selections.set(item_id,next_slot_number);this.slots.set(next_slot_number,true);this.filled++;if(matching_choice){matching_choice.addClassName("disabled");}this.updateSampleContent();if(this.onResourceJSON){this.fetchResourceJSON(content,slot_item);}if(this.onSelect){this.onSelect(content,slot_item);}}})});document.observe("dom:loaded",function(event){if($("noobStrapSubmit")){new LFM.Form.Placeholder("noobStrapTextarea");$("noobStrapSubmit").observe("click",function(e){if($F("noobStrapTextarea")&&$F("noobStrapTextarea")!=$F("noobStrapPlaceholder")){}else{e.stop();}});}});LFM.set("PreviewButtonManager",Class.create({buttonSelector:"a.previewbutton",activeClass:"previewbutton-active",trackIdAttribute:"data-track-id",soundManager:null,playingSound:null,loadingAnimation:null,loadingAnimationParams:{startFrame:3,length:5,loop:true,fps:10,play:true},playbackAnimation:null,playbackAnimationParams:{startFrame:8,length:33},initialize:function(soundManager,webServiceHost,webServiceKey,spriteClass){this.soundManager=soundManager;this.webServiceHost=webServiceHost;this.webServiceKey=webServiceKey;this.spriteClass=spriteClass;this.soundManager.onready(this.apply.bind(this));},apply:function(){if(this.soundManager.supported()){document.observe("click",this.onClick.bind(this));}},getAudioURL:function(elementAnchor){var audioURL=elementAnchor.getAttribute("href");if(!audioURL.endsWith(".mp3")){var trackId=this.getTrackId(elementAnchor);audioURL=trackId?this.generatePreviewURL(trackId):false;}return audioURL;},getTrackId:function(element){var dataElement=element.down().up("["+this.trackIdAttribute+"]");if(dataElement){return dataElement.readAttribute(this.trackIdAttribute);}return false;},generatePreviewURL:function(trackId){var params={method:"track.previewmp3",trackid:trackId,api_key:this.webServiceKey};return"http://"+this.webServiceHost+"/2.0/?"+Object.toQueryString(params);},play:function(elementAnchor,elementImage,audioURL){this.soundManager.stopAll();this.loadingAnimation=new LFM.Util.SpriteAnimation(elementImage,this.loadingAnimationParams);this.playbackAnimation=new LFM.Util.SpriteAnimation(elementImage,this.playbackAnimationParams);elementAnchor.addClassName(this.activeClass);this.playAudio(audioURL);},playAudio:function(audioURL){var id="sound_"+audioURL;if(this.playingSound=this.soundManager.getSoundById(id)){this.playingSound.play();}else{this.playingSound=this.soundManager.createSound({id:id,url:audioURL,onfinish:this.onStop.bind(this),onstop:this.onStop.bind(this),ondataerror:this.onError.bind(this),whileplaying:this.onPlayback.bind(this),autoPlay:true});}LFM.Page.Tracker.eventPlayTrack("Preview");},stop:function(){if(this.playingSound){this.playingSound.stop();}this.cleanupAnimation();var activeButtonSelector=this.buttonSelector+"."+this.activeClass;$$(activeButtonSelector).invoke("removeClassName",this.activeClass);},cleanupAnimation:function(){if(this.loadingAnimation){this.loadingAnimation.stop();this.loadingAnimation.cleanup();delete this.loadingAnimation;}if(this.playbackAnimation){this.playbackAnimation.cleanup();delete this.playbackAnimation;}},onClick:function(event){var element=event.element();var elementAnchor=element.match(this.buttonSelector)?element:element.up(this.buttonSelector);var elementImage=elementAnchor?elementAnchor.down("img",0):null;if(!elementImage||!elementAnchor){return;}var isPlaying=elementAnchor.hasClassName(this.activeClass);var audioURL=this.getAudioURL(elementAnchor);this.stop();if(audioURL){event.preventDefault();elementAnchor.blur();if(!isPlaying){this.play(elementAnchor,elementImage,audioURL);}}},onPlayback:function(){if(this.loadingAnimation.isPlaying()){this.loadingAnimation.stop();this.playbackAnimation.reset();}var duration=this.playingSound.duration;if(duration<this.playingSound.durationEstimate){duration=this.playingSound.durationEstimate;}var audioProgress=this.playingSound.position/duration*100;var animationProgress=(this.playbackAnimation.getFramePosition()+1)/this.playbackAnimation.getLength()*100;if(audioProgress>animationProgress){this.playbackAnimation.next();}},onStop:function(){this.stop();},onError:function(){this.stop();}}));document.observe("dom:loaded",function(){new LFM.PreviewButtonManager(LFM.SoundManager.getInstance(),LFM.Session.wsHost,LFM.Session.wsKey);});LFM.set("Display",{PromoBar:Class.create({url:"/ajax/dismisspromobar",initialize:function(){document.observe("dom:loaded",function(){var b=$(document.body);b.observe("click",this.dismiss.bind(this));b.observe("click",this.link.bind(this));}.bind(this));},dismiss:function(event){var promobar,barName,target=$(event.target);if(target.hasClassName("promobarDismiss")){promobar=target.up(".promobar");barName=promobar.readAttribute("data-barname");LFM.Page.Tracker.eventPromobarDismiss(barName);this.hide(promobar);new Ajax.Request(this.url,{method:"post",parameters:{barName:barName,dismiss:true}});}},show:function(barName){new Ajax.Request(this.url,{method:"post",parameters:{barName:barName,dismiss:false}});},link:function(event){var promobar,barName,target=$(event.target);if(target.hasClassName("promobarLink")){promobar=target.up(".promobar");barName=promobar.readAttribute("data-barname");LFM.Page.Tracker.eventPromobarLink(barName);}},hide:function(promobarEl){promobarEl.setStyle({"height":promobarEl.getHeight()+"px"});new Effect.BlindUp(promobarEl);new Effect.Fade(promobarEl);}})});new LFM.Display.PromoBar();LFM.set("Page",{Extract:{trackIds:function(rootElement,unique){if(typeof unique=="undefined"){unique=true;}rootElement=$(rootElement)||document.body;var trackIds=rootElement.select("*[data-track-id]").collect(function(elem){return elem.getAttribute("data-track-id");});return unique?this._unique(trackIds):trackIds;},_unique:function(list){var sorted=list.sortBy(function(item){return Number(item);});uniques=[list[0]];for(var i=1;i<sorted.length;i++){if(sorted[i-1]==sorted[i]){}else{uniques.push(sorted[i]);}}return uniques;}}});LFM.set("Input",{RichText:Class.create({hasFocus:false,busy:false,wordSeparators:" \t\n,.()!?|=-\\",initialize:function(div,options){this.div=$(div);this.options=options?options:{};this.caret=this.div.down("span.caret");this.caret.style.color="white";this.caret.style.borderLeft="1px solid white";this.textarea=this.div.next("textarea");Event.observe(this.textarea,"keypress",this.keyPress.bindAsEventListener(this));Event.observe(this.textarea,"keydown",this.keyDown.bindAsEventListener(this));Event.observe(window,"keydown",this.keyDown.bindAsEventListener(this));Event.observe(this.div,"click",this.focus.bindAsEventListener(this));Event.observe(window,"blur",this.blur.bindAsEventListener(this));new Ajax.Request("/ajax/getArtists",{onComplete:function(resp){var out=resp.responseText.evalJSON();this.artists=out.items;}.bind(this)});},keyDown:function(e){e=window.event||e;var keyCode=e.charCode||e.keyCode||e.which;var s=String.fromCharCode(keyCode);this.cancelOnDown=false;if(this.specialKeyDown(keyCode,e)){Event.stop(e);this.cancelOnDown=true;return false;}if(e.ctrlKey){s=s.toLowerCase();if(s=="a"||s=="m"){Event.stop(e);var sel=this.getSelection();var name=this.getSelectedText(sel);var richtext;if(s=="a"){richtext="<lfm:artist>"+name.strip().escapeHTML()+"</lfm:artist>";}else{if(s=="m"){richtext='<lfm:artist name="'+name.strip().escapeHTML()+'"><lfm:image size="small" /></lfm:artist>';}}this.replaceSelection(richtext,sel);}}},getSelection:function(){var sel;if(window.getSelection){sel=window.getSelection();}else{if(document.selection){sel=document.selection.createRange();}}return sel;},getSelectedText:function(sel){var name="";var next=sel.anchorNode;while(next){if(next.nodeValue){name+=next.nodeValue;}if(next==sel.focusNode){break;}next=next.nextSibling;}return name;},replaceSelection:function(richtext,sel){new Ajax.Request("/ajax/richtextrenderer",{method:"post",parameters:{richtext:richtext},onComplete:function(resp){var out=resp.responseText.evalJSON();var range=sel.getRangeAt(0);$(document.body).insert({bottom:out.rendered});var node=$(document.body).lastChild;node.remove();range.deleteContents();range.insertNode(node);this.textarea.value+=out.richtext;}});},keyPress:function(e){e=window.event||e;var keyCode=e.charCode||e.keyCode||e.which;var s=String.fromCharCode(keyCode);if(this.specialKeyPress(keyCode,e)){Event.stop(e);return false;}if(e.altKey){Event.stop(e);return false;}if(!this.hasFocus||e.element()==window){return;}var prev=this.caret.previousSibling;if(prev&&prev.nodeType==3&&prev.nodeValue.strip().empty()&&prev.nodeValue!="\n"){var parentNode=prev.parentNode;var range=prev.ownerDocument.createRange();range.setStartBefore(prev);var newChar=range.createContextualFragment(s);var n=parentNode.replaceChild(newChar,prev);var range=this.caret.ownerDocument.createRange();range.setStartBefore(this.caret.previousSibling);var space=range.createContextualFragment(" ");parentNode.insertBefore(space,this.caret.previousSibling);}else{this.caret.insert({before:s});}},_delete:function(prev){var newline=false;var prevPrev=prev.previousSibling;if(prev.nodeType==1){if(prev.nodeName=="A"){var child=prev.firstChild;prev.parentNode.replaceChild(child,prev);child.unlinked=true;var start=this.textarea.selectionStart;var tag="";var i=start-2;while(i>=0&&(this.textarea.value.charAt(i)!="/")){tag=this.textarea.value.charAt(i)+tag;i--;}var closeTagPosition=i;var openTag="<"+tag+">";var openTagLength=openTag.length;while(i>=0&&(this.textarea.value.substr(i,openTagLength)!=openTag)){i--;}var value=this.textarea.value.substr(0,i);var contentStart=i+openTagLength;value+=this.textarea.value.substr(contentStart,closeTagPosition-contentStart-1);value+=this.textarea.value.substr(start);this.textarea.value=value;return;}}if(prev.nodeValue=="\n"){newline=true;}var parentNode=prev.parentNode;if(prev.nodeType==3){var start=this.textarea.selectionStart;var value=this.textarea.value.substr(0,start-1);if(start<this.textarea.value.length){value+=""+this.textarea.value.substr(start);}this.textarea.value=value;if(this.textarea.createTextRange){var oRange=this.textarea.createTextRange();oRange.moveStart("character",start-1);oRange.moveEnd("character",start-1);oRange.select();}else{if(this.textarea.setSelectionRange){this.textarea.setSelectionRange(start-1,start-1);}}if(prev.nodeValue.length>1){prev.nodeValue=prev.nodeValue.substr(0,prev.nodeValue.length-1);return;}}else{if(prev.nodeName=="BR"){this.textarea.value=this.textarea.value.substr(0,this.textarea.value.length-6);}}parentNode.removeChild(prev);if(prevPrev&&prevPrev.nodeType==3&&prevPrev.nodeValue.strip().empty()&&prevPrev.nodeValue!="\n"){var range=prevPrev.ownerDocument.createRange();range.setStartAfter(prevPrev);var nbsp=range.createContextualFragment("&nbsp;");parentNode.replaceChild(nbsp,prevPrev);prevPrev=nbsp;}if(newline){var prevPrev=prev.previousSibling;parentNode.removeChild(prev);this.caret.previousSibling=prevPrev;this.caret.remove();}if(prevPrev){parentNode.insertBefore(this.caret,prevPrev.nextSibling);}},specialKeyDown:function(keyCode,e){if(keyCode>=37&&keyCode<=40&&!(e.ctrlKey||e.altKey||e.shiftKey||e.metaKey)){var prev=this.caret.previousSibling;var next=this.caret.nextSibling;var parent=this.caret.parentNode;if(keyCode==37&&prev){this.caret.remove();parent.insertBefore(this.caret,prev);var start=this.textarea.selectionStart;if(this.textarea.createTextRange){var oRange=this.textarea.createTextRange();oRange.moveStart("character",start-1);oRange.moveEnd("character",start-1);oRange.select();}else{if(this.textarea.setSelectionRange){this.textarea.setSelectionRange(start-1,start-1);}}}else{if(keyCode==39&&next){this.caret.remove();parent.insertBefore(this.caret,next.nextSibling);var start=this.textarea.selectionStart;if(this.textarea.createTextRange){var oRange=this.textarea.createTextRange();oRange.moveStart("character",start+1);oRange.moveEnd("character",start+1);oRange.select();}else{if(this.textarea.setSelectionRange){this.textarea.setSelectionRange(start+1,start+1);}}}}this.textarea.focus();return true;}else{if(keyCode==46){if(this.caret.nextSibling){this.moveTextAreaCursorBy(1);var next=this.caret.nextSibling;this.caret.remove();next.parentNode.insertBefore(this.caret,next.nextSibling);this._delete(next);}return true;}else{if(keyCode==8){if(this.caret.previousSibling){this._delete(this.caret.previousSibling);}return true;}else{if(keyCode==13){this.caret.insert({before:"<br />"});this.textarea.value+="<br />";return true;}}}}},specialKeyPress:function(keyCode,e){var s=String.fromCharCode(keyCode);if(this.cancelOnDown){return true;}if(this.wordSeparators.indexOf(s)>=0){var lastChar=this.caret;if(lastChar.previousSibling&&lastChar.previousSibling.nodeType==3&&!lastChar.previousSibling.unlinked){var back=0;var name="";var insertPoint;while((lastChar=lastChar.previousSibling)&&lastChar.nodeType==3&&lastChar.nodeValue.unescapeHTML().strip()!=""){name=lastChar.nodeValue+name;back++;}insertPoint=lastChar;var richtext=false;name=name.strip();if(s!="."&&name.match(/^((ht|f)tp(s?)\:\/\/|~\/|\/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((\/?\w+\/)+|\/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?/)){richtext='<a href="'+name.escapeHTML()+'">'+name.escapeHTML()+"</a>";}else{var upperName=name.toUpperCase();var found=this.artists.find(function(a){return a.toUpperCase()==upperName;});if(found){richtext="<lfm:artist>"+name.escapeHTML()+"</lfm:artist>";}}if(richtext){var textareaStart=this.textarea.selectionStart;new Ajax.Request("/ajax/richtextrenderer",{method:"post",parameters:{richtext:richtext},onComplete:function(resp){var out=resp.responseText.evalJSON();var lastChar=insertPoint.nextSibling;for(;back>0;back--){var tmp=lastChar.nextSibling;lastChar.parentNode.removeChild(lastChar);lastChar=tmp;}if(insertPoint){var range=insertPoint.ownerDocument.createRange();range.setStartAfter(insertPoint);var element=range.createContextualFragment(out.rendered);insertPoint.parentNode.insertBefore(element,insertPoint.nextSibling);}else{this.div.insert({top:out.rendered});}var value=this.textarea.value.substr(0,textareaStart-name.length);value+=out.richtext;value+=""+this.textarea.value.substr(textareaStart);this.textarea.value=value;}.bind(this)});}}}else{if(s=="/"){var lastChar=this.caret.previousSibling;if(!lastChar||lastChar.nodeValue!="["){return false;}var nextToCursor=lastChar;var contents="";var tag="";var back=2;while((lastChar=lastChar.previousSibling)&&lastChar.nodeType==3&&lastChar.nodeValue!="]"){contents=lastChar.nodeValue+contents;back++;}while((lastChar=lastChar.previousSibling)&&lastChar.nodeType==3&&lastChar.nodeValue!="["){tag=lastChar.nodeValue+tag;back++;}if(tag=="artist"){contents=contents.strip();var textareaStart=this.textarea.selectionStart;var richtext="<lfm:artist>"+contents.escapeHTML()+"</lfm:artist>";new Ajax.Request("/ajax/richtextrenderer",{method:"post",parameters:{richtext:richtext},onComplete:function(resp){var out=resp.responseText.evalJSON();lastChar=nextToCursor;for(var i=back;i>0;i--){var tmp=lastChar.previousSibling;lastChar.parentNode.removeChild(lastChar);lastChar=tmp;}if(this.caret.previousSibling){var rm=this.caret.previousSibling;rm.parentNode.removeChild(rm);}this.caret.insert({before:out.rendered});var value=this.textarea.value.substr(0,textareaStart-back-1);value+=""+out.richtext;value+=""+this.textarea.value.substr(textareaStart);this.textarea.value=value;}.bind(this)});return true;}}}if(s==" "){this.caret.insert({before:"&nbsp;"});this.textarea.value+=" ";return true;}},moveTextAreaCursorBy:function(n){var start=this.textarea.selectionStart;if(this.textarea.createTextRange){var oRange=this.textarea.createTextRange();oRange.moveStart("character",start+n);oRange.moveEnd("character",start+n);oRange.select();}else{if(this.textarea.setSelectionRange){this.textarea.setSelectionRange(start+n,start+n);}}},focus:function(e){Event.stop(e);var rangeParent=e.rangeParent;if(this.caret.parentNode){this.caret.remove();}if(rangeParent!=this.caret&&rangeParent!=this.div){rangeParent.parentNode.insertBefore(this.caret,rangeParent.nextSibling);}else{this.div.appendChild(this.caret);}this.hasFocus=true;this.textarea.focus();this.startBlinkingCaret();},blur:function(){this.hasFocus=false;this.stopBlinkingCaret();},startBlinkingCaret:function(){this.caret.style.borderLeft="1px solid black";},stopBlinkingCaret:function(){this.blinkCaret();},blinkCaret:function(){this.caret.style.borderLeft=this.caret.style.borderLeft=="1px solid black"?"1px solid white":"1px solid black";}})});LFM.set("Scrobbler",new (Class.create({minScrobbleDuration:30,scrobbleURL:"/ajax/scrobble",nowPlayingURL:"/ajax/nowplaying",initialize:function(){},sendScrobble:function(track,successCallback,failureCallback){var params={method:"post",parameters:{track:track.id,formtoken:LFM.Session.formtoken},onSuccess:successCallback,onFailure:failureCallback};new Ajax.Request(this.scrobbleURL,params);},sendNowPlaying:function(track,successCallback,failureCallback){var params={method:"post",parameters:{track:track.id,formtoken:LFM.Session.formtoken},onSuccess:successCallback,onFailure:failureCallback};new Ajax.Request(this.nowPlayingURL,params);},isScrobblable:function(track){var isValidDuration=track.duration&&track.duration>=this.minScrobbleDuration;var hasValidMetadata=track.id;return isValidDuration&&hasValidMetadata;},getScrobblePoint:function(track){return Math.max(Math.round(track.duration/2),30);}}))());LFM.set("ScrobbleStream",Class.create({id:null,updateInterval:10,updateLimit:50,maxUpdates:20,updateCount:0,scrobbles:[],streamURL:"/ajax/getgloballisteners",interval:null,isUpdating:false,isPopulated:false,initialize:function(id){this.id=id;},start:function(){if(this.interval){return;}this.update();this.interval=setInterval(this.update.bind(this),this.updateInterval*1000);},stop:function(){clearInterval(this.interval);this.interval=null;},updateData:function(){if(this.updateCount>=this.maxUpdates){this.stop();return;}this.updateCount++;if(this.isUpdating){return;}this.isUpdating=true;new Ajax.Request(this.streamURL,{parameters:{limit:this.updateLimit,formtoken:LFM.Session.formtoken},onException:(function(r){this.isUpdating=false;}).bind(this),onFailure:(function(r){this.isUpdating=false;}).bind(this),onSuccess:(function(response){if(response.responseText){var scrobbles=response.responseText.evalJSON();for(var i=0;i<scrobbles.length;i++){this.scrobbles.push(scrobbles[i]);}}this.isUpdating=false;}).bind(this)});},update:function(){if(this.scrobbles.length<=1){this.updateData();}if(this.scrobbles.length==0){return;}var scrobble=this.scrobbles.shift();var li=new Element("li",{"style":"display: none;"}).update(scrobble);$(this.id).insert({"top":li});new Effect.SlideDown(li,{duration:1});}}));var Scroller=Class.create({initialize:function(scroller){this.scroller=$(scroller);this.imageTrackContainer=$(document).getElementsByClassName("imageTrackContainer",this.scroller)[0];this.imageTrack=this.imageTrackContainer.getElementsByTagName("UL")[0];this.isScrolling=false;this.makeScrollingWork();this.centerSelectedImage();},makeScrollingWork:function(){Element.addClassName(this.scroller,"scrollerJS");if(this.getWidth()<=this.getVisibleWidth()){if(window.attachEvent&&!window.opera){Element.setStyle(this.scroller,{width:this.getWidth()+"px"});}}else{Element.setStyle(this.scroller,{padding:"0 10px",marginLeft:0,marginRight:0,overflow:"hidden"});this.leftScrollButton=document.createElement("a");this.leftScrollButton.innerHTML="scroll left";this.leftScrollButton.href="#";Element.addClassName(this.leftScrollButton,"scrollLeft");this.scroller.insertBefore(this.leftScrollButton,this.imageTrackContainer);Event.observe(this.leftScrollButton,"click",this.scrollLeft.bindAsEventListener(this));this.rightScrollButton=document.createElement("a");this.rightScrollButton.innerHTML="scroll right";this.rightScrollButton.href="#";Element.addClassName(this.rightScrollButton,"scrollRight");this.scroller.insertBefore(this.rightScrollButton,this.imageTrackContainer);Event.observe(this.rightScrollButton,"click",this.scrollRight.bindAsEventListener(this));Event.observe(window,"resize",this.onResize.bindAsEventListener(this));this.setWidth();}},setWidth:function(){if(!this.imageWidth){this.imageWidth=this.getImageWidth();}Element.setStyle(this.scroller,{maxWidth:this.getWidth()+"px"});var optimalWidth=this.getVisibleWidth();modulo=optimalWidth%this.imageWidth;optimalWidth=optimalWidth-modulo;if(optimalWidth>this.getWidth()){optimalWidth=this.getWidth();}Element.setStyle(this.scroller,{maxWidth:optimalWidth+"px"});var scrollDelta=this.getWidth()*-1+Math.abs(this.getOffset())+this.getVisibleWidth();var properScrollDelta=(this.getWidth()-this.getVisibleWidth())*-1;this.setOffset(properScrollDelta);this.refreshButtonStates();},onResize:function(event){this.setWidth();},getImageWidth:function(){if(this.imageWidth){return this.imageWidth;}else{sampleImage=this.imageTrack.getElementsByTagName("LI")[0];if(sampleImage){this.imageWidth=sampleImage.offsetWidth;this.imageWidth=this.imageWidth+Element.getStyle(sampleImage,"padding-left").replace("px","")*1;this.imageWidth=this.imageWidth+Element.getStyle(sampleImage,"padding-right").replace("px","")*1;this.imageWidth=this.imageWidth+Element.getStyle(sampleImage,"margin-left").replace("px","")*1;this.imageWidth=this.imageWidth+Element.getStyle(sampleImage,"margin-right").replace("px","")*1;var borderLeftWidth=Element.getStyle(sampleImage,"border-left-width").replace("px","")*1;if(!isNaN(borderLeftWidth)){this.imageWidth=this.imageWidth+borderLeftWidth;}var borderRightWidth=Element.getStyle(sampleImage,"border-right-width").replace("px","")*1;if(!isNaN(borderRightWidth)){this.imageWidth=this.imageWidth+borderRightWidth;}return this.imageWidth;}else{return false;}}},getMiddle:function(){return Math.ceil(this.imageTrackContainer.offsetWidth/2);},getWidth:function(){return this.imageTrack.offsetWidth;},getVisibleWidth:function(){return this.imageTrackContainer.offsetWidth;},getNumberOfVisibleImages:function(){return Math.floor(this.getVisibleWidth()/this.getImageWidth());},getNumberOfImages:function(){return Math.floor(this.imageTrack.getElementsByTagName("LI").length);},getOffset:function(){offset=Element.getStyle(this.imageTrack,"left");if(offset){offset=offset.replace("px","")*1;if(!isNaN(offset)){return offset;}else{return 0;}}else{return 0;}},setOffset:function(offset){var blah=this.getWidth()-this.getVisibleWidth();this.imageTrack.setStyle({left:offset+"px"});},scrollLeft:function(event){if(!this.isScrolling&&this.getOffset()<0){var maxDelta=Math.abs(this.getOffset());var delta=this.getVisibleWidth();if(delta>maxDelta){delta=maxDelta;}this.scroll(delta);}this.refreshButtonStates();this.leftScrollButton.blur();Event.stop(event);},scrollRight:function(event){if(!this.isScrolling&&(Math.abs(this.getOffset())+this.getVisibleWidth())<this.getWidth()){var maxDelta=this.getWidth()-(Math.abs(this.getOffset())+this.getVisibleWidth());var delta=this.getVisibleWidth();if(delta>maxDelta){delta=maxDelta;}delta=delta*-1;this.scroll(delta);}this.refreshButtonStates();this.rightScrollButton.blur();Event.stop(event);},scroll:function(delta,force){if(!this.isScrolling||force){new Effect.Move(this.imageTrack,{x:delta,y:0,mode:"relative",duration:0.5,afterFinish:this.afterScrolling.bind(this),beforeStart:this.beforeScrolling.bind(this),queue:{position:"end",scope:"scroller"}});}},beforeScrolling:function(effect){this.isScrolling=true;this.totalDelta=this.totalDelta+effect.options.x;},afterScrolling:function(effect){this.isScrolling=false;this.totalDelta=this.totalDelta-effect.options.x;this.refreshButtonStates();},refreshButtonStates:function(){if(this.rightScrollButton&&this.leftScrollButton){if((Math.abs(this.getOffset())+this.getVisibleWidth())<this.getWidth()){this.rightScrollButton.className="scrollRight";}else{this.rightScrollButton.className="scrollRight disabled";}if(this.getOffset()<0){this.leftScrollButton.className="scrollLeft";}else{this.leftScrollButton.className="scrollLeft disabled";}}},getSelectedImage:function(){selectedImage=$(document).getElementsByClassName("selected",this.imageTrack)[0];if(selectedImage){return $(selectedImage);}else{return false;}},centerSelectedImage:function(){if(this.getVisibleWidth()!=this.getWidth()){var offset=this.getSelectedImage().id;if(offset&&this.getImageWidth()){offset=(offset.substring(5)*1)-1;var imageOffset=offset*this.getImageWidth();imageOffset=imageOffset-this.getMiddle()+this.getImageWidth()/2;if(imageOffset>(this.getWidth()-this.getVisibleWidth())){imageOffset=this.getWidth()-this.getVisibleWidth();}imageOffset=imageOffset*-1;if(imageOffset>0){imageOffset=0;}Element.setStyle(this.imageTrack,{left:imageOffset+"px"});this.refreshButtonStates();}}}});LFM.set("Form",{SelectAChain:Class.create({initialize:function(){$$("body")[0].observe("click",this.clickHandler.bindAsEventListener(this));var selects=$$(".selectachain select");selects.each(function(selectElem){selectElem.down('option[value="_"]').remove();},this);},clickHandler:function(e){var target=$(e.target);if(target.match("a")){var parent=target.up(0);if(parent.match(".selectachain li")){e.stop();if(parent.match(".selectachain-option")){var subject=parent.next("li");var select=subject.down("select");var label=subject.down("label");select.disabled=true;Event.fire(select,"CustomSelect:change");var link=new Element("a",{"href":label.getAttribute("data-selectachain-url")}).update(label.innerHTML);label.replace(link);var backLink=parent.down("a");var backStrong=new Element("strong").writeAttribute("data-selectachain-url",backLink.getAttribute("href")).update(backLink.innerHTML);backLink.replace(backStrong);subject.removeClassName("selectachain-option");}else{var select=parent.down("select");var link=parent.down("a");var label=new Element("label",{"for":select.getAttribute("id"),"class":"rm"}).writeAttribute("data-selectachain-url",link.getAttribute("href")).update(link.innerHTML);link.replace(label);var backStrong=parent.previous("li").down("strong");var backLink=new Element("a",{"href":backStrong.getAttribute("data-selectachain-url")}).update(backStrong.innerHTML);backStrong.replace(backLink);parent.addClassName("selectachain-option");select.disabled=false;Event.fire(select,"CustomSelect:change");}}}}})});document.observe("dom:loaded",function(){new LFM.Form.SelectAChain();});LFM.set("Resource",{Shoutbox:Class.create(LFM.Observable,{initialize:function($super,shoutbox){this.shoutbox=shoutbox;this.shoutbox.container=$(this.shoutbox.container);this.textarea=$("shoutmsg");this.overCharLimit=false;if($("shoutPost")){$("shoutPost").observe("submit",this.submit.bindAsEventListener(this));this.textarea.observe("keyup",this.calculateCharCount.bindAsEventListener(this));}this.deleteButtons=this.shoutbox.container.select(".delete");this.deleteButtons.each(function(deleteButton){deleteButton.observe("click",this.bin.bindAsEventListener(this));}.bind(this));if($("shoutboxPopup")){$("shoutboxPopup").observe("click",this.popup.bindAsEventListener(this));}if($("shoutPostToggler")&&$("shoutPostToggler").down("a")){$("shoutPostToggler").down("a").observe("click",this.toggleInput.bindAsEventListener(this));}if($("shoutPostAgain")){$("shoutPostAgain").observe("click",this.toggleInput.bindAsEventListener(this));}$super();},submit:function(e){e.stop();if($F(this.textarea)==""){return;}var self=this;if(LFM.Page.Captcha){if(!LFM.Page.Captcha.isVisible()){LFM.Page.Captcha.show(function(){console.log(new LFM.Event.ShoutCaptchaShown());self.notifyObservers(new LFM.Event.ShoutCaptchaShown());});return;}}this.toggleInput(e);$("shoutPostWait").show();$("shoutboxError").hide();var url=this.shoutbox.destination;if(url.substr(-1)!="/"){url+="/";}url+="add";var pars=$("shoutPost").serialize()+"&restype="+this.shoutbox.restype+"&resid="+this.shoutbox.resid+"&lang="+this.shoutbox.lang+"&ajax=1";if($("captcha")){pars+="&recaptcha_challenge_field="+$("recaptcha_challenge_field").value+"&recaptcha_response_field="+$("recaptcha_response_field").value;}var that=this;var myAjax=new Ajax.Request(url,{method:"post",parameters:pars,onSuccess:this.addShout.bind(this),onFailure:function(){that.toggleInput();$("shoutPostWait").hide();$("shoutboxError").show();if(LFM.Page.Captcha){LFM.Page.Captcha.reload();}}});},addShout:function(originalRequest){if(this.shoutbox.restype==20){LFM.Page.Tracker.eventCommentPost();}else{LFM.Page.Tracker.eventShoutPost();}var shoutList=$("shoutList");$("shoutList").insert({before:originalRequest.responseText});if(this.shoutbox.order=="asc"){shoutList.innerHTML=shoutList.innerHTML+$("newShoutList").innerHTML;}else{shoutList.innerHTML=$("newShoutList").innerHTML+shoutList.innerHTML;}$("newShoutList").remove();$("shoutList").select("li").each(function(li){var newDeleteButton=li.down(".delete");if(newDeleteButton){newDeleteButton.observe("click",this.bin.bindAsEventListener(this));}}.bind(this));this.textarea.value="";$("shoutPostWait").hide();if($("noShouts")){$("noShouts").remove();}if($("shoutPostToggler")){$("shoutPostToggler").hide();}$("shoutPostAgain").show();if(LFM.Page.Captcha){$("captcha").remove();delete LFM.Page.Captcha;}this.updateCharCountDisplay(0);this.notifyObservers(new LFM.Event.ShoutComplete());},bin:function(event){event.stop();var shoutItem=event.findElement("li");var form=shoutItem.down("form");var action=this.shoutbox.destination;if(action.substr(-1)!="/"){action+="/";}action+="delete";form.action=action;var restype=this.shoutbox.restype;var resid=this.shoutbox.resid;var dialog=new LFM.Dialog({content:LFM.String.deleteMessagePrompt,confirmText:LFM.String.deleteButtonText,action:action,onConfirm:function(e){e.stop();this.hide();form.request({parameters:{restype:restype,resid:resid,ajax:1},onSuccess:function(req){if(req.responseText=="OK"){new Effect.Fade(shoutItem,{duration:0.2});}}});}});dialog.show();},toggleInput:function(e){if($("shoutPost").visible()){$("shoutPost").hide();}else{$("shoutPostAgain").hide();$("shoutPost").show();this.textarea.focus();}if(typeof e!=="undefined"){e.stop();}},calculateCharCount:function(){var charcount=this.textarea.value.length;this.updateCharLimit(charcount);this.updateCharCountDisplay(charcount);},updateCharCountDisplay:function(charcount){charCounter=$("sbCharCount");var charCounterText=this.shoutbox.charlimitMessage;if(charCounter){charCounterText=charCounterText.replace(/CURRENTCHARS/,charcount);charCounterText=charCounterText.replace(/MAXCHARS/,this.shoutbox.charlimit);charCounter.innerHTML=charCounterText;}},updateCharLimit:function(charcount){var overCharLimit=(charcount>this.shoutbox.charlimit);if(!this.overCharLimit&&overCharLimit){$("sbCharCount").up().addClassName("overCharLimit");$("sbPost").disable();this.textarea.focus();}if(this.overCharLimit&&!overCharLimit){$("sbCharCount").up().removeClassName("overCharLimit");$("sbPost").enable();}this.overCharLimit=overCharLimit;},hasShout:function(){if(this.textarea){return shout=$F(this.textarea).strip()!="";}else{return false;}}})});LFM.set("SoundManager",Class.create({initialize:function(){}}));LFM.SoundManager.getInstance=function(){if(!window.soundManager){window.soundManager=new SoundManager();window.soundManager.url=LFM.Session.staticHost+"/flatness/soundmanager/297a-20110918/";if(LFM.get("useHTML5Audio")){window.soundManager.useHTML5Audio=true;window.soundManager.preferFlash=false;}window.soundManager.onready(function(){LFM.log("SoundManager2 Ready");});window.soundManager.ontimeout(function(){LFM.log("SoundManager2 not supported");});window.soundManager.beginDelayedInit();}return window.soundManager;};LFM.set("Util",{SpriteAnimation:Class.create({initialize:function(element,params){this.element=element;this.frameSize=params.frameSize||this.element.getHeight();this.startFrame=params.startFrame||0;this.endFrame=this.startFrame+params.length-1;this.loop=params.loop||false;this.positionX=params.positionX||0;this.positionY=params.positionY||0;this.axis=(params.axis||"y").toUpperCase();this.fps=params.fps||1;this.currentFrame=this.startFrame;this.timer=null;if(params.play){this.play();}},reset:function(){this.setFrame(this.startFrame);},getLength:function(){return this.endFrame-this.startFrame+1;},next:function(){if(this.currentFrame!=this.endFrame){this.setFrame(1+this.currentFrame);}else{if(this.loop){this.reset();}else{this.stop();}}},setFrame:function(frame){this.currentFrame=frame;this["position"+this.axis]=this.currentFrame*(this.frameSize*-1);var pos=this.positionX+"px "+this.positionY+"px";this.element.setStyle({backgroundPosition:pos});},play:function(start,end,loop){this.stop();this.reset();this.timer=setInterval(this.next.bind(this),1000/this.fps);},getFramePosition:function(){return this.currentFrame-this.startFrame;},stop:function(){clearTimeout(this.timer);this.timer=null;},isPlaying:function(){return !!this.timer;},cleanup:function(){this.element.setStyle({"backgroundPosition":""});}})});LFM.set("Display",{TableDragDrop:Class.create({initialize:function(table,options){this.draggedRow=null;this.rowWithBorderAndShit=null;this.mouseOffset=null;this.oldY=0;this.dragged=false;if(options&&options.dragHandle){this.dragHandle=options.dragHandle;}else{this.dragHandle=false;}this.table=$(table);this.table.addClassName("draggable");this.table.observe("mousedown",this.onMouseDown.bindAsEventListener(this));if(this.dragHandle){this.table.addClassName("withDragHandles");}else{this.table.addClassName("allDraggable");}this.table.down("tbody").observe("click",this.onClick.bindAsEventListener(this));},onClick:function(event){if(this.dragged){event.stop();this.dragged=false;}},getMouseOffset:function(target,event){var docPos=target.cumulativeOffset();return{x:event.pointerX()-docPos.left,y:event.pointerY()-docPos.top};},onMouseDown:function(event){if(!event.isLeftClick()){return;}if(this.dragHandle&&!event.element().hasClassName(this.dragHandle)){return;}if((tag_name=event.element().tagName.toUpperCase())&&(tag_name=="INPUT"||tag_name=="SELECT"||tag_name=="OPTION"||tag_name=="BUTTON"||tag_name=="TEXTAREA")){return;}this.draggedRow=event.findElement("tr");if(this.draggedRow.previous("tr")){this.rowWithBorderAndShit=this.draggedRow.previous("tr");this.rowWithBorderAndShit.addClassName("beforeDraggedRow");}else{if(this.draggedRow.next("tr")){this.rowWithBorderAndShit=this.draggedRow.next("tr");this.rowWithBorderAndShit.addClassName("afterDraggedRow");}}this.mouseOffset=this.getMouseOffset(this.draggedRow,event);event.stop();this.draggedRow.addClassName("dragging");this.documentOnMouseMove=this.onMouseMove.bindAsEventListener(this);this.documentOnMouseUp=this.onMouseUp.bindAsEventListener(this);document.observe("mousemove",this.documentOnMouseMove);document.observe("mouseup",this.documentOnMouseUp);this.rows=this.table.down("tbody").select("tr");},onMouseMove:function(event){var y=event.pointerY()-this.mouseOffset.y;event.stop();if(y!=this.oldY){var movingDown=y>this.oldY;this.oldY=y;var targetRow=this.findDropTargetRow(y);if(targetRow){this.dragged=true;if(movingDown&&this.draggedRow!=targetRow){this.draggedRow.parentNode.insertBefore(this.draggedRow,targetRow.nextSibling);}else{if(!movingDown&&this.draggedRow!=targetRow){this.draggedRow.parentNode.insertBefore(this.draggedRow,targetRow);}}}}},onMouseUp:function(event){event.stop();this.draggedRow.removeClassName("dragging");this.rowWithBorderAndShit.removeClassName("beforeDraggedRow");this.rowWithBorderAndShit.removeClassName("afterDraggedRow");if(this.onDrop){this.onDrop(this.table,this.draggedRow);}this.draggedRow=null;document.stopObserving("mousemove",this.documentOnMouseMove);document.stopObserving("mouseup",this.documentOnMouseUp);},findDropTargetRow:function(y){return this.rows.find(function(row){var rowY=row.cumulativeOffset().top;var rowHeight=row.getHeight()/2;if((y>rowY-rowHeight)&&(y<(rowY+rowHeight))){return true;}else{return false;}});return null;}})});LFM.set("Resource",{Users:Class.create({initialize:function(users){this.container=$("users");this.container.observe("click",function(event){log("clicked container");var element=event.element();if(element.match("a.delete img")){event.stop();var friend=element.up("li");if(friend){this.bin(friend);}}}.bind(this));},bin:function(friend){var dialog=new LFM.Dialog({resource:friend.getResource(),content:LFM.String.deleteFriendPrompt,confirmText:LFM.String.deleteButtonText,action:"friends/delete",onDone:function(response){var friend_item=response.getResourceElement();new Effect.Fade(friend_item,{duration:0.5});},showDone:false});dialog.show();}})});LFM.set("Video",{FullWidth:Class.create({initialize:function(id){this.container=$(id);this.wrapper=this.container.down("div.wrapper");this.originalDimensions=this.wrapper.getDimensions();this.aspectRatio=this.originalDimensions.height/this.originalDimensions.width;this.resize();Event.observe(document.onresize?document:window,"resize",function(event){this.resize();}.bind(this));},resize:function(){this.wrapper.setStyle({width:this.container.getWidth()+"px",height:Math.round(this.container.getWidth()*this.aspectRatio)+"px"});}})});LFM.set("Video",{VevoFullWidth:Class.create(LFM.Video.FullWidth,{initialize:function($super,id){this.object=$("myExperience");$super(id);},resize:function($super){$super();var dimensions=this.wrapper.getDimensions();this.object.writeAttribute("width",dimensions.width);this.object.writeAttribute("height",dimensions.height);}})});LFM.set("Input",{Weekpicker:Class.create({initialize:function(config){var weekpickers=$$(config.target);weekpickers.each(function(container){var target=container.select("select")[0];var label=container.select("label")[0];new LFM.Form.MasterSlaveSelectBox(target);var master=target.retrieve("MasterSlaveSelectBox.master");var masterLabel=new Element("label",{"for":master.getAttribute("id"),"class":"rm"}).update(config.yearLabel);var slave=target.retrieve("MasterSlaveSelectBox.slave");var slaveLabel=new Element("label",{"for":slave.getAttribute("id"),"class":"rm"}).update(config.weekLabel);target.insert({after:master});master.insert({before:masterLabel});master.insert({after:slave});slave.insert({before:slaveLabel});this.updateWeeknumberStore(slave);master.observe("change",this.masterChangeListener.bindAsEventListener(this));master.observe("keyup",this.masterChangeListener.bindAsEventListener(this));slave.observe("change",this.slaveChangeListener.bindAsEventListener(this));slave.observe("keyup",this.slaveChangeListener.bindAsEventListener(this));new LFM.Form.CustomSelect([slave,master]);},this);},masterChangeListener:function(e){var master=$(e.target);var slave=master.retrieve("MasterSlaveSelectBox.slave");var weeknumber=slave.retrieve("weekpicker-weeknumber");var options=slave.select("option");var optionsWeekRange=[options[0].readAttribute("data-weekpicker-weeknumber"),options[options.length-1].readAttribute("data-weekpicker-weeknumber")];if(weeknumber<optionsWeekRange[0]){slave.selectedIndex=0;}else{if(weeknumber>optionsWeekRange[1]){slave.selectedIndex=slave.options.length-1;}else{options.each(function(optElem,index){if(optElem.readAttribute("data-weekpicker-weeknumber")==weeknumber){slave.selectedIndex=index;}});}}this.updateWeeknumberStore(slave);Event.fire(slave,"CustomSelect:change");Event.fire(slave,"MasterSlaveSelectBox:change");},slaveChangeListener:function(e){var slave=$(e.target);this.updateWeeknumberStore(slave);},updateWeeknumberStore:function(slave){slave.store("weekpicker-weeknumber",slave.select("option")[slave.selectedIndex].readAttribute("data-weekpicker-weeknumber"));}})});LFM.Ajax.LazyRequest=Class.create({options:{laziness:2,beforeSend:false},_defaultAjaxOptions:{method:"post",parameters:{ajax:true,formtoken:LFM.get("Session","formtoken")}},_timeoutId:false,_ajaxUrl:false,_ajaxOptions:{},_lastTime:0,initialize:function(url,lazyOptions){Object.extend(this.options,lazyOptions);this._ajaxUrl=url;if(this.options.lazyness){this.options.laziness=this.options.lazyness;}},send:function(options){if(this._intervalId){clearTimeout(this._intervalId);}var now=new Date();this._lastTime=now.getTime()/1000;this._ajaxOptions=this._defaultAjaxOptions;if(options){if(options.parameters){Object.extend(this._ajaxOptions.parameters,options.parameters);options.paramaters=this._ajaxOptions.parameters;}Object.extend(this._ajaxOptions,options);}this._ajaxOptions.parameters.time=this._lastTime;this._intervalId=setTimeout(this._performSend.bind(this),this.options.laziness*1000);},_beforeSend:function(){if(!this.options.beforeSend){return;}Object.extend(this._ajaxOptions.parameters,this.options.beforeSend());},_performSend:function(){this._beforeSend();new Ajax.Request(this._ajaxUrl,this._ajaxOptions);}});if(Ajax.Request&&!Ajax.Request.prototype.abort){Ajax.Request.prototype.abort=function(){try{if(this.transport&&this.transport.abort){this.transport.onreadystatechange=function(){};this.transport.abort();}}catch(e){}};}LFM.Ajax.Response=Class.create({initialize:function(response){try{if(typeof response=="string"){this.ajaxResponse=response.evalJSON();}else{if(response.responseText){this.ajaxResponse=response.responseText.evalJSON();}else{this.ajaxResponse=response;}}}catch(err){this.ajaxResponse={errormessage:"Invalid JSON response"};}this.data=$H(this.ajaxResponse.data);if(this.isError()){this.printError();}},get:function(key){return this.data.get(key);},set:function(key,value){return this.data.set(key,value);},toObject:function(){return this.data.toObject();},isError:function(){return !this.ajaxResponse.success;},isSuccess:function(){return !this.isError();},getErrorCode:function(){return this.ajaxResponse.errorcode?this.ajaxResponse.errorcode:null;},getErrorMessage:function(){return this.ajaxResponse.errormessage?this.ajaxResponse.errormessage:null;},errorIs:function(code){return this.getErrorCode()===code;},isUnauthorised:function(){return this.errorIs(LFM.Ajax.Response.Errors.UNAUTHORISED);},printError:function(){if(LFM.get("config","DEVELOPMENT_SERVER")){if(!this.ajaxResponse){LFM.warn("Error [No response]");}else{LFM.warn("Error ["+this.getErrorCode()+"]: "+this.getErrorMessage());}}},getResource:function(){return this.ajaxResponse.resource?this.ajaxResponse.resource:null;},getResourceElement:function(){return LFM.getResourceElement(this.getResource());},buildResourceLink:function(){var resource=this.getResource();if(resource){var link=new Element("a",{"href":resource.url});if(resource.name){link.update(resource.name);}return link;}return false;},followRedirect:function(){if(this.ajaxResponse.redirect){window.location.href=this.ajaxResponse.redirect;return true;}else{return false;}}});LFM.Ajax.Response.Errors={UNAUTHORISED:401};LFM.Ajax.setUserPref=function(pref,value,callback){new Ajax.Request("/ajax/setUserPref",{parameters:{formtoken:LFM.Session.formtoken,pref:pref,value:value},onComplete:function(transport){var response=new LFM.Ajax.Response(transport);if(callback){callback(response);}}});};LFM.Ajax.saveOptinPreference=function(option,successCallback,errorCallback){var ajaxReq=new Ajax.Request("/ajax/settings/friendfinder",{method:"post",parameters:{choice:option,formtoken:LFM.Session.formtoken},onComplete:function(response){if(response&&response.responseJSON&&response.responseJSON.success){successCallback();}else{errorCallback();}}});};LFM.Ajax.StatusHolder=Class.create({initialize:function(element,options){this.status="idle";this.element=$(element);this.options={position:"after"};Object.extend(this.options,options);this.indicator=$(this.element.identify()+"_statusHolder");if(this.indicator){if(this.indicator.hasClassName("success")){this.status="success";}else{if(this.indicator.hasClassName("failure")){this.status="failure";}else{if(this.indicator.hasClassName("progress")){this.status="busy";}}}}else{this.indicator=document.createElement("img");this.indicator=Element.extend(this.indicator);this.indicator.src=LFM.Session.staticHost+"/tablestyles/pixel.gif";this.indicator.height=16;this.indicator.width=16;if(this.options.position=="after"){this.element.parentNode.insertBefore(this.indicator,this.element.nextSibling);}else{if(this.options.position=="before"){this.element.parentNode.insertBefore(this.indicator,this.element);}else{if(this.options.position=="top"){this.element.insertBefore(this.indicator,this.element.firstChild);}else{if(this.options.position=="bottom"){this.element.appendChild(this.indicator);}}}}this.indicator=this.indicator.wrap("SPAN");this.indicator.addClassName("statusHolder");this.indicator.id=this.element.identify()+"_statusHolder";}},remove:function(){this.indicator.remove();},busy:function(){this.idle();this.status="busy";this.indicator.addClassName("progress");this.indicator.down("img").src=LFM.Session.staticHost+"/depth/global/progress_new.gif";},isBusy:function(){return this.status=="busy";},success:function(){this.idle();this.status="success";this.indicator.addClassName("success");this.indicator.down("img").src=LFM.Session.staticHost+"/depth/forms/correct_new.gif";},isSuccess:function(){return this.status=="success";},failure:function(){this.idle();this.status="failure";this.indicator.addClassName("failure");this.indicator.down("img").src=LFM.Session.staticHost+"/depth/forms/incorrect_new.gif";},isFailure:function(){return this.status=="failure";},idle:function(){this.status="idle";this.indicator.removeClassName("progress");this.indicator.removeClassName("success");this.indicator.removeClassName("failure");this.indicator.down("img").src=LFM.Session.staticHost+"/tablestyles/pixel.gif";},isIdle:function(){return this.status=="idle";}});LFM.set("Links",{setupPost:function(linkContainer){var link=$(linkContainer);var doPost=function(e){e.preventDefault();var token=new Element("input",{type:"hidden",name:"formtoken",value:LFM.Session.formtoken});var form=new Element("Form",{action:this.href,method:"post"});form.appendChild(token);$(this).appendChild(form).submit();};if(link){link.down("a").observe("click",doPost);}}});document.observe("dom:loaded",function(){LFM.Links.setupPost("userVerification");});LFM.set("Ajax",{Autocompleter:Class.create(Ajax.Autocompleter,{setOptions:function(options){this.options=Object.extend({method:"get"},options||{});},buildItem:function(name){return new Element("a",{href:"#"}).update(name).wrap(new Element("li"));},onComplete:function(transport){try{var response=transport.responseText.evalJSON();}catch(err){return false;}if(response&&response.response.docs){var list=new Element("ul");var original_query=this.getToken();list.insert(this.buildItem(original_query));response.response.docs.each(function(result){if(result.name.toLowerCase()!=original_query.toLowerCase()){list.insert(this.buildItem(result.name));}}.bind(this));this.updateChoices(new Element("div").update(list).innerHTML);}}})});LFM.set("Ajax",{Multicompleter:Class.create(LFM.Ajax.Autocompleter,{initialize:function(element,update,url,options){this.baseInitialize(element,update,options);this.url=url;this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.onHide=function(element,update){window.status="";new Effect.Fade(update,{duration:0.15});};this.form=this.element.up("form");this.submit=this.form.down("input[type=submit]");var defaultParams={};if(this.options.enabled){defaultParams["force"]=1;}else{this.show=function(){return false;};this.startIndicator=function(){return false;};}if(LFM.Session.userName){defaultParams["username"]=LFM.Session.userName;}if(this.options.parameters){defaultParams=Object.extend(defaultParams,this.options.parameters);}this.options.defaultParams=defaultParams;(function(options){var original=options.onShow;options.onShow=function(element,update){update.style.display="block";original(element,update);};})(this.options);this.element.observe("keyup",this.onKeyUp.bindAsEventListener(this));this.update.observe("mouseup",this.onClick.bindAsEventListener(this));this.update.observe("mouseover",this.onHover.bindAsEventListener(this));this.element.observe("focus",this.onFocus.bindAsEventListener(this));this.init();},init:function(){},getUpdatedChoices:function(){this.startIndicator();var entry=encodeURIComponent(this.options.paramName)+"="+encodeURIComponent(this.getToken());this.options.parameters={};this.options.parameters[this.options.paramName]=this.getToken();if(this.options.defaultParams){Object.extend(this.options.parameters,this.options.defaultParams);}this.search();},search:function(){new Ajax.Request(this.url,this.options);this.personalMatches=this.matchPersonalData(this.getToken());},matchPersonalData:function(query){if(!query.length||!this.personalData){return false;}var match_regex=new RegExp(query.replace(/([\\\^\$*+[\]?{}.=!:(|)])/g,"\\$1"),"i");var matches=[];var friends=this.personalData.get("friends");if(friends){friends.each(function(friend,i){var is_match=friend.name.match(match_regex)||(friend.realname&&friend.realname.match(match_regex));if(is_match){matches.push(friend);}});}var groups=this.personalData.get("groups");if(groups){groups.each(function(group,i){var is_match=group.name.match(match_regex);if(is_match){matches.push(group);}});}var labels=this.personalData.get("labels");if(labels){labels.each(function(label,i){var is_match=label.name.match(match_regex)&&label.single_artist!="t";if(is_match){matches.push(label);}});}return matches;},buildEvent:function(result){var datetime_toks=result.date.split("T");var date_toks=datetime_toks[0].split("-");var event_name=result.event||result.artist;var calSheet='<span class="calSheet calSheetSmall">'+'<span title="'+result.date+'">'+'<span class="month">'+LFM.String.shortMonths[date_toks[1]-0]+"</span>"+'<span class="day">'+(date_toks[2]-0)+"</span>"+"</span>"+"</span>";var country=result["country_"+LFM.Session.language]||result["country_en"];return calSheet+"<strong>"+event_name.truncate(25)+"</strong><br>"+result.city.truncate(25)+", "+country.truncate(25);},buildEventTitle:function(result){var event_name=result.event||result.artist;var country=result["country_"+LFM.Session.language]||result["country_en"];return event_name+", "+result.venue+", "+result.city+", "+country;},buildEventURL:function(result){return"/event/"+encodeURIComponent(encodeURIComponent(result.resid));},buildArtist:function(result){var image_url=this.buildArtistImageURL(result);var image='<img src="'+image_url+'" width="34" height="34">';return image+this.buildName(result.artist);},buildArtistTitle:function(result){return result.artist;},buildArtistURL:function(result){return"/music/"+encodeURIComponent(encodeURIComponent(result.artist));},buildArtistImageURL:function(result){if(result.image){return LFM.Session.userserveHost+"/serve/34s/"+result.image;}else{var wsparams={api_key:LFM.Session.wsKey,artist:result.artist,method:"artist.getImageRedirect",size:"smallsquare"};return"http://"+LFM.Session.wsHost+"/2.0/?"+Object.toQueryString(wsparams);}},buildAlbum:function(result){var image_url=this.buildAlbumImageURL(result);var albumCover='<span class="albumCover coverSmall" />'+'<span class="art"><img src="'+image_url+'" width="34" height="34"></span>'+'<span class="jewelcase"></span>'+"</span>";return albumCover+this.buildName(result.album)+"<br>"+result.artist.truncate(25);},buildAlbumTitle:function(result){return result.album+" - "+result.artist;},buildAlbumURL:function(result){return"/music/"+encodeURIComponent(encodeURIComponent(result.artist))+"/"+encodeURIComponent(encodeURIComponent(result.album));},buildAlbumImageURL:function(result){if(result.image){return LFM.Session.userserveHost+"/serve/34s/"+result.image;}else{var wsparams={api_key:LFM.Session.wsKey,artist:result.artist,album:result.album,method:"album.getImageRedirect",size:"smallsquare"};return"http://"+LFM.Session.wsHost+"/2.0/?"+Object.toQueryString(wsparams);}},buildTrack:function(result){var image_url=this.buildArtistImageURL(result);var image='<img src="'+image_url+'" width="34" height="34">';var duration=result.duration?" <small> ("+LFM.timeFormat(result.duration)+")</small>":"";return image+this.buildName(result.track)+duration+"<br>"+result.artist.truncate(25);},buildTrackTitle:function(result){return result.track+" - "+result.artist;},buildTrackURL:function(result){return"/music/"+encodeURIComponent(encodeURIComponent(result.artist))+"/_/"+encodeURIComponent(encodeURIComponent(result.track));},buildTag:function(result){var icon='<img width="30" height="30" src="'+LFM.Session.staticHost+'/flatness/icons/tag/1/tag_30.png">';return icon+this.buildName(result.tag);},buildTagTitle:function(result){return result.tag;},buildTagURL:function(result){return"/tag/"+encodeURIComponent(encodeURIComponent(result.tag));},buildUser:function(result){var image=this.buildResImage(result,"/flatness/catalogue/noimage/2/default_user_small.png");var user=image+this.buildName(result.name);if(result.realname){user+="<br>"+result.realname.truncate(25);}return user;},buildUserTitle:function(result){var title=result.name;if(result.realname){title+=" - "+result.realname;}return title;},buildUserURL:function(result){return"/user/"+encodeURIComponent(encodeURIComponent(result.name));},buildGroup:function(result){var image=this.buildResImage(result,"/flatness/catalogue/noimage/2/default_group_small.png");var name;if(result.group){name=this.buildName(result.group);}else{name=this.buildName(result.name);}return image+name;},buildGroupTitle:function(result){return result.name||result.group;},buildGroupURL:function(result){var name=result.name||result.group;return"/group/"+encodeURIComponent(encodeURIComponent(name));},buildLabel:function(result){var image=this.buildResImage(result,"/flatness/catalogue/noimage/2/default_label_small.png");var name;if(result.label){name=this.buildName(result.label);}else{name=this.buildName(result.name);}return image+name;},buildLabelTitle:function(result){return result.name||result.label;},buildLabelURL:function(result){var root;var name=result.name||result.label;if(result.single_artist=="t"){root="/artist/";}else{root="/label/";}return root+encodeURIComponent(encodeURIComponent(name));},buildName:function(name){return"<strong>"+name.truncate(25)+"</strong>";},buildResTitle:function(result){return result.name;},buildResImage:function(result,defaultImage){var image_url=LFM.Session.staticHost+defaultImage;if(result.image_id){image_url=LFM.Session.userserveHost+"/serve/34s/"+result.image_id+".jpg";}else{if(result.image){image_url=LFM.Session.userserveHost+"/serve/34s/"+result.image;}}var image='<img src="'+image_url+'" width="34" height="34">';return image;},buildItemLink:function(result){var result_restype=result.res?result.res.type:result.restype;var restype=LFM.resTypeLookup[result_restype];if(!restype){LFM.warn("no restype found: "+result_restype);}else{try{var url=this["build"+restype+"URL"](result);if(!this.urls[url]){this.urls[url]=restype;var item=this["build"+restype](result);var title=this["build"+restype+"Title"](result);var link=new Element("a",{href:url+"?ac="+encodeURIComponent(this.getToken()),title:title}).addClassName(restype.toLowerCase()+"Item").update(item);return link;}}catch(e){LFM.warn(restype,e);}}},buildSearchLink:function(result){var search_url=this.form.action+"?"+this.form.serialize();var link=new Element("a",{href:search_url}).addClassName("viewAll");return new Element("span").addClassName("moduleOptions").update(result).wrap(link);},setOptions:function(options){options=options||{};this.options=Object.extend({method:"get",onShow:function(element,update){if(!update.style.position||update.style.position=="absolute"){update.style.position="absolute";Position.clone(element,update,{setHeight:false,setWidth:false,offsetTop:element.offsetHeight});}Effect.Appear(update,{duration:0.15});}},options);},markNext:function(){if(this.index===null){this.index=0;}else{if(this.index<this.entryCount-1){this.index++;}}var entry=this.getCurrentEntry();if(entry){window.status=entry.down("a").href;}else{window.status="";}},markPrevious:function(){if(this.index>0){this.index--;}else{this.index=null;}var entry=this.getCurrentEntry();if(entry){window.status=entry.down("a").href;}else{window.status="";}},getEntry:function(index){if(index!==null){return this.update.down("li.item",index);}},updateElement:function(item){if(item){var link=item.down("a");if(link){LFM.redirect(link.href);return true;}}},addLinkedItem:function(result,list){var link;var restype=result.res?result.res.type:result.restype;if(restype){link=this.buildItemLink(result);}else{link=this.buildSearchLink(result);}if(link){var item=link.wrap(new Element("li").addClassName("item"));list.insert(item);return item;}return false;},onBlur:function(e){this.blurTimeout=setTimeout(function(){this.hide();this.hasFocus=false;this.active=false;}.bind(this),250);},onFocus:function(e){if(this.options.enabled){this.loadPersonalData();}},loadPersonalData:function(){if(this.personalData||!LFM.Session.loggedIn||!LFM.Session.userURL||this.unauthorised){return false;}LFM.info("AC: Load personal data");new Ajax.Request(LFM.Session.userURL+"/acdata",{method:"get",parameters:{ajax:1},onSuccess:function(transport){response=new LFM.Ajax.Response(transport);if(response.isSuccess()){LFM.info("AC: Personal data loaded");this.personalData=response;}else{if(response.isUnauthorised()){this.unauthorised=true;}}}.bind(this)});},onHover:function(e){var link=e.findElement("a");if(link){if(this.index!=link.autocompleteIndex){this.index=link.autocompleteIndex;this.render();}}},onClick:function(e){this.element.focus();clearTimeout(this.blurTimeout);var link=e.findElement("a");},onKeyPress:function(e){if(this.active){switch(e.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:if(this.options.enabled&&this.getCurrentEntry()){this.selectEntry();e.stop();}break;case Event.KEY_ESC:if(this.options.enabled){this.hide();this.active=false;e.stop();}return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:if(this.options.enabled){this.markPrevious();this.render();e.stop();}return;case Event.KEY_DOWN:if(this.options.enabled){this.markNext();this.render();e.stop();}return;}}else{if(e.keyCode==Event.KEY_TAB||e.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&e.keyCode==0)){return;}}this.changed=true;this.hasFocus=true;if(this.observer){clearTimeout(this.observer);}this.observer=setTimeout(this.onObserverEvent.bind(this),this.options.frequency*1000);},onKeyUp:function(e){this.changed=false;var token=this.getToken();if(token.length>=this.options.minChars&&token!=this.lastToken){this.startIndicator();}},onObserverEvent:function(){this.changed=false;var token=this.getToken();if(token.length>=this.options.minChars){if(token!=this.lastToken&&token!=this.element.getAttribute("placeholder")){this.getUpdatedChoices();}else{this.render();}}else{this.active=false;this.hide();}this.lastToken=token;this.oldElementValue=this.element.value;},getToken:function(){return $F(this.element);},processResults:function(results){var list=new Element("ul");if(results){this.urls={};results.each(function(result,index){this.addLinkedItem(result,list);},this);}this.addViewAll(list,results.length);return list;},addViewAll:function(list,result_count){this.addLinkedItem(LFM.String.siteSearchViewAll.replace("QUERY",this.getToken().escapeHTML()),list);this.entryCount=result_count+1;},onComplete:function(transport){if(this.changed||!this.hasFocus){return false;}var results=new Array,result_count=0;try{var response=transport.responseText.evalJSON();results=response.response.docs;}catch(err){LFM.warn("JSON error: "+transport.responseText);}if(this.personalMatches&&this.personalMatches.length){var personal_slots=Math.min(this.personalMatches.length,3);results=this.personalMatches.slice(0,personal_slots).concat(results.slice(0,10-personal_slots));}result_count=results.length;var list=this.processResults(results);this.updateChoices(list,result_count);},updateChoices:function(list,length){this.update.update(list);var header=new Element("p",{"class":"header"});if(length){header.update(LFM.String.siteSearchSuggestions);}else{header.update(LFM.String.siteSearchNoSuggestions).addClassName("empty");}this.update.insert({"top":header});if(LFM.Session.loggedIn&&!this.personalData){var dataDownMessage=new Element("div").addClassName("message messageWarn").update(LFM.String.autocompletePersonalDataDown);this.update.insert({"bottom":dataDownMessage});}this.update.select("li.item a").each(function(link,index){link.autocompleteIndex=index;},this);this.stopIndicator();this.index=null;this.render();}})});LFM.set("Ajax",{GroupedMulticompleter:Class.create(LFM.Ajax.Multicompleter,{resTypeGroups:[LFM.resTypes.ARTIST,LFM.resTypes.ALBUM,LFM.resTypes.TRACK,LFM.resTypes.EVENT,LFM.resTypes.TAG,LFM.resTypes.USER,LFM.resTypes.GROUP,LFM.resTypes.LABEL],init:function(){this.update.addClassName("grouped");},buildArtist:function(result){var image_url=this.buildArtistImageURL(result);var image='<span class="img"><span><img src="'+image_url+'" width="34" height="34" /></span></span>';return image+'<strong class="artist">'+result.artist.truncate(25)+"</strong>";},buildTrack:function(result){var image_url=this.buildArtistImageURL(result);var image='<span class="img"><span><img src="'+image_url+'" width="34" height="34" /></span></span>';var duration=result.duration?' <small class="time"> ('+LFM.timeFormat(result.duration)+")</small>":"";return image+'<strong class="track">'+result.track.truncate(20)+"</strong>"+duration+"<br>"+result.artist.truncate(25);},buildTag:function(result){var icon='<img width="20" height="20" src="'+LFM.Session.staticHost+'/flatness/icons/activity/tagged.png">';return icon+'<strong class="tag">'+result.tag.truncate(25)+"</strong>";},processResults:function(results,list){var list=new Element("ul");if(results){this.urls={};var groupedResults=this.groupResults(results);var group,groupTitle,groupList,plural;this.resTypeGroups.each(function(restype,index){if(groupedResults[restype]){group=new Element("li");plural=(restype==LFM.resTypes.USER)?LFM.String.resTypePlural["friends"]:LFM.String.resTypePlural[restype];groupTitle=new Element("h3").update(plural).addClassName(LFM.resTypeLookup[restype].toLowerCase());groupList=new Element("ul");groupedResults[restype].each(function(result,index){this.addLinkedItem(result,groupList);},this);group.insert(groupTitle);group.insert(groupList);list.insert(group);}},this);}this.addViewAll(list,results.length);return list;},groupResults:function(results){var groups={},restype;results.each(function(result,index){restype=result.res?result.res.type:result.restype;if(!groups[restype]){groups[restype]=[];}groups[restype].push(result);},this);return groups;}})});LFM.set("Ajax",{SideGroupedMulticompleter:Class.create(LFM.Ajax.GroupedMulticompleter,{init:function(){this.update.addClassName("grouped sidegrouped");},processResults:function(results,list){var table=new Element("table",{cellspacing:0,cellpadding:0,border:0});var tbody=new Element("tbody");var group_count=0;if(results){this.urls={};var groupedResults=this.groupResults(results);var group,groupTitle,groupList,plural;this.resTypeGroups.each(function(restype,index){if(groupedResults[restype]){group_count++;group=new Element("tr");if(group_count%2==0){group.addClassName("alt");}plural=(restype==LFM.resTypes.USER)?LFM.String.resTypePlural["friends"]:LFM.String.resTypePlural[restype];groupTitle=new Element("h3").update(plural).addClassName(LFM.resTypeLookup[restype].toLowerCase());groupList=new Element("ul");groupedResults[restype].each(function(result,index){this.addLinkedItem(result,groupList);},this);group.insert(new Element("th").update(groupTitle));var group_cell=new Element("td").update(groupList);if(group_count==1){group_cell.addClassName("first");}group.insert(group_cell);tbody.insert(group);}},this);}var viewAllRow=new Element("tr");if(group_count%2==0){viewAllRow.addClassName("alt");}var viewAllList=new Element("ul");this.addViewAll(viewAllList,results.length);viewAllRow.insert(new Element("th"));viewAllRow.insert(new Element("td",{"class":"viewAll"}).update(viewAllList));tbody.insert(viewAllRow);table.update(tbody);return table;}})});
