var R={}
try{document.execCommand("BackgroundImageCache",false,true);}catch(e){}
Number.prototype.toFixed=function(fraction_digits){var m=Math.pow(10,fraction_digits);return Math.round(this*m,0)/m;}
document.viewport={getDimensions:function(){var dimensions={},B=Prototype.Browser;$w('width height').each(function(d){var D=d.capitalize();if(B.WebKit&&!document.evaluate){dimensions[d]=self['inner'+D];}else if(B.Opera&&parseFloat(window.opera.version())<9.5){dimensions[d]=document.body['client'+D]}else{dimensions[d]=document.documentElement['client'+D];}});return dimensions;},getWidth:function(){return this.getDimensions().width;},getHeight:function(){return this.getDimensions().height;},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop);}};Form.Hacks={serialize:function(form,getHash){return Form.serializeElements(Form.getElements(form),true);}};Object.extend(Form,Form.Hacks);Object.extend(Effect.Highlight.prototype,{initialize:function(element){this.element=$(element);var options=Object.extend({startcolor:'#eaf7e5'},arguments[1]||{});this.start(options);}});Ajax.Updater.Hacks=Ajax.Request.Hacks={setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(Browser.isMSIE()&&this.method!='post'){headers['If-Modified-Since']=new Date(0)}
if(this.method=='post'){headers['Content-type']=this.options.contentType+
(this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005)
headers['Connection']='close';}
if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(typeof extras.push=='function')
for(var i=0,length=extras.length;i<length;i+=2)
headers[extras[i]]=extras[i+1];else
$H(extras).each(function(pair){headers[pair.key]=pair.value});}
for(var name in headers)
this.transport.setRequestHeader(name,headers[name]);}};Object.extend(Ajax.Request.prototype,Ajax.Request.Hacks);Object.extend(Ajax.Updater.prototype,Ajax.Updater.Hacks);Ajax.InPlaceEditor.Hacks={enterHover:function(){if(this.saving)return;Element.addClassName(this.element,'hover');},leaveHover:function(){Element.removeClassName(this.element,'hover');if(this.saving)return;}};Object.extend(Ajax.InPlaceEditor.prototype,Ajax.InPlaceEditor.Hacks);Effect.Shake=function(element){element=$(element);var oldStyle={top:element.getStyle('top'),left:element.getStyle('left')};return new Effect.Move(element,{x:2,y:0,duration:0.05,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-5,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:5,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-5,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:5,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-2,y:0,duration:0.05,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle);}})}})}})}})}})}});}
Effect.Scroll=Class.create();Object.extend(Object.extend(Effect.Scroll.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);var options=Object.extend({x:0,y:0,mode:'absolute'},arguments[1]||{});this.start(options);},setup:function(){if(this.options.continuous&&!this.element._ext){this.element.cleanWhitespace();this.element._ext=true;this.element.appendChild(this.element.firstChild);}
this.originalLeft=this.element.scrollLeft;this.originalTop=this.element.scrollTop;if(this.options.mode=='absolute'){this.options.x-=this.originalLeft;this.options.y-=this.originalTop;}else{}},update:function(position){this.element.scrollLeft=this.options.x*position+this.originalLeft;this.element.scrollTop=this.options.y*position+this.originalTop;}});var autocompletes=new Object();var suggesters=new Object();var saveRequiredOn=false;var markdownLoaded=false;var browser=null;var queue={start:0};var OUNCES_TO_GRAMS=28.3495231;var GRAMS_TO_OUNCES=0.0352739619;var METERS_TO_YARDS=1.0936133;var YARDS_TO_METERS=0.9144;var wmd_instances=new Object();var wmd_delayed=new Array();var balloon={timer:null,cur:null};var pageless={mouse_state:0,scrolling:false,page:1,pending:0,total_pages:null,loading:false,disabled:false,page_id:0};function getViewportSize(){if(typeof window.innerWidth!='undefined'){return[window.innerWidth,window.innerHeight];}else{return[document.documentElement.clientWidth,document.documentElement.clientHeight];}}
function addDOMLoadEvent(func){if(!window.__load_events){var init=function(){if(arguments.callee.done)return;arguments.callee.done=true;if(window.__load_timer){clearInterval(window.__load_timer);window.__load_timer=null;}
for(var i=0;i<window.__load_events.length;i++){window.__load_events[i]();}
window.__load_events=null;};if(document.addEventListener){document.addEventListener("DOMContentLoaded",init,false);}
if(/WebKit/i.test(navigator.userAgent)){window.__load_timer=setInterval(function(){if(/loaded|complete/.test(document.readyState)){init();}},10);}
window.onload=init;window.__load_events=[];}
window.__load_events.push(func);}
function getNameAndId(element,arrayNotation){var result;if(element.id){var indexStart=arrayNotation?element.id.indexOf('['):element.id.lastIndexOf('_');if(indexStart>=0){var name=element.id.substring(0,indexStart);var id=element.id.substring(indexStart+1,element.id.length-(arrayNotation?1:0));result={'name':name,'id':id};}}
return result;}
function getId(element,arrayNotation){return getNameAndId(element,arrayNotation).id;}
function anchor(name){document.location.href='#'+name;}
function prependPath(s){return R.utils.prependPath(s);}
function photoParameters(src){var p="owner="+escape(document.location.pathname.replace("/photos",""));if(src)p+="&src="+src;return p;}
function positionContainer(container,rel_to){yoff=document.documentElement.scrollTop;yoff+=180;$(container).style['top']=yoff+"px";}
function navigateToFirstLink(element,new_window){var elements=element.getElementsByTagName('a');if(elements.length>0){var href=elements[0].getAttribute('href');if(!new_window){document.location.href=href;}else{window.open(href);}}}
function preventSubmitOnEnter(id){$$('#'+id+' input').each(function(element){Event._observeAndCache(element,'keypress',function(event){if((event.charCode||event.keyCode)==13){Event.stop(event);}},false);});}
function navigateWithSelect(select){document.location.replace(select.options[select.selectedIndex].value)}
function focusFirstFormElement(){var form=$$('form').first();if(form){var element=form.findFirstElement();if(element&&element.tagName.toLowerCase()=='input'){element.activate();}}}
function addDataToMarker(marker,data){marker.data=data;return marker;}
function locationMapClicked(marker){if(marker&&marker.data){Element.show('map_indicator');new Ajax.Updater('location_results','/people/geo/browse?'+$H(marker.data).toQueryString(),{method:'get',onComplete:function(){Element.hide('map_indicator')}});}}
function photoDeleted(id){var border=$('sortablephoto_'+id);new Effect.DropOut(border);}
function tableRowSelected(row){nid=getNameAndId(row,true);if(nid){if(nid.name=='edit_pattern'){document.location.href='/patterns/edit/'+nid.id;}else{document.location.href=prependPath(nid.id);}}}
function projectPhotoUpdated(){}
function showForumReply(link,id,depth){var p=link;var indicator;while(p&&p.getElementsByClassName('indicator').length==0){p=p.parentNode;}
if(p){var indicators=p.getElementsByClassName('indicator');if(indicators.length>0){indicator=indicators[0];}}
var container=link.parentNode.parentNode.parentNode;var threadContainer=$(container).getElementsByClassName('thread')[0];var bit=$(threadContainer).getElementsByClassName('parent_post');if(bit.length>0&&Element.visible(bit[0])){new Effect.BlindUp(bit[0]);}else{var url="/forum_posts/parent/"+id;if(depth){url+="?depth="+depth;}
if(indicator){Element.show(indicator);}
new Ajax.Updater(threadContainer,url,{asynchronous:true,evalScripts:true,onComplete:function(){Element.hide(indicator);var bit=$(threadContainer).getElementsByClassName('parent_post')[0];new Effect.Appear(bit);}});}}
function suggest(event,model,field,force){var id=model+'_'+field+'_id';var name=model+'_'+field+'_name';var prompted=model+'_'+field+'_prompted';var value=$(name).value;var previous=autocompletes[id];var changed=!previous||(previous!=value);autocompletes[id]=value;if($(prompted)){$(prompted).value="false";}
if(changed||force){if(changed){$(id).value="";}
if(value!=""){var controller;if(field=='pattern'){if($('pattern_information')){new Effect.Fade('pattern_information')}
controller='patterns';}else if(field=='yarn'){if($('yarn_information')){new Effect.Fade('yarn_information')}
controller='yarns';}else if(field=='shop'){controller='shops';}
if(controller){var url='/'+controller+'/suggestions?src='+model+'_'+field+'&query='+escape(value);if(suggesters[controller]!=url){suggesters[controller]=url;var box=name+'_suggestions';var indicator=$(name+'_indicator');if(indicator){indicator.src='/images/circle-ball-dark-antialiased.gif';}
new Ajax.Request(url+'&suggestions='+box,{asynchronous:true,evalScripts:true,onComplete:function(){suggesters[controller]=null;if(indicator)indicator.src='/images/silk-link.png';}});}}}}}
function packUnitsPrecision(units){if(units=='ounces'){return 2;}else if(units=='yards'||units=='meters'){return 1;}else{return 0;}}
function packWeightUnitsChanged(select,pack_id,update_totals){var units=$F(select);var multiplier=(units=='ounces')?GRAMS_TO_OUNCES:OUNCES_TO_GRAMS;var field=$('packs_'+pack_id+'_skein_weight');if(field.value!=''){field.value=(field.value*multiplier).toFixed(packUnitsPrecision(units));}
$('packs_'+pack_id+'_skein_weight_units').selectedIndex=select.selectedIndex;$('packs_'+pack_id+'_weight_units').selectedIndex=select.selectedIndex;calculatePackTotals(pack_id);}
function packLengthUnitsChanged(select,pack_id,update_totals){var units=$F(select);var multiplier=(units=='yards')?METERS_TO_YARDS:YARDS_TO_METERS;var field=$('packs_'+pack_id+'_skein_length');if(field.value!=''){field.value=(field.value*multiplier).toFixed(packUnitsPrecision(units));}
$('packs_'+pack_id+'_skein_length_units').selectedIndex=select.selectedIndex;$('packs_'+pack_id+'_length_units').selectedIndex=select.selectedIndex;calculatePackTotals(pack_id);}
function calculatePackTotals(pack_id){var calculated_totals=$('packs_'+pack_id+'_calculated_totals');var weight_units=$F('packs_'+pack_id+'_skein_weight_units');var length_units=$F('packs_'+pack_id+'_skein_length_units');var weight=$F('packs_'+pack_id+'_skein_weight');var length=$F('packs_'+pack_id+'_skein_length');var skeins=$('packs_'+pack_id+'_formatted_skeins').value;var total_weight=(weight*skeins).toFixed(packUnitsPrecision(weight_units));if(!isNaN(total_weight)&&skeins!=''){$('packs_'+pack_id+'_calculated_total_weight').innerHTML=total_weight+" "+weight_units;$('packs_'+pack_id+'_total_weight').value=total_weight;}else{$('packs_'+pack_id+'_calculated_total_weight').innerHTML="";$('packs_'+pack_id+'_total_weight').value="";}
var total_length=(length*skeins).toFixed(packUnitsPrecision(length_units));if(!isNaN(total_length)&&skeins!=''){$('packs_'+pack_id+'_calculated_total_length').innerHTML=total_length+" "+length_units;$('packs_'+pack_id+'_total_length').value=total_length;}else{$('packs_'+pack_id+'_calculated_total_length').innerHTML=""
$('packs_'+pack_id+'_total_length').value="";}
var both=!isNaN(total_length)&&!isNaN(total_weight)&&skeins!='';$('packs_'+pack_id+'_calculated_total_divider').innerHTML=both?" / ":"";if(skeins!=''&&(!isNaN(total_length)||!isNaN(total_weight))){if(!Element.visible(calculated_totals)){Element.show(calculated_totals);}}}
function editPackTotals(pack_id){$('packs_'+pack_id+'_formatted_skeins').value='';$('packs_'+pack_id+'_skein_priority').value='false';Element.hide('packs_'+pack_id+'_skein_field');Element.hide('packs_'+pack_id+'_units');Element.show('packs_'+pack_id+'_totals');}
function editPackSkeins(pack_id){$('packs_'+pack_id+'_skein_priority').value='true';Element.show('packs_'+pack_id+'_skein_field');Element.show('packs_'+pack_id+'_units');Element.hide('packs_'+pack_id+'_totals');}
function suggestionSelected(field,selected_id,selected_name){var id=$(field+'_id')
var name=$(field+'_name')
if(!selected_id){selected_id='';}
id.value=selected_id;autocompletes[field]=selected_name;var indexed=false;if(field.indexOf('packs_')==0){indexed=true;indexed_summary=$(field+"_summary");}
if(!selected_id){if(field=='project_pattern'){$('pattern_summary_content').innerHTML='';Element.hide($('pattern_summary'));}else if(field=='queued_project_pattern'){Element.hide($('linked_fields'));Element.show($('personal_fields'));}
if(field=='project_yarn'||field=='stash_yarn'){$('yarn_summary_content').innerHTML='';Element.hide($('yarn_summary'));}
if(field=='stash_yarn'){$('stash_summary').innerHTML='';Element.hide($('stash_summary'));}else if(indexed&&field.indexOf('_yarn')>0){updateYarnSummaries(selected_id,field.indexOf('packs')>=0,field);}}else{name.value=selected_name;if(field=='project_pattern'){updatePatternSummary(selected_id);Element.show($('pattern_summary'));}else if(field=='queued_project_pattern'){Element.hide($('personal_fields'));new Ajax.Request(prependPath('pattern_selected?pattern_id='+selected_id),{asynchronous:true,evalScripts:true,method:'get'})}
if(field=='stash_yarn'){updateStashSummary(selected_id);Element.show($('stash_summary'));updateYarnSummary(selected_id);Element.show($('yarn_summary'));}else if(field.indexOf('_yarn')>0){updateYarnSummaries(selected_id,field.indexOf('packs')>=0,field);}}
suggestionsClosed(field);}
function suggestionsClosed(field,prompt,skip_effect){var suggestions=$(field+'_name_suggestions')
var prompted=$(field+'_prompted')
if($(prompted)){$(prompted).value=prompt?"true":"false";}
if(!prompt){if(suggestions){if(skip_effect){Element.hide(suggestions);}else{new Effect.DropOut(suggestions);}}}else{if(suggestions){new Effect.Fade(suggestions);}}}
function suggestionPromptCancelled(field,prompt){var prompted=$(field+'_prompted')
if($(prompted)){$(prompted).value="false";}
if(field=='queued_project_pattern'){new Effect.Fade('pattern_information',{queue:'end'})}else if(field=='queued_project_yarn'){new Effect.Fade('yarn_information',{queue:'end'})}}
function changeTab(tabId){tab=$(tabId);if(tab.className=='static_tab'){a=tab.getElementsByTagName("a")[0];document.location.href=a.getAttribute("href");}else{$$('.tabs li').each(function(li){li.id='';});$$('.panel').each(function(panel){Element.hide(panel)});name=tabId.substring(0,tabId.indexOf("_tab"));panelId=name+"_panel";$(tabId).parentNode.id='current';Element.show($(panelId));key=document.body.className+"_tab";new Ajax.Request("/preferences/save",{method:'post',postBody:'key='+key+"&value="+name})
return false;}}
function updateDroppables(){$$('.droppable_photo').each(function(element){if(element.droppable){return;}
element.droppable=true;var cropper=$('cropper_'+getId(element));Event.observe(element,'mouseover',function(event){if(cropper)cropper.style.display='block';});Event.observe(element,'mouseout',function(event){if(cropper)cropper.style.display='none';});Droppables.add(element,{hoverclass:'hover',accept:'draggable_photo',onDrop:function(drop){var src=drop.getAttribute("original")?drop.getAttribute("original"):drop.src;if(element.id=="photo_placeholder"){var indicator=$('placeholder_indicator');indicator.style.display='block';new Ajax.Request('/photos',{method:'post',postBody:photoParameters(src),onComplete:function(req){indicator.style.display='none';new Insertion.Before('photo_placeholder_border',req.responseText);updateDroppables();updateSortables();}});}else{element.style.backgroundImage="url('"+src+"')";element.style.backgroundRepeat="no-repeat";element.style.backgroundPosition="0px 0px";new Ajax.Request('/photos/'+getId(element),{method:'post',postBody:photoParameters(src)+"&_method=put",onComplete:function(req){new Insertion.Before('photo_placeholder_border',req.responseText);updateDroppables();}});}}});if(cropper){var droppablePhoto=new Draggable(cropper,{'reverteffect':function(element,top_offset,left_offset){new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:0});}});droppablePhoto.startDrag=function(event){};droppablePhoto.endDrag=function(event){this.previousLeft=null;this.previousTop=null;if(this.cropperPos){cropper.style.left=this.cropperPos[0]+"px";cropper.style.top=this.cropperPos[1]+"px";cropper.style.visibility="visible";}
if(this.moved){params=photoParameters()+'&_method=put&x_offset='+this.xOffset+"&y_offset="+this.yOffset;new Ajax.Request('/photos/'+getId(element),{method:'post',postBody:params});}
Event.stop(event);};droppablePhoto.updateDrag=function(event,pointer){var loc=Position.cumulativeOffset(element);var left=pointer[0]-loc[0];var top=pointer[1]-loc[1];if(!this.cropperPos){this.cropperPos=[cropper.offsetLeft,cropper.offsetTop];}
if(this.previousLeft&&this.previousTop){topNudge=top-this.previousTop;leftNudge=left-this.previousLeft;if(element.style.backgroundPosition){var previous=element.style.backgroundPosition.split(" ");var previousLeft=parseInt(previous[0].replace("px",""));var previousTop=parseInt(previous[1].replace("px",""));this.yOffset=previousLeft+leftNudge;this.xOffset=previousTop+topNudge;cropper.style.left=(cropper.offsetLeft+leftNudge)+"px";cropper.style.top=(cropper.offsetTop+topNudge)+"px";cropper.style.visibility="hidden";element.style.backgroundPosition=this.yOffset+"px "+this.xOffset+"px";this.moved=true;}}
this.previousLeft=left;this.previousTop=top
Event.stop(event);};}});}
function updateDraggables(){$$('.draggable_photo').each(function(element){new Draggable(element,{'ghosting':true,'revert':true,'reverteffect':function(element,top_offset,left_offset){new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:0});}});});}
function updateSortables(){if($('photo_browser')){Sortable.create('photo_browser',{tag:'div',only:'sortable',constraint:null,overlap:'vertical',onUpdate:function(huh){params=Sortable.serialize('photo_browser',{'tag':'div','name':'photo_order'});new Ajax.Request('/photos/reorder',{method:'post',postBody:params,evalScripts:true});}});}}
function updateZoomables(){$$('.zoomable_photo').each(function(element){Event.observe(element,'click',function(e){R.photos.zoom(element);Event.stop(e);});});}
function saveGroupAssociation(select,owner_type,owner_id){var params="owner_type="+owner_type+"&owner_id="+owner_id;var group_id=$F(select);if(group_id!=''){Element.show('group_indicator');new Ajax.Request('/groups/'+group_id+'/associate',{method:'post',postBody:params,evalScripts:true,onComplete:function(){Element.hide('group_indicator')}});}}
function removeGroupAssociation(group_id,owner_type,owner_id){var params="owner_type="+owner_type+"&owner_id="+owner_id;new Ajax.Request('/groups/'+group_id+'/disassociate',{method:'post',postBody:params,evalScripts:true,onComplete:function(){Element.hide('group_indicator')}});}
function saveQueueSortOrder(updates){updateQueueNumberingInPlace(Sortable.sequence(updates));var ids=new Array();$$('#queued_projects .queued_project').each(function(element){if(Element.visible(element)){ids.push("queued_project[]="+getId(element));}});new Ajax.Request(prependPath('simple_sort?'+ids.join('&')+"&start="+queue.start),{asynchronous:true});}
function editQueueItem(id,source){var elementId='add_to_queue_dialog';R.utils.initializeRedbox(elementId);RedBox.loading();var url=prependPath(id+'/edit').replace('/organize/','/');if(source){url+="?source="+source;}
new Ajax.Updater(elementId,url,{asynchronous:true,evalScripts:true,method:'get',onComplete:function(request){RedBox.addHiddenContent(elementId);}});}
function deleteQueueItem(id){if(confirm('Are you sure that you want to remove this item from your queue?')){new Ajax.Request(prependPath(id),{asynchronous:true,evalScripts:true,method:'delete'});}}
function updateLibrarySortables(){if($('shelved_books')){Sortable.create('shelved_books',{tag:'div',only:'volume',handle:'mover',constraint:null,scroll:window,onUpdate:saveLibrarySortOrder});}}
function saveLibrarySortOrder(){var ids=new Array();$$('#shelved_books .volume').each(function(element){if(Element.visible(element)){ids.push("volume[]="+getId(element));}});new Ajax.Request(prependPath('sort?'+ids.join('&')),{asynchronous:true});}
function setQueueStart(i){queue.start=i;}
function updateQueueNumbering(){var position=queue.start;$$('#queued_projects input.sort_field').each(function(element){if(Element.visible(element)){element.value=position++;}});}
function updateQueueNumberingInPlace(sequence){var numbers=$$('#queued_projects input.sort_field').collect(function(element){return parseInt(element.value);});numbers.sort(function(a,b){return a-b;});$A(sequence).each(function(id,index){console.log('sort_order_'+id+' = '+numbers[index]+" ["+index+"]");$('sort_order_'+id).value=numbers[index];});}
function updateEndlessPageless(){var eop=$('end_of_page');if(eop&&pageless){Event.observe(document,'mousedown',function(){pageless.mouse_state=1;});Event.observe(document,'mouseup',function(){pageless.mouse_state=0;pageless.scrolling=false;});Event.observe(document,'mousemove',function(){pageless.scrolling=false;});Event.observe(window,'scroll',function(){checkPageless();});}}
function checkPageless(){if(!pageless.loading&&!pageless.disabled&&pageless.pending==0){new ExclusiveAction(function(){if(!pageless.loading&&!pageless.disabled&&pageless.pending==0){var viewport=getViewportSize();var threshold=viewport[1]*1.75;var eop=$('end_of_page');if(eop&&Position.page(eop)[1]<threshold){pageless.loading=true;pageless.page++;Element.show('end_of_page_indicator');var project_form=$('project_search_form');if(project_form){var params=Form.serialize(project_form);params['page']=pageless.page;new Ajax.Request(prependPath(''),{asynchronous:true,evalScripts:true,parameters:params});}else{new Ajax.Request(prependPath('?page='+pageless.page),{asynchronous:true,evalScripts:true,method:'get'});}}}});}}
function pagelessReset(){pageless.disabled=false;pageless.loading=false;pageless.page=1;}
function pagelessLoaded(){if($('end_of_page_indicator')){Element.hide('end_of_page_indicator');if(pageless.page>=pageless.total_pages){Element.hide('end_of_page')
pageless.disabled=true;}
pageless.loading=false;}}
function updateMenuLinks(parentId){var selector='.menu_link a';if(parentId){selector=parentId+" "+selector;}
$$(selector).each(function(element){Event.observe(element,'click',function(event){Event.stop(event);menuId=element.parentNode.id+"_menu";observerClass=element.parentNode.id+"_observer";$$('#'+menuId+' .close a').each(function(element){Event.observe(element,'click',function(event){Element.hide(menuId);Event.stop(event);});});if(Element.visible(menuId)){Effect.SlideUp(menuId,{duration:.5});Effect.Fade(menuId,{duration:.75});$$('.'+observerClass).each(function(element){Element.removeClassName(element,'active_menu');});}else{var selectInput=function(){var input=$$("#"+menuId+" input").first();if(input){Field.focus(input)}};$$('.'+observerClass).each(function(element){Element.addClassName(element,'active_menu');});Effect.SlideDown(menuId,{duration:.5,afterFinish:selectInput});Effect.Appear(menuId,{duration:.75,afterFinish:selectInput});}});});}
function updateRatingControls(parentId){var prefix=parentId?'#'+parentId+' ':'';$$(prefix+'.rateable .rating li').each(function(element){var ul=element.parentNode;Event.observe(element,'click',function(){var ul=element.parentNode;var ratingType=ul.id;var rating=ul.getAttribute('rating');var max=0;if(rating){var r=0;for(var i=0;i<ul.childNodes.length;i++){var node=ul.childNodes[i];if(node.nodeType==1){max++;if(++r<=rating){Element.addClassName(node,"filled");}else{Element.removeClassName(node,"filled");}
if(r==rating){Element.addClassName(node,"selected");if(node.id){Element.addClassName(node,node.id+'_selected');}}else{Element.removeClassName(node,"selected");if(node.id){Element.removeClassName(node,node.id+'_selected');}}}}
ul.saved_rating=rating;if(ul.className.indexOf('zero_based')>=0){rating--;}
if(ul.className.indexOf('progress')>=0){rating=(100.0/max)*rating;var name=$(ul.id+"_name");if(name){name.innerHTML=rating+'%';}
var rater=$(ul.id+"_rater");if(rater){new Effect.Highlight(name,{duration:1});Element.hide(rater);}}
new Ajax.Request('/ratings/'+ratingType,{method:'post',postBody:'_method=put&rating='+rating,onComplete:function(req){}});}});Event.observe(element,'mouseover',function(){var ul=element.parentNode;var max=0;var rating=0;var rated_element=false;for(var i=0;i<ul.childNodes.length;i++){var node=ul.childNodes[i];if(node.nodeType==1){if(!rated_element){rating++;Element.addClassName(node,'hover');Element.removeClassName(node,'dim');}else{Element.addClassName(node,'dim');Element.removeClassName(node,'hover');}
max++;}
if(node==element){rated_element=true;}}
var score=$(ul.id+"_score");if(score&&ul.getAttribute('rating')!=rating){percent=parseFloat(rating)/parseFloat(max);if(percent==1){score.innerHTML='impossible'}else if(percent>.7){score.innerHTML='difficult'}else if(percent>.3){score.innerHTML='medium'}else if(percent>.1){score.innerHTML='easy'}else{score.innerHTML='piece o\' cake'}}
ul.setAttribute("rating",rating)});});$$(prefix+'.rateable ul.rating').each(function(element){Event.observe(element,'mouseout',function(){var ul=element;for(var i=0;i<ul.childNodes.length;i++){if(ul.childNodes[i].nodeType==1){var li=ul.childNodes[i];Element.removeClassName(li,'hover');Element.removeClassName(li,'dim');}}
var score=$(ul.id+"_score");if(score)score.innerHTML='';});});}
function updateColorFamily(option){var color=option.innerHTML.toLowerCase();if(color&&color.length>0&&color.indexOf('color')<0){option.style.background="white url(/images/colors/"+color+".jpg) repeat-y";}}
function updateDialogLinks(){$$("a.dialog").each(function(a){Event.observe(a,'click',function(event){var box=a.id+'_redbox';initializeRedbox(box);RedBox.loading();new Ajax.Updater(box,a.getAttribute('href'),{asynchronous:true,onComplete:function(request){RedBox.addHiddenContent(box);},evalScripts:true});Event.stop(event)});});}
function updatePatternSummary(id){new Ajax.Updater('pattern_summary','/patterns/library/'+id+"/summary",{onComplete:function(){new Effect.Highlight('pattern_summary_content',{duration:.5});updateRatingControls('pattern_summary');}});}
function updateYarnSummary(id){if($('yarn_summary')){new Ajax.Updater('yarn_summary','/yarns/library/'+id+"/summary",{onComplete:function(){new Effect.Highlight('yarn_summary_content',{duration:.5});updateRatingControls('yarn_summary');}});}}
function updateYarnSummaries(selected_id,pack,field){var yarn_ids=new Array();$$('form input.yarn_id').each(function(element){yarn_ids.push("yarn_ids[]="+element.value);});var summary_id="yarn_"+selected_id+"_summary";var on_complete=function(){if($('yarn_'+selected_id+'_content')){new Effect.Highlight('yarn_'+selected_id+'_content',{duration:.5});updateRatingControls(summary_id);}}
if(pack){var url=prependPath('yarn_selected?yarn_id='+selected_id+'&field='+field+'&'+yarn_ids.join('&'))
url=url.replace('/contribute/','/');url=url.replace('/edit/','/');new Ajax.Request(url,{asynchronous:true,evalScripts:true,method:'get',onComplete:on_complete})}else if($('yarn_summaries')){var url=prependPath('yarns?'+yarn_ids.join('&')).replace('/edit/','/');new Ajax.Updater('yarn_summaries',url,{onComplete:on_complete});}}
function updateStashSummary(id){new Ajax.Updater('stash_summary',prependPath('summary?yarn_id='+id),{method:'get',onComplete:function(){new Effect.Highlight('stash_summary',{duration:.5});}});}
function avatarMouseOver(element){if(balloon.timeout){clearTimeout(balloon.timeout);}
balloon.timeout=setTimeout(function(){avatarBalloon(element);},1000);}
function avatarMouseOut(avatar){balloonCloser();}
function updateAvatars(){}
function balloonCloser(event){if(balloon.timeout){clearTimeout(balloon.timeout);}
if(balloon.cur){balloon.timeout=setTimeout(function(){balloon.cur.hide();},500);}}
function avatarBalloon(element){if(element.id&&element.id.indexOf('avatar_')==-1){balloon.cur=new HelpBalloon({title:element.id,returnElement:true,dataURL:'/people/'+element.id+'/bubble'});new Insertion.Bottom(document.body,'<span id="'+balloon.cur._properties.id+'"></span>');balloon.cur._elements.icon=$(element).getElementsByTagName('img')[0]
balloon.cur.show();var bubble=balloon.cur._elements.container;Event.observe(bubble,'mouseover',function(event){if(balloon.timeout){clearTimeout(balloon.timeout);}
Event.observe(bubble,'mouseout',balloonCloser);});}}
function saveRequired(){if(!saveRequiredOn){$$('form.autosave').each(function(form){Element.addClassName(form,'save_required');Element.getElementsBySelector(form,'input','button').each(function(button){saveRequiredOn=true;if(button.type=='submit'){if(button.className.indexOf('save_required')<0){Element.addClassName(button,'save_required');Event.observe(button,'click',function(event){saveRequiredOn=false;});}}});});}}
function adminLoaded(){discussionsLoaded();}
function helpLoaded(){$$('.help_faq dt').each(function(dt){Event.observe(dt,'mouseover',function(event){Element.addClassName(dt,'hover');});Event.observe(dt,'mouseout',function(event){Element.removeClassName(dt,'hover');});Event.observe(dt,'click',function(event){var element=Element.next(dt);if(element.style.display=='block'){element.style.display=null;}else{element.style.display='block';}
Event.stop(event);});});}
function dialogLoaded(){}
function discussionsLoaded(){R.forums.onload();}
var topicToolbarHackTimeout;function topicsLoaded(){if($('topic_selector')){Event.observe($('topic_selector'),'change',function(event){navigateWithSelect($('topic_selector'));});}
if(Browser.isSafari()){$('topic_toolbar').style.width="100%";}
if(Browser.isMSIE6()&&$('topic_toolbar')){topicToolbarHack();window.onresize=function(){topicToolbarHack()};Event.observe(window,'scroll',function(){if(topicToolbarHackTimeout){clearTimeout(topicToolbarHackTimeout);}
Element.hide('topic_toolbar');topicToolbarHackTimeout=setTimeout(topicToolbarHack,250);});}}
function topicToolbarHack(){var unread=Element.visible('next_unread');Element.hide('topic_toolbar');if(unread){Element.hide('next_unread');}
var d=document.documentElement;$('topic_toolbar').style.width=d.clientWidth-10;$('topic_toolbar').style.top=d.scrollTop+d.clientHeight-35;$('next_unread').style.top=d.scrollTop+d.clientHeight-130;Element.show('topic_toolbar');if(unread){Element.show('next_unread');}}
function slideshowLoaded(){}
function notebookLoaded(){$$('#needle_inventory td').each(function(element){Event.observe(element,'mouseover',function(){Element.addClassName(element,'hover');});Event.observe(element,'mouseout',function(){Element.removeClassName(element,'hover');});Event.observe(element,'mousedown',function(event){Element.hide('needle_editor');});Event.observe(element,'click',function(event){var id=getId(element);Element.addClassName(element,'lit');var loc=Position.cumulativeOffset('needle_editor');var left=Event.pointerX(event)-150;var top=Event.pointerY(event)-80;$('needle_editor').style.top=top+"px";$('needle_editor').style.left=left+"px";new Ajax.Request(prependPath(id+'/edit'),{asynchronous:true,evalScripts:true,method:'get'})});});if($('user_messages_panel')){R.messages.initialize();}
if($('queued_projects')){Sortable.create('queued_projects',{tag:'div',only:'sortable_queued_project',handle:'handle',constraint:null,scroll:window,onUpdate:saveQueueSortOrder});}
R.utils.updateAutosubmitForms('#projects_panel form');R.utils.updateAutosubmitForms('#posts_panel form');updateLibrarySortables();}
function stashLoaded(){editorLoaded();updateRatingControls();updateZoomables();$$('select#colorway_color_family_id option').each(function(option){updateColorFamily(option);});triggeredMarkdownEditor('stash_notes');triggeredMarkdownEditor('comment_text');}
function peopleLoaded(){if($('sortable_avatars')){$$('#sortable_avatars a.people_link').each(function(element){Event.observe(element,'click',function(event){Event.stop(event);});});Sortable.create('sortable_avatars',{tag:'div',onUpdate:function(){params=Sortable.serialize('sortable_avatars',{tag:'div',name:'avatar_order'});new Ajax.Request(prependPath('../avatars/reorder',true),{method:'post',postBody:params,evalScripts:true});}});}
if($('password_change')){$$('.password_change').each(function(element){Event.observe(element,'click',function(event){new Effect.BlindDown($('password_change'));Event.stop(event);});});}}
function patternSourcesLoaded(){}
function patternsLoaded(){$$('table.pattern_list .clicker').each(function(element){Event.observe(element,'click',function(event){Event.stop(event);});});$$('table.pattern_list .sortable').each(function(element){Event.observe(element,'click',function(event){document.location.replace('/patterns/list?view=list&sort='+element.id);Event.stop(event);});});$$('.featured_pattern .thumbnail').each(function(element){Event.observe(element,'click',function(event){document.location.href="/patterns/library/"+element.id;Event.stop(event);});});$$('#yarns_panel .photo').each(function(element){Event.observe(element,'click',function(event){document.location.href="/yarns/library/"+element.id;Event.stop(event);});});if($('edit_pattern_form')){$A($('edit_pattern_form').getElementsBySelector('input','select','textarea')).each(function(element){Event.observe(element,'focus',function(){new Ajax.Request('/tips/for?from=edit_pattern&id='+element.id,{method:'get',onComplete:function(transport){var json=eval("("+transport.responseText+")");if(json["message_html"]){var required="";if(!json["required"]){required="<div class='tip_required'>This field is <strong>required<strong></div>"}
var t="<img src='/images/silk-pencil.png' class='inline'/> <strong>tips:</strong> "+json["name"];$('tip_container').innerHTML="<div class='tip markdown'><div class='tip_title'>"+
t+"</div>"+json["message_html"]+required+'</div>';var oldTop=Position.cumulativeOffset($("tip_container"))[1];var top=(document.documentElement.scrollTop||document.body.scrollTop)+100;if(top<325){top=325;}
new Effect.MoveBy($('tip_container'),top-oldTop,0);}else{$('tip_container').innerHTML="";}}});});});}
triggeredMarkdownEditor('comment_text');browseActionLoaded();updateSortables();updateZoomables();if(Element.hasClassName(document.body,'patterns_index')){focusFirstFormElement();}}
function browseActionLoaded(){if($('browse_form')){R.utils.observeHover('browse_form','.option');$$('#browse_form .option').each(function(element){var check=Element.getElementsBySelector(element,'input').first();if(check.value=='1'){Element.addClassName(element,'selected');}
Event.observe(element,'click',function(){var check=Element.getElementsBySelector(element,'input').first();if(Element.hasClassName(element,'selected')){Element.removeClassName(element,'selected');check.value='';}else{Element.addClassName(element,'selected');check.value='1';}
$('browse_form_page').value=1;Element.show('browse_indicator');if(browser){clearTimeout(browser);}
browser=setTimeout(function(){$$('#browse_form form').first().onsubmit();},500);});});browseActionSubmit();}}
function browseActionSubmit(){Element.show('browse_indicator');$$('#browse_form form').first().onsubmit();}
function browseActionPaged(a){var page=a.getAttribute('href').split('page=')[1];$('browse_form_page').value=page;scroll(0,0);browseActionSubmit();}
function browseActionSort(sort){$('browse_form_sort').value=sort;browseActionSubmit();}
function patternBrowserLoaded(){$$('#browse_results .photo').each(function(element){Event.observe(element,'click',function(event){document.location.href="/patterns/library/"+element.id;Event.stop(event);});});}
function yarnBrowserLoaded(){$$('#browse_results .photo').each(function(element){Event.observe(element,'click',function(event){document.location.href="/yarns/library/"+element.id;Event.stop(event);});});}
function groupsLoaded(){R.forums.initializeTopic();if($('page_index')){$$('#page_index tbody tr').each(function(element){Event.observe(element,'click',function(event){navigateToFirstLink(element);});});}
if($('large_calendar')){$$('#large_calendar td').each(function(element){Event.observe(element,'click',function(event){navigateToFirstLink(element);});element.onmouseover=function(){Element.addClassName(this,'hover');};element.onmouseout=function(){Element.removeClassName(this,'hover');};});}}
function designersLoaded(){$$('.thumbnail .photo').each(function(element){Event.observe(element,'click',function(event){document.location.href="/patterns/library/"+element.id;Event.stop(event);});});$$('.gutter .framed_photo .photo').each(function(element){Event.observe(element,'click',function(event){document.location.href="/patterns/library/"+element.id;Event.stop(event);});});}
function yarnCompaniesLoaded(){$$('.thumbnail .photo').each(function(element){Event.observe(element,'click',function(event){document.location.href="/yarns/library/"+element.id;Event.stop(event);});});if($('project_search_color')){$$('select#project_search_color option').each(function(option){updateColorFamily(option);});}}
function knitalongsLoaded(){$$('.photo').each(function(element){Event.observe(element,'click',function(event){document.location.href="/alongs/"+element.id;Event.stop(event);});});$$('body.knitalongs_show').each(function(element){editorLoaded();});}
function projectsLoaded(){editorLoaded();updateRatingControls();updateZoomables();triggeredMarkdownEditor('project_notes');triggeredMarkdownEditor('comment_text');}
function yarnsLoaded(){editorLoaded();browseActionLoaded();updateZoomables();if($('project_search_color')){$$('select#project_search_color option').each(function(option){updateColorFamily(option);});}
triggeredMarkdownEditor('yarn_notes');triggeredMarkdownEditor('comment_text');}
function editorLoaded(){$$('.remote_image').each(function(element){Event.observe(element,'load',function(){new Effect.Appear(element);});});$$('.preview').each(function(a){var preview_id=a.id+"_content";var eventName=a.getAttribute('preview')?'click':'mouseover';if($(preview_id)||a.getAttribute('preview')){Event.observe(a,eventName,function(event){var preview=$(preview_id);if(!preview){var src=a.getAttribute('preview');if(src){preview=new Insertion.After(a,'<img class="preview_image" style="display:none;" src="'+src+'" id="'+preview_id+'"/>')
preview=$(preview_id);}}
if(!preview.showing){xoff=a.getAttribute('preview')?300:200;preview.showing=true;preview.style.top=(Event.pointerY(event)-25)+"px";preview.style.left=(Event.pointerX(event)-xoff)+"px";new Effect.Appear(preview,{duration:.5});}});Event.observe(a,'mouseout',function(){var preview=$(preview_id);if(preview&&preview.showing){preview.showing=false;new Effect.Fade(preview,{duration:.3});}});}});if($$('form').length>0){window.onbeforeunload=function(event){if(saveRequiredOn){var msg='You have unsaved changes.';if(!event){event=window.event;}
if(event){event.returnValue=msg;}
return msg;}};}
updateSortables();updateDraggables();updateDroppables();}
function removeMarkdownEditor(textarea_id){var t=wmd_instances[textarea_id];wmd_instances[textarea_id]=null;if(t&&t.editor){t.editor.destroy();}
if(t&&t.previewManager){t.previewManager.destroy();}}
function applyMarkdownEditor(textarea,preview){if(typeof(Attacklab)!='undefined'&&Attacklab&&Attacklab.wmd){wmd_instances[textarea]={editor:new Attacklab.wmd.editor($(textarea)),previewManager:null};}else{wmd_delayed.push(textarea);}}
function triggeredMarkdownEditor(f){var textarea=$(f);var preview=$(f+"_html");var content=$(f+"_content");if(preview){Event.observe(preview,'click',function(){Element.hide(preview);Element.show(textarea);if(content){Element.show(content);}});}}
function loadRichText(editor_fields){$A(editor_fields).each(function(f){var textarea=$(f);var preview=$(f+"_html");var content=$(f+"_content");if(preview){Event.observe(preview,'click',function(){Element.hide(preview);var fck=new FCKeditor(f);fck.BasePath="/javascripts/fckeditor/";fck.ReplaceTextarea();if(content){Element.show(content);}
$$("form input.submit","form input.clicker","form button").each(function(s){Event.observe(s,'click',function(){FCKeditorAPI.GetInstance(f).UpdateLinkedField();});});});}});}
function FCKeditor_OnComplete(editorInstance){}
function focusEditor(field){}
function applyRichText(field){}
function addOpenSearch(){window.sidebar.addSearchEngine("http://www.ravelry.com/search.src","http://www.ravelry.com/favicon.ico","Ravelry","Web");}
function initializeRedbox(box){if(!$(box)){new Insertion.Bottom(document.body,"<div id='"+box+"'></div>");}}
function slideLoading(){Element.show('default_indicator');}
function slideLoaded(){var slide;Element.hide('default_indicator');$$('#current_slide .slide').each(function(element){if(!slide){new Effect.Appear(element,{duration:0.75});slide=true;}else{new Effect.Fade(element,{duration:0.75});}});}
function slideshowRedbox(){return false;Element.show('slideshow');$('content').style.display='none';$("RB_window").style['width']='100%';$("RB_window").style['height']=$("RB_overlay").style['height'];$("RB_window").style['left']="0px";$("RB_window").style['bottom']="0px";$("RB_window").style['marginTop']="0px";Element.addClassName(document.body,'picture_show');}
function setCookie(name,value,expires,path,domain,secure){value=encodeURIComponent(value);if(value.length>3608){value=value.substring(0,3608);}
document.cookie=name+"="+value+
((expires)?"; expires="+expires.toGMTString():"")+
((path)?"; path="+path:"")+
((domain)?"; domain="+domain:"")+
((secure)?"; secure":"");}
function getCookie(name){var dc=document.cookie;var prefix=name+"=";var begin=dc.indexOf("; "+prefix);if(begin==-1){begin=dc.indexOf(prefix);if(begin!=0)return null;}else{begin+=2;}
var end=document.cookie.indexOf(";",begin);if(end==-1){end=dc.length;}
return decodeURIComponent(dc.substring(begin+prefix.length,end));}
function deleteCookie(name,path,domain){if(getCookie(name)){document.cookie=name+"="+
((path)?"; path="+path:"")+
((domain)?"; domain="+domain:"")+"; expires=Thu, 01-Jan-70 00:00:01 GMT";}}
function captchaReady(){var captcha=null;if(navigator.appName.indexOf("Microsoft")!=-1){captcha=window['captcha'];}else{captcha=document['captcha'];}
if(captcha){var id=captcha.fGetId();if(id!="null"&&id!=null&&id!=''){var expires=new Date((new Date()).getTime()+(1000*60*60*24*365*5));setCookie('captchaid',id,expires,'/');}else{id=getCookie('radvid');if(id&&id!=''){captcha.fSetId(id);}}}}
R.accounts=function(){return{checkUsername:function(username){new Ajax.Request('/account/check?username='+username);}}}();R.admin={};R.admin.yarns=function(){var selectedYarnList=function(){var ids=new Array();$$('input.yarn_id_checkbox').each(function(element){if(element.checked)ids.push(element.getAttribute("value"));});return ids.join(',');};return{expungeSelectedYarns:function(){$('expunge_yarn_list').value=selectedYarnList();$('expunge_yarn_form').submit();},mergeSelectedYarns:function(){$('merge_yarn_list').value=selectedYarnList();$('merge_yarn_form').submit();},mergeTo:function(toYarnId){$('to_yarn_id').value=toYarnId;$('merge_form').submit();$$('.merge .clicker').each(Element.hide);Element.show($('default_indicator'));},expunge:function(yarnId){$$('#mini_yarn_'+yarnId+' .merge .clicker').each(Element.hide);Element.show($('yarn_'+yarnId+'_indicator'));new Ajax.Request('/yarns/library/'+yarnId+'/expunge',{method:'post',evalScripts:true});}};}();R.admin.patterns=function(){var selectedPatternList=function(){var ids=new Array();$$('input.checkbox#pattern_id').each(function(element){if(element.checked){ids.push(element.getAttribute("value"));}});return ids.join(',');};return{mergeSelectedPatterns:function(){$('merge_pattern_list').value=selectedPatternList();$('merge_pattern_form').submit();},moveSelectedPatterns:function(){$('move_pattern_list').value=selectedPatternList();$('move_pattern_form').submit();},mergeTo:function(toPatternId){$('to_pattern_id').value=toPatternId;$('merge_form').submit();$$('.merge .clicker').each(Element.hide);Element.show($('default_indicator'));}};}();var Admin={Patterns:R.admin.patterns,Yarns:R.admin.yarns}
R.ads=function(){var shown=new Array();return{inlineAffiliateLink:function(link){var redirect=link;if(link.match(/^http:\/\/shop.interweave.com/)){redirect="http://shop.interweave.com/AffiliateWiz/aw.aspx?B=1&A=5&Task=Click&TargetURL="+encodeURIComponent(link);}else if(link.match(/^http:\/\/cgi.ebay.com/)){redirect="http://rover.ebay.com/rover/1/711-53200-19255-0/1?type=4&campid=5335842904&toolid=10001&customid=&mpre="+encodeURIComponent(link);}else if(link.match(/^http:\/\/www.amazon.com/)){redirect="http://www.amazon.com/gp/redirect.html?ie=UTF8&tag=ravelry-20&linkCode=ur2&camp=1789&creative=9325&location="+encodeURIComponent(link);}
alert(redirect);},observe:function(zone){if(zone=='notebook_vertical'||zone=='forum_topic'||zone=='group_topic'){Element.observe(zone,'mouseover',function(){Element.down(zone,'.clipper').style.visibility='visible';});Element.observe(zone,'mouseout',function(){Element.down(zone,'.clipper').style.visibility='hidden';});}},more:function(zone,creativeId,targetableId,start,pager){url="/enablers/more/"+zone;if(targetableId){url+="?tid="+targetableId;}
document.location.href=url;},rewind:function(zone,creativeId,targetableId){shown.push(creativeId);var stamp=new Date().getTime()+';'+Math.random();var url="/enablers/s/"+zone+"/?s="+stamp+"&rewind="+creativeId;if(targetableId){url+="&tid="+targetableId;}
new Ajax.Request(url);},clip:function(adId,creativeId){$("cliplink_"+creativeId).innerHTML='<img src="/images/indicator_little01.gif"/>';var params={ad_id:adId,creative_id:creativeId};new Effect.Shake('img_'+creativeId);new Ajax.Request('/sponsors/clip',{parameters:params,method:'post'});}};}();R.advertisers={};R.advertisers.initializer=function(){return{initialize:function(){if((Element.hasClassName(document.body,'advertisers_suggestions'))){R.advertisers.suggestions.initialize();}}};}();R.advertisers.campaigns=function(){return{deleteCampaign:function(campaignId){if(confirm('Are you sure that you want to deactivate this campaign?')){var url=prependPath(campaignId);new Ajax.Request(url,{asynchronous:true,evalScripts:true,method:'delete'});}}};}();R.advertisers.suggestions=function(){return{initialize:function(){R.advertisers.suggestions.updateLinks();},updateLinks:function(){$('tabset').getElementsBySelector("a").each(function(link){var href=link.href.split('?');var base=href[0];var params=$H(href[1].parseQuery());params['selections']=$('selections').value;params['ad']=$('ad').value;link.href=base+"?"+params.toQueryString();});var reviewUrl='review_suggestions?selections='+$('selections').value+"&ad="+$('ad').value;$('review_link').down('a').href=reviewUrl;if($('selection_count_label')){var selections=$('selections').value.split(',');if(selections.length>0&&selections[0]!=''){var link="<a href='"+reviewUrl+"'>"+selections.length+" groups selected.</a>";$('selection_count_label').innerHTML=link;}}},addSelection:function(id){var selections=$('selections');var idList=id+"";if(selections.value&&selections.value!=''){idList+=","+selections.value;}
selections.value=$A(idList.split(',')).uniq().join(',');R.advertisers.suggestions.updateLinks();},removeSelection:function(id){var selections=$('selections');var ids=selections.value.split(',');var idString=id+"";selections.value=$A(ids).without(idString).join(',');R.advertisers.suggestions.updateLinks();}};}();R.advertisers.ads=function(){return{aboutAutoRenew:function(){RedBox.open('about_auto_renew','/advertisers/about/auto_renew');},chooseSlots:function(zoneId,geotargeted){geotargeted=geotargeted?"true":"false";document.location.replace("slots?zone_id="+zoneId+"&geotargeted="+geotargeted);},copyDialog:function(){RedBox.open('copy_ad_dialog_box',prependPath('prepare_copy'));},showZones:function(zoneType){var zoneTypeId=$F(zoneType);var parameters="zone_type_id="+zoneTypeId;new Ajax.Updater('available_zones','/zones/search',{asynchronous:true,evalScripts:true,method:'get',parameters:parameters});},localZoneSelected:function(zoneId){R.advertisers.ads.zoneSelected(zoneId,'local_');},zoneSelected:function(zoneId,prefix){if(!prefix){prefix='';}
$(prefix+'selection_'+zoneId).checked=true;$$('tr.'+prefix+'_zone').each(function(row){Element.removeClassName(row,'selected');});Element.addClassName(prefix+'zone_'+zoneId,'selected');}};}();R.advertisers.targeted=function(){return{addGroup:function(groupId){new Ajax.Request(prependPath("add_targetable?targetable_type=Group&targetable_id="+groupId));},addYarnBrand:function(yarnCompanyId){new Ajax.Request(prependPath("add_targetable?targetable_type=YarnCompany&targetable_id="+yarnCompanyId));},addYarn:function(yarnCompanyId){new Ajax.Request(prependPath("add_targetable?targetable_type=Yarn&targetable_id="+yarnCompanyId));}};}();R.affiliates=function(){return{convertToAffiliateLink:function(href){if(href.indexOf('http://shop.interweave.com')==0&&href.indexOf('http://shop.interweave.com/AffiliateWiz')<0){return['Ravelry&nbsp;IK&nbsp;link',"http://shop.interweave.com/AffiliateWiz/aw.aspx?B=1&A=5&Task=Click&TargetURL="+encodeURIComponent(href)];}else if(href.indexOf('http://www.interweavestore.com')==0&&href.indexOf('af=ravelry')<0){return['Ravelry&nbsp;IK&nbsp;link',href+"?af=ravelry"];}else if(href.indexOf('http://www.amazon.com')==0&&href.indexOf('http://www.amazon.com/gp/redirect.html')<0){return['Ravelry&nbsp;Amazon&nbsp;link',"http://www.amazon.com/gp/redirect.html?ie=UTF8&tag=ravelry-20&linkCode=ur2&camp=1789&creative=9325&location="+encodeURIComponent(href)];}else if(href.indexOf('http://www.amazon.co.uk')==0&&href.indexOf('http://www.amazon.co.uk/gp/redirect.html')<0){return['Ravelry&nbsp;Amazon.co.uk&nbsp;link',"http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&tag=ravelry-21&linkCode=ur2&camp=1634&creative=6738&location="+encodeURIComponent(href)];}else if(href.indexOf('http://www.amazon.de')==0&&href.indexOf('http://www.amazon.co.uk/gp/redirect.html')<0){return['Ravelry&nbsp;Amazon.de&nbsp;link',"http://www.amazon.de/gp/redirect.html?ie=UTF8&tag=ravelry-09-21&linkCode=ur2&camp=1836&creative=6742&location="+encodeURIComponent(href)];}else if(href.indexOf('http://cgi.ebay.com')==0||href.indexOf('http://stores.ebay.com')==0||href.indexOf('http://search.ebay.com')==0){return['Ravelry&nbsp;eBay&nbsp;link',"http://rover.ebay.com/rover/1/711-53200-19255-0/1?type=4&campid=5335842904&toolid=10001&customid=&mpre="+encodeURIComponent(href)];}else if(href.indexOf('http://www.joann.com')==0){return['Ravelry&nbsp;JoAnn&nbsp;link',"http://www.tkqlhce.com/click-2669604-1495773?url="+encodeURIComponent(href)];}else if(href.indexOf('http://www.cafepress.com')==0){return['Ravelry&nbsp;CafePress&nbsp;link','http://www.qksrv.net/click-2669604-10463747?URL='+encodeURIComponent(href)];}else if(href.indexOf('http://www.zazzle.com')==0&&href.indexOf('rf=238775932184149241')<0){var sep=href.indexOf('?')>0?'?':'&';return['Ravelry&nbsp;Zazzle&nbsp;link',href+sep+'rf=238775932184149241'];}else{return['Ravelry&nbsp;link',href];}},revealAffiliateLink:function(link){if(!link)return false;if(document.body.className&&document.body.className.indexOf('topics_show')<0&&document.body.className.indexOf('groups_show'))return false;link=$(link);var converted=R.affiliates.convertToAffiliateLink(link.href);var next=link.next();var reveal=converted[1]!=link.href&&(!next||(next&&next.className!='revealed_affiliate_link'));if(reveal){var html='&nbsp;<span class="revealed_affiliate_link" style="display: none; padding-left: 5px; padding-right: 5px;background-color: #e8ffe3; border: 1px solid #ccc; font-size: .95em; padding: 1px;">';html+='<a href="'+converted[1]+'" style="text-decoration: none;" target="_new" title="Use this link to earn money for Ravelry">&nbsp;<img src="/images/silk-money.png" class="inline"/>&nbsp;'+converted[0]+'&nbsp;</a></span>';new Insertion.After(link,html);next=link.next();if(next){new Effect.Appear(next);}}
return reveal;}}}();R.analytics=function(){var outclickDomain='ravelry.com';var outclickTracker='http://stats.ravelry.com/outclick/';var outclickPause=500;var outclicked=false;var esc=function(s){return(typeof encodeURIComponent=='undefined')?escape(s):encodeURIComponent(s);};return{reportOutclick:function(ev){var url;var target=ev?ev.target:window.event.srcElement;if(!target&&window.event){target=window.event.srcElement;}
for(var i=0;target&&i<=20;i++){if(target.tagName&&target.tagName.toLowerCase()=='a'){break;}
target=target.parentNode;}
if(target&&target.tagName&&target.tagName.toLowerCase()=='a'&&target.href){url=target.href;if(!url||typeof(url)!='string'||url==""){return;}
if(R.affiliates.revealAffiliateLink(target)){var event=ev?ev:window.event;Event.stop(event);return false;}
if(url.indexOf(outclickDomain)==-1){var path=outclickTracker;path+="?outclick="+esc(url);path+="&from_title="+esc(document.title);path+="&from="+esc(self.location);var image=new Image();outclicked=false;image.onLoad=function(){outclicked=true;};image.src=path;var now=new Date();var stopTime=now.getTime()+outclickPause;while(now.getTime()<stopTime&&!outclicked){now=new Date();}}}}}}();R.books=function(){return{previewCallback:function(json){var values=$H(json).values();if(values.length>0&&values[0]['preview']!='noview'){$('google_book_search').innerHTML="<img src=\"/images/silk-zoom.png\" class=\"inline\"/> <a target=\"_new\" href=\""+values[0]['preview_url']+"\">look inside this book</a>";}}}}();Browser={inspect:function(){return navigator.userAgent;},isSafari:function(){return navigator.userAgent.toLowerCase().indexOf("apple")>-1;},isMSIE6:function(){return Browser.isMSIE()&&typeof(XMLHttpRequest)=='undefined';},isMSIE:function(){return(navigator.userAgent.toLowerCase().indexOf("msie")>-1)&&!this.isOpera();},isOpera:function(){return navigator.userAgent.toLowerCase().indexOf("opera")>-1;},isMozilla:function(){return(navigator.userAgent.toLowerCase().indexOf("mozilla")>-1)&&!this.isOpera()&&!this.isMSIE();}}
R.calendar=function(){var MONTHS=["January","February","March","April","May","June","July","August","September","October","November","December"];var target=null;var handler=false;var tips=null;return{setTarget:function(id){target=id;},selectDay:function(o){var parts=o.id.split('-');R.calendar.setDate(parts[1],parts[2],parts[3]);},selectYear:function(y){R.calendar.open(target,{year:y});},selectMonth:function(y,m){R.calendar.open(target,{year:y,month:m});},selectPartial:function(year,month){R.calendar.setDate(year,month);},open:function(target,options,ajax_options){var array=target instanceof Array;if(options&&options.relativeTop){anchor=$(array?target[0]:target);var offset=Position.positionedOffset(anchor)[1]+options.relativeTop;$('date_picker').style.top=offset+"px";}
var targetList=array?target.join():target;var url='/calendars/new?target='+targetList;if(options){url+="&"+$H(options).toQueryString();}
if(array){url+="&tips=false";}
if(Element.visible('date_picker')){$('calendar_closer').src="/images/progress.gif";}
savedOptions=options;new Ajax.Request(url);},show:function(){Event.observe(document,'click',R.calendar.clickHandler);$('date_picker').show();},clickHandler:function(evt){var onCalendar=$(Event.element(evt)).up('#date_picker');if(!onCalendar){R.calendar.close();}},close:function(){Event.stopObserving(document,'click',R.calendar.clickHandler);new Effect.DropOut($('date_picker'));},setDate:function(year,month,day){R.calendar.close();var array=target instanceof Array;if(target&&(target.length==1||!array)){var s="";if(month)s+=MONTHS[month-1];if(day)s+=" "+day+",";if(year)s+=" "+year;var t=$(array?target[0]:target);t.value=s;t.select();}else{R.utils.selectOption(target[0],year);R.utils.selectOption(target[1],month);if(day){R.utils.selectOption(target[2],day);}else{R.utils.selectOption(target[2],"");}}}}}();R.chat=function(){var userId=0;var messageLimit=1000;var activeUsers=[];var lastMessageTimeStamp="";var lastMessageUser=null;var lastMessage=null;var subscriber=null;var baseTitle="";var away=false;var backlog=0;var paused=false;var currentChatId=null;var isConnected=false;var smLoaded=false;var sound=null;var scheduledPause=null;var scheduledAway=null;var scheduleTimeout=10000;return{initialize:function(chatId,client){R.chat.resizeWindow();baseTitle=document.title;currentChatId=chatId;new PeriodicalExecuter(function(pe){if(R.chat.online){R.chat.refreshUsers();}},60);stomp=new STOMPClient();subscriber=function(){stomp.subscribe("/topic/CHAT."+chatId,{exchange:''});};stomp.onopen=function(){R.chat.connected();};stomp.onclose=function(code){R.chat.disconnected();};stomp.onerror=function(error){R.chat.errors();};stomp.onerrorframe=function(error){R.chat.errors();};stomp.onconnectedframe=function(error){subscriber();R.chat.connected();};stomp.onmessageframe=function(frame){eval(frame.body);};stomp.connect("chat.ravelry.com",61613,'guest','guest');Event.observe(window,'resize',function(){R.chat.resizeWindow();});Event.observe(window,'blur',function(){R.chat.scheduleAway();R.chat.schedulePause();});Event.observe(window,'focus',function(){R.chat.setAway(false);R.chat.resume();});Event.observe($('chat_message'),'click',function(){if(paused){R.chat.setAway(false);R.chat.resume();}});Event.observe($('talk_messages'),'scroll',function(){R.chat.viewportScrolled();});var passedChatId=chatId;Event.observe(document,'keydown',function(event){var element=Event.element(event);if(element.tagName=='TEXTAREA'){if(away)R.chat.setAway(false);if(paused)R.chat.setPaused(false);var key=R.utils.keyCode(event);if(key==13){Event.stop(event);R.chat.talk(passedChatId,$('chat_message').value);}}});},soundManagerLoaded:function(){smLoaded=true;},schedulePause:function(){if(scheduledPause){window.clearTimeout(scheduledPause);scheduledPause=null;}
scheduledPause=window.setTimeout("R.chat.setPaused(true)",scheduleTimeout);},setPaused:function(p){if(scheduledPause){window.clearTimeout(scheduledPause);}
paused=p;var indicator=$('paused');if(p){if(!Element.visible(indicator)){new Effect.Appear(indicator);}}else{Element.hide(indicator);}},scheduleAway:function(){if(scheduledAway){window.clearTimeout(scheduledAway);scheduledAway=null;}
scheduledAway=window.setTimeout("R.chat.setAway(true)",scheduleTimeout);},setAway:function(b){away=b;if(b==false){document.title=baseTitle;backlog=0;}},resume:function(){R.chat.setPaused(false);var messageWindow=$('talk_messages');messageWindow.scrollTop=messageWindow.scrollHeight-messageWindow.clientHeight;if(Element.visible($('chat_message'))&&isConnected){$('chat_message').focus();}},viewportScrolled:function(){var messageWindow=$('talk_messages');var position=messageWindow.scrollHeight-messageWindow.scrollTop-messageWindow.clientHeight;if(position<50){R.chat.setPaused(false);}else{R.chat.scheduledPause();}},resizeWindow:function(){var height=getViewportSize()[1];$('talk_messages').style.height=(height-215)+"px";},online:function(){return isConnected;},leave:function(){if(isConnected){isConnected=false;new Ajax.Request('/chats/'+currentChatId+'/leave_onunload',{method:'get',asynchronous:false});}},errors:function(){$('connecting').hide();$('interactive').hide();$('errors').show();},connected:function(){isConnected=true;$('errors').hide();$('connecting').hide();$('interactive').show();R.chat.resume();},disconnected:function(){isConnected=false;$('errors').hide();$('interactive').hide();$('connecting').show();},refreshUsers:function(showEnterExit){var activeUserList=activeUsers.join(',');new Ajax.Request('/chats/'+currentChatId+'/users?compare='+activeUserList,{method:'get'});},setActiveUsers:function(userIds){activeUsers=userIds;},userEntered:function(){R.chat.refreshUsers()},userLeft:function(){R.chat.refreshUsers()},talkReceived:function(messageTimeStamp,messageId,message,options){if(messageTimeStamp==lastMessageTimeStamp){$('chat_message').value="";$('default_indicator').hide();new Effect.Opacity('chat_message',{from:0.6,to:1,duration:0.5});if(Element.visible($('chat_message'))){$('chat_message').focus();}}
var messages=$A($('talk_messages').getElementsByClassName('chat_message'));var messagesToRemove=messages.length-messageLimit;var i;for(i=1;i<=messagesToRemove&&messagesToRemove>0;i++){Element.remove(messages[messages.size()-i]);}
Insertion.Bottom($('talk_messages'),message);if(options&&options.messageType==1){R.chat.refreshUsers();if(currentChatId==1){R.chat.ding();}}
if(away){if(backlog==0){R.chat.ding();}
backlog++;document.title="("+backlog+") "+baseTitle;}else if(!paused){Position.prepare();var container_y=Position.cumulativeOffset($('talk_messages'))[1];var element_y=Position.cumulativeOffset($('chat_message_'+messageId))[1];new Effect.Scroll('talk_messages',{x:0,y:(element_y-container_y)});}},talk:function(chatId,msg){R.chat.setPaused(false);R.chat.setAway(false);if(msg!=""){new Effect.Opacity('chat_message',{from:1.0,to:0.6,duration:0.5});$('default_indicator').show();lastMessageTimeStamp=userId+"-"+(new Date());new Ajax.Request('/chats/'+chatId+'/talk',{parameters:{message:msg,message_ts:lastMessageTimeStamp}});}},ding:function(){if(smLoaded){try{soundManager.url='/swf/';if(!sound){sound=soundManager.createSound({id:'ding',url:'/audio/mario-ding.mp3'});}
sound.play();}catch(e){}}},chatUsers:function(chatId){RedBox.open('chat_user_dialog','/chats/'+chatId+'/chat_users');}}}();R.collections=function(){return{create:function(type){new Ajax.Request('/collections/prepare?type='+type,{method:'get'});},destroy:function(id){new Ajax.Request('/collections/'+id,{method:'delete'});}}}();R.controls=function(){viewSelectorTop=null;rawViewSelectorTop=null;return{openViewSelector:function(){if(rawViewSelectorTop==null){rawViewSelectorTop=$('view_selector').style.top;}
viewSelectorTop=parseInt(rawViewSelectorTop.replace('px',''));var itemsAboveTheSelection=0;var found=false;$('view_selector').getElementsBySelector('li').each(function(li){found=found||$(li).hasClassName('selected');if(!found){itemsAboveTheSelection++;}});if(rawViewSelectorTop==$('view_selector').style.top){$('view_selector').style.top=((itemsAboveTheSelection*-20)+viewSelectorTop)+"px";$('view_selector').addClassName('opened_view_selector');}},closeViewSelector:function(){$('view_selector').style.top=rawViewSelectorTop;$('view_selector').removeClassName('opened_view_selector');},tickyBox:function(div,url,key,options){div=$(div).up('.ticky_item').down('.ticky_box');var selectedClass='ticky_box_selected';var toggledValue=Element.hasClassName(div,selectedClass)?0:1;if(toggledValue){Element.addClassName(div,selectedClass);}else{Element.removeClassName(div,selectedClass);}
if(url[0]!='/'&&url.indexOf('http://')<0){url=R.utils.prependPath(url);}
var ajaxOptions={};if(options&&options.indicator){var indicator=options.indicator;ajaxOptions={onComplete:function(){new Effect.Appear(indicator,{duration:.25,afterFinish:function(){new Effect.Fade(indicator,{delay:1,duration:0});}});}};}
var sep=url.indexOf('?')>=0?'&':'?';new Ajax.Request(url+sep+key+"="+toggledValue,ajaxOptions);}}}();R.editing=function(){return{popupDiff:function(form){form=$(form);R.utils.popup({url:form.action+"?"+$H(Form.serialize(form)).toQueryString(),width:850});}}}();R.editor=function(){var windowSelection=function(){if(window.getSelection){return window.getSelection();}else if(document.getSelection){return document.getSelection();}else if(document.selection){return document.selection.createRange().text;}else{return'';}};return{apply:function(textarea){var editor=new Control.TextArea(textarea);var toolbar=new Control.TextArea.ToolBar(editor);toolbar.container.id='editor_toolbar';Element.setStyle('editor_toolbar',{width:(Element.getWidth(textarea)-1)+'px'});toolbar.addButton('Bold',function(){this.wrapSelection('**','**','bold text');},{id:'editor_bold_button'});toolbar.addButton('Italics',function(){this.wrapSelection('*','*','italicized text');},{id:'editor_italics_button'});toolbar.addButton('Link',function(){var selection=this.getSelection();var response=prompt('Enter Link URL','');if(response==null)
return;this.replaceSelection('['+(selection==''?'Link Text':selection)+']('+(response==''?'http://link_url/':response).replace(/^(?!(f|ht)tps?:\/\/)/,'http://')+')');},{id:'editor_link_button'});toolbar.addButton('Block Quote',function(event){var windowSelected=windowSelection();var selected=this.getSelection();if(selected==''&&windowSelected==''){alert("Highlight the text that you would like to quote and then press the quote button");}else if(selected!=''){this.injectEachSelectedLine(function(lines,line){lines.push((event.shiftKey?line.replace(/^\> /,''):'> '+line));return lines;});}else if(windowSelected!=''){windowSelected=windowSelected+'';var callback=(function(lines,line){lines.push((event.shiftKey?line.replace(/^\> /,''):'> '+line));return lines;});windowSelected=$A(this.getSelection().split("\n")).inject([],callback).join("\n");this.element.value+='\n\n'+windowSelected;}},{id:'editor_quote_button'});toolbar.addButton('Image',function(){var selection=this.getSelection();var response=prompt('Enter Image URL','');if(response==null)
return;this.replaceSelection('!['+(selection==''?'enter image title':selection)+']('+(response==''?'http://image_url/':response).replace(/^(?!(f|ht)tps?:\/\/)/,'http://')+')');},{id:'editor_image_button'});}}}();R.events=function(){return{initialize:function(){groupsLoaded();if($('photo_browser')){editorLoaded();}},selectAttendance:function(clicker){var vote=clicker.id.split('_')[0];var url=R.utils.prependPath("attend?vote="+vote);new Ajax.Request(url);},clearAttendance:function(){var url=R.utils.prependPath("attend?vote=");new Ajax.Request(url);},startDrivingDirections:function(){var dd=$('driving_directions_entry');if(Element.visible(dd)){new Effect.SlideUp(dd);}else{new Effect.SlideDown(dd);$('address').focus();}},finishDrivingDirections:function(form,baseUrl){var saddr=$(form).down('#address').value;var url=baseUrl+"&saddr="+saddr;window.open(url);$('driving_directions_entry').hide();},smartTagHelp:function(event){RedBox.open('event_help','/help/dialog?id=help/tags/smart-tags');},connectGroup:function(){if(Element.visible('group_connector')){new Effect.SlideUp('group_connector');}else{new Effect.SlideDown('group_connector');}},setSmartTag:function(tag){var smart=$('smart_tag');if(smart.value==''){smart.value=tag.toLowerCase().replace(/\s+/g,'-').replace(/[^a-z0-9\xC0-\xD6\xD8-\xF6\xF8-\xFF\-\s\$\!]/g,"");}}}}();var ExclusiveAction=function(criticalSection){this.attempt=function(start){for(var j=start;j!=null;j=ExclusiveAction.next(j.id)){if(j.enter||(j.number&&(j.number<this.number||(j.number==this.number&&j.id<this.id)))){var me=this;return setTimeout(function(){me.attempt(j);},200);}}
this.criticalSection();this.number=0;ExclusiveAction.waitList[this.id]=null;}
this.id=++ExclusiveAction.commandID;this.criticalSection=criticalSection;ExclusiveAction.waitList[this.id]=this;this.enter=true;this.number=(new Date()).getTime();this.enter=false;this.attempt(ExclusiveAction.next());}
ExclusiveAction.waitList=new Object();ExclusiveAction.commandID=0;ExclusiveAction.next=function(k){for(i in ExclusiveAction.waitList){if(!k){return ExclusiveAction.waitList[i];}
if(k==i){k=null;}}
return null;}
R.favorites=function(){return{refreshSidebar:function(){if($('bookmark_types')){var href=window.location.href.split('?');var url=href[0];var qs=href[1];if(qs==null){qs="";}
var parts=url.split('/favorites');var base=parts[0]+'/favorites/refresh_sidebar';var action=parts[1];if(action==null){action='index';}else{action=action.replace('/','');}
new Ajax.Request(base+"?for="+action+"&"+qs,{method:'get'});}},editTags:function(id,base){new Ajax.Request(base+'/'+id+'/edit_tags',{method:'get'});},tagInPlace:function(bookmarkId){if($('inplace_tag_editor')){R.tags.hideInPlace();}else{new Ajax.Request('/tags/inplace?bookmark_id='+bookmarkId,{method:'get'});}}}}();R.forums=function(){var lastRead=null;var loadingNextUnread=false;var nextUnreadTimer=null;var posting={};var radarTimer;var radarPaused=false;var lastRadarId;var radarLimit=10;var radarTimeout=5000;var tooltipInterval=700;var forumPostPosition=null;var pageSize=25;var frozen=false;var moving;var currentTooltip;var activeTooltips=new Array();var topicUrl=function(forum,topicId,append){var url='/discuss/'+forum+'/topics/'+topicId;if(append){url+=append;}
return url;};var forumsSorted=function(container){var sorts=new Array();Element.getElementsBySelector($('forum_sets'),'.forum_set ul').each(function(element){sorts.push('forum_set['+getId(element)+"]="+Sortable.sequence(element,{}).join(','));});new Ajax.Request('/forum_sets/sort',{method:'post',postBody:sorts.join('&')});};var topicToolsIndicator=function(){var indicator=$('topic_tool_indicator');if(indicator){Element.show(indicator);}};var lastSuggestionQuery=null;return{onload:function(){var forumSets=$('forum_sets');if(forumSets){var containers=new Array();Element.getElementsBySelector(forumSets,'.forum_set ul').each(function(element){containers.push(element);});Element.getElementsBySelector(forumSets,'.forum_set ul').each(function(element){var listItems=Element.getElementsBySelector(forumSets,'li');listItems.each(function(li){Event.observe(li,'mouseover',function(){Element.addClassName(li,'hover');});Event.observe(li,'mouseout',function(){Element.removeClassName(li,'hover');});});Sortable.create(element,{containment:containers,constraint:false,dropOnEmpty:true,onUpdate:forumsSorted,ghosting:false});});}
R.forums.enableTooltips();},enableTooltips:function(){if(R.swatch.isSwatching("FORUMPEEK")){var titles=Sly.search('td.title');var i;for(i=0;i<titles.length;i++){var table=$(titles[i]);table.hoverIntent({sensitivity:7,interval:tooltipInterval,timeout:0,over:function(evt){R.forums.showTooltip(evt);},out:function(evt){R.forums.hideTooltips();}});}}},parseTooltipEvent:function(evt){var a=Event.findElement(evt,'TR').down('A')
var href=a.href;var parts=href.split('/');var topicId=parts[parts.length-2];var forum=parts[parts.length-3];var anchor=Position.cumulativeOffset(a);return{originalEvent:evt,href:href,topicId:topicId,forum:forum,anchor:anchor};},showTooltip:function(evt){var options=R.forums.parseTooltipEvent(evt);var tooltip=$("tooltip_"+options.topicId);if(!tooltip){new Insertion.Bottom('content',"<div class='topic_tooltip' onmouseout='R.forums.hideTooltips();' style='display: none;' id='tooltip_"+options.topicId+"'></div>");tooltip=$("tooltip_"+options.topicId);}
R.forums.hideTooltips();activeTooltips.push(tooltip);tooltip.style.top=(options.anchor[1]+30)+"px";tooltip.style.left=(options.anchor[0]+10)+"px";new Ajax.Request(topicUrl(options.forum,options.topicId,'/tooltip'),{method:'get'});},hideTooltips:function(evt){var oldArray=activeTooltips;activeTooltips=new Array();$A(oldArray).each(function(t){new Effect.Fade(t,{duration:.1});});},fooly:function(button){new Effect.MoveBy(button,Math.floor((.5-Math.random())*150),Math.floor((.5-Math.random())*150),{transition:Effect.Transitions.sinoidal,duration:.05,afterFinish:function(effect){new Effect.Shake(button);}});},customizeButtons:function(button,value){var hide=value.checked?0:1;new Ajax.Request("/discuss/customize_buttons?button="+button+"&hide="+hide);},changeMainBoards:function(forumId,value){var hide=value.checked?0:1;new Ajax.Request("/discuss/change_main_boards?forum_id="+forumId+"&hide="+hide);},showReplies:function(forumPostId){var e=$('replies_'+forumPostId);var replace="";if(Element.visible(e)){Element.hide(e)}else{var marker=$("guest_moderator_markers_"+forumPostId);if(marker==null){marker=$("reply_summary_"+forumPostId);}
if(marker){replace=marker.innerHTML;marker.innerHTML="<img src='/images/circle-ball-dark-antialiased.gif' />&nbsp;";}
new Ajax.Request("/forum_posts/"+forumPostId+"/replies",{method:'get',onComplete:function(){marker.innerHTML=replace;}});}},post:function(form){if(!posting[form.action]){posting[form.action]=true;R.utils.clearDraft('forum_post');new Ajax.Request(form.action,{asynchronous:true,evalScripts:true,method:'post',onFailure:function(request){Element.hide('reply_form_indicator');posting[form.action]=null;},onSuccess:function(request){Element.hide('reply_form_indicator');posting[form.action]=null;},onLoading:function(request){Element.show('reply_form_indicator');},parameters:Form.serialize(form)});}},replyTo:function(forum,topicId,forumPostId){new Ajax.Request('/discuss/'+forum+'/topics/'+topicId+'/reply?reply_to='+forumPostId,{asynchronous:true,evalScripts:true});},changeBoardSize:function(forumSetId,selector){var size=$F(selector);var set=$('forum_set_'+forumSetId);var sizes=$A(["small","medium","large"]);sizes.each(function(s){Element.removeClassName(set,s)});Element.addClassName(set,sizes[selector.selectedIndex]);new Ajax.Request('/forum_sets/'+forumSetId+'/size',{method:'post',postBody:"size="+size});},setLastRead:function(messageNumber){if(messageNumber){lastRead=messageNumber;}},report:function(forumPostId,value){if(value==0||confirm('Are you sure that you want to report this post? Please only use this in case of emergency: Abusive or illegal posts, spam, etc. (See our community guidelines)')){R.forums.vote(forumPostId,'reported',value);}},searchTopic:function(url){if(Element.visible($('topic_header'))){R.forums.hideReportButtons();Element.hide('topic_header')}else{new Ajax.Request(url,{method:'get'});}},reportTopic:function(url){if(Element.visible($('topic_header'))){R.forums.hideReportButtons();Element.hide('topic_header')}else{new Ajax.Request(url);}},hideReportButtons:function(){($('forum_posts').getElementsBySelector('a.report')).each(function(link){Element.hide(link);});},showReportButtons:function(){($('forum_posts').getElementsBySelector('a.report')).each(function(link){Element.show(link);});},toggleUnreadReplies:function(){var menuId='reply_details_menu';if(Element.visible(menuId)){new Effect.SlideUp(menuId,{duration:.5});new Effect.Fade(menuId,{duration:.75});}else{new Ajax.Request('/forum_posts/unread_replies');}},vote:function(postId,type,vote){new Ajax.Request('/forum_posts/'+postId+'/vote',{method:'post',postBody:"type="+type+"&vote="+vote});},guestModerate:function(postId,downvote){new Ajax.Request('/forum_posts/'+postId+'/guest_moderate',{method:'post',postBody:"downvote="+downvote});},showNextUnread:function(forum,topicId){var load=!loadingNextUnread;loadingNextUnread=true;if(load){nextUnreadTimer=setTimeout(function(){var popup=$('next_unread');Element.show(popup);new Ajax.Request(topicUrl(forum,topicId,'/unread'),{asynchronous:true,evalScripts:true,method:'get'});},750);}},cancelNextUnread:function(){if(nextUnreadTimer){clearTimeout(nextUnreadTimer);loadingNextUnread=false;}},hideNextUnread:function(){Element.hide('next_unread');},firstPostInViewport:function(options){var last=null;var container=$('forum_posts');if(container){var lastElement=null;var viewportTop=getViewportSize()[1];var tableTop=Position.page(container)[1];$A($('current_posts').getElementsByTagName('tr')).each(function(element){var top=0;if(element.offsetTop+tableTop<viewportTop){lastElement=element;}});if(lastElement){last=parseInt(getId(lastElement));}}
return last;},updateUnreadCount:function(topicId,unread){if(unread==0){unread="";}
var td=$$('#topic_row_'+topicId+' .posts')[0];if(td){td.innerHTML='<strong>'+unread+'</strong>';}},markVisibleRead:function(forumId){var topics=new Array();$$("#forum_glance_"+forumId+" table tr").each(function(row){var topicId=row.id.split('_')[2];if(topicId){topics.push(topicId);}});new Ajax.Request('/discuss/'+forumId+'/topics/mark_read?location=glance&topics='+$A(topics).join(','));},periodicallyMarkAsRead:function(options){new PeriodicalExecuter(function(pe){var last=R.forums.firstPostInViewport();if(last&&last>lastRead){lastRead=last;new Ajax.Request(options.url,{method:'post',postBody:"last_read="+last});}},options.frequency);},movePosts:function(howMany){var last=forumPostPosition;if(!last&&window.location.hash!=''){var jump=parseInt(window.location.hash.substring(1));if(jump!=NaN)last=jump;}
if(!last){last=R.forums.firstPostInViewport();}
if(last&&!frozen){var next=last+howMany;var post=$("forum_post_"+next);if(post){forumPostPosition=next;moving=true;y=Position.cumulativeOffset(post)[1];window.scrollTo(0,y);}else if($("previous_page_"+next)){frozen=true;document.location.href=(next-pageSize+1)+"-"+next+"#"+next;}else if($("next_page_"+next)){frozen=true;document.location.href=next+"-"+(next+pageSize-1)+"#"+next;}}},initializeTopic:function(){if(Element.hasClassName(document.body,'discussions_index')||Element.hasClassName(document.body,'topics_index')||Element.hasClassName(document.body,'groups_show')){R.forums.enableTooltips();}
if(Element.hasClassName(document.body,'topics_show')){Event.observe(document,'scroll',function(event){frozen=false;if(moving){moving=false;}else{forumPostPosition=null;}});Event.observe(document,'keydown',function(event){var element=Event.element(event);if(element.tagName=='TEXTAREA'||element.tagName=='INPUT'||element.tagName=='SELECT')return;var key=R.utils.keyCode(event);if(key==74){R.forums.movePosts(1);}else if(key==75){R.forums.movePosts(-1);}});}},initializeRadar:function(id){Event.observe(document,'keypress',function(event){if(R.utils.keyCode(event)==32){if(radarPaused){R.forums.playRadar();}else{R.forums.pauseRadar();}
Event.stop(event);}});R.forums.startRadar(id,0);},startRadar:function(id,count,timeout){if(!radarPaused){if(timeout==null){timeout=radarTimeout;}
var posts=$A($('radar_posts').getElementsByClassName('radar_post'));var postsToRemove=posts.length-radarLimit;for(var i=1;i<=postsToRemove&&postsToRemove>0;i++){Element.remove(posts[posts.size()-i]);}
lastRadarId=id;radarTimer=setTimeout(function(){Element.show('default_indicator');new Ajax.Request('/discuss/radar_sweep?id='+id+"&count="+(count+1),{onComplete:function(){Element.hide('default_indicator');}});},timeout);}},pauseRadar:function(){if(radarTimer){clearTimeout(radarTimer);radarTimer=null;}
radarPaused=true;$('radar_pause').hide();$('radar_play').show();},playRadar:function(){if(!radarTimer){radarPaused=false;R.forums.startRadar(lastRadarId,2,0);}
$('radar_play').hide();$('radar_pause').show();},watchTopic:function(forum,topicId,loc){topicToolsIndicator();new Ajax.Request(topicUrl(forum,topicId,'/watch?location='+loc),{asynchronous:true,evalScripts:true,method:'post'})},ignoreTopic:function(forum,topicId,loc){topicToolsIndicator();new Ajax.Request(topicUrl(forum,topicId,'/ignore?location='+loc),{asynchronous:true,evalScripts:true,method:'post'})},clearMonitorship:function(forum,topicId,loc){topicToolsIndicator();new Ajax.Request(topicUrl(forum,topicId,'/clear?location='+loc),{asynchronous:true,evalScripts:true,method:'post'})},markLastRead:function(forum,topicId,postNumber,loc){topicToolsIndicator();var params={force_last_read:postNumber};new Ajax.Request(topicUrl(forum,topicId,'/read?location='+loc),{asynchronous:true,evalScripts:true,method:'post',parameters:params})},suggestTopics:function(forum,query){if(query==lastSuggestionQuery){return;}
if(Element.hasClassName(document.body,'topics')){lastSuggestionQuery=query;new Ajax.Request(topicUrl(forum,'suggestions'),{parameters:{query:query,method:'get'}});}},prepareFlag:function(forumPostId,options){var adjust=options&&options.position=='right'?400:0;new Ajax.Request('/forum_posts/'+forumPostId+"/prepare_flag",{method:'get',onComplete:function(){var container=$('prepare_flag_container');var offset=Position.cumulativeOffset($('fave_'+forumPostId));container.style.top=(offset[1]+30)+"px";container.style.right=(offset[0]-30+adjust)+"px";container.show();}});},prepareModeratePost:function(forumPostId){new Ajax.Request('/forum_posts/'+forumPostId+"/prepare_moderate",{method:'get'});},topicTools:function(forum,topicId,loc,e){var evt=e?e:window.event;var left=0;var top=0;if(loc!='glance'){left=Event.pointerX(evt)-225;top=Event.pointerY(evt)-225;}else{left=Event.pointerX(evt)-225;top=Event.pointerY(evt)+10;var status=$('topic_'+topicId+'_status');if(status){status.previousInnerHTML=status.innerHTML;status.innerHTML='<img src="/images/circle-ball-dark-antialiased.gif" />';}}
var contents=$('topic_tools_contents');if(contents){contents.innerHTML='';}
var tt=$('topic_tools_container')
if(!tt){var html='<div id="topic_tools_container" style="display:none; z-index:100; position: absolute;"></div>';new Insertion.Bottom(document.body,html);tt=$('topic_tools_container')}
tt.style.top=top+"px";tt.style.left=left+"px";tt.style.display='block';topicToolsIndicator();new Ajax.Request(topicUrl(forum,topicId,'/tools?location='+loc),{asynchronous:true,evalScripts:true,method:'get',onComplete:function(){var status=$('topic_'+topicId+'_status');if(loc=='glance'&&status&&status.previousInnerHTML){status.innerHTML=status.previousInnerHTML;status.previousInnerHTML='';}}});}};}();R.friends=function(){return{selectSets:function(user,friend_id){var url="/people/"+user+"/friends/"+friend_id+'/select_sets';new Ajax.Request(url,{method:'get'});},friendRemoved:function(friend_id){var friend=$("friend_"+friend_id);if(friend){new Effect.DropOut('friend_'+friend_id);}
var row=$("friend_"+friend_id+"_row");if(row){row.getElementsBySelector('td').each(function(td){td.innerHTML='';});}},changeSets:function(user,friend_id){var collections=$('collections_container');if(collections&&Element.visible(collections)){new Effect.SlideUp(collections);}else{var url='/people/'+user+'/friends/'+friend_id+'/change_sets';new Ajax.Request(url,{evalScripts:true,method:'get'});}}};}();R.groups=function(){return{associateByName:function(select,owner_type,owner_id){var group_name=$F(select);if(group_name!=''){var params="owner_type="+owner_type+"&owner_id="+owner_id+"&group_name="+group_name;Element.show('group_indicator');new Ajax.Request('/groups/associate_by_name',{method:'post',postBody:params,evalScripts:true,onComplete:function(){Element.hide('group_indicator')}});}},disassociate:function(group_id,owner_type,owner_id,src){if(confirm('Are you sure that you want to remove this '+owner_type.toLowerCase()+' from the group?')){var params="owner_type="+owner_type+"&owner_id="+owner_id+"&src="+src;new Ajax.Request('/groups/'+group_id+'/disassociate',{method:'post',postBody:params,evalScripts:true});}},searchDialog:function(){var url='/groups/search_dialog?q='+name
RedBox.open('group_dialog_box',url);}};}();Object.extend(Event,{KEY_SHIFT:16,KEY_CONTROL:17,KEY_CAPSLOCK:20,KEY_SPACE:32,keyPressed:function(event){return Browser.isMSIE()?window.event.keyCode:event.which;}});Object.genGUID=function(){var len=8;if(!isNaN(parseInt(arguments[0])))len=parseInt(arguments[0]);var chars="abcdef0123456789";var output="";while(output.length<len){var rnd=Math.floor(Math.random()*(chars.length-1));output+=chars.charAt(rnd);}
return output;}
var HelpBalloon=Class.create();HelpBalloon.prototype={initialize:function(options){this.options=Object.extend({returnElement:false,altText:'Click here for help with this topic',dataURL:null,title:'Title',content:'Content',duration:.5,useEvent:['click'],imagePath:'http://style.ravelry.com/images/',method:'get'},options||{});this._elements={container:null,inner:null,icon:null,content:null,button:null,title:null,bgContainer:null};this._properties={id:"HelpBalloon_"+Object.genGUID(),balloons:[this.options.imagePath+'bubble-tl.png',this.options.imagePath+'bubble-tr.png',this.options.imagePath+'bubble-bl.png',this.options.imagePath+'bubble-br.png'],balloonStyle:{position:'absolute',border:'none',background:'white',width:'250px',height:'220px',display:'none',zIndex:1010},button:this.options.imagePath+'button.png',visible:false,balloonCoords:null,innerDims:[230,160],outerDims:[300,200],pointerDims:[20,25],innerMargin:0,buttonHeight:20,drawn:false,renderXY:[0,0],x_offset:35,y_offset:-30};for(var i=0;i<this._properties.balloons.length;i++){var timg=new Image();timg.src=this._properties.balloons[i];}
this._elements.container=document.createElement('div');this._elements.container._HelpBalloon=this;},toggle:function(e)
{if(!e)e=window.event||{type:this.options.useEvent,target:this._elements.icon};var icon=Event.element(e);if(e.type==this.options.useEvent&&!this._properties.visible&&icon==this._elements.icon)
this.show();else
this.hide();},show:function()
{if(!this._properties.drawn)this._draw();this._reposition();this._hideOtherHelps();Effect.Appear(this._elements.container,{duration:this.options.duration});setTimeout(this._hideLowerElements.bind(this),(this.options.duration*1000)/2);setTimeout(function(){this._elements.container.style.display='block';}.bind(this),(this.options.duration*1000));this._properties.visible=true;Event.observe(window,'resize',this._reposition.bindAsEventListener(this));},hide:function()
{this._showLowerElements();Effect.Fade(this._elements.container,{duration:this.options.duration});setTimeout(function(){this._elements.container.style.display='none';}.bind(this),this.options.duration*1000);this._properties.visible=false;Event.stopObserving(window,'resize',this._reposition.bindAsEventListener(this));return;},_reposition:function()
{this._properties.balloonCoords=this._getXY(this._elements.icon);this._properties.balloonCoords.x+=Math.round(this._elements.icon.width/2)+this._properties.x_offset;this._properties.balloonCoords.y+=Math.round(this._elements.icon.height/2)+this._properties.y_offset;var pos=0;var relativeToViewport=Position.page(this._elements.icon);var oh=relativeToViewport[0]+parseInt(this._elements.container.style.width);var ov=relativeToViewport[1]-parseInt(this._elements.container.style.height);if(ov>0)pos+=2;var ww=Browser.isMSIE()?document.body.clientWidth:window.outerWidth;if(oh>ww)
pos+=1;if(Browser.isMSIE()&&this._properties.balloons[pos].toLowerCase().indexOf('.png')>-1)
{var doAppend=false;if(!this._elements.bgContainer)
{doAppend=true;this._elements.bgContainer=document.createElement('div');}
this._elements.bgContainer.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this._properties.balloons[pos]+"', sizingMethod='crop')";this._elements.bgContainer.style.position='absolute';this._elements.bgContainer.style.left='0px';this._elements.bgContainer.style.top='0px';this._elements.bgContainer.style.width=this._elements.container.style.width;this._elements.bgContainer.style.height=this._elements.container.style.width;this._elements.bgContainer.style.zIndex=-1;doAppend&&this._elements.container.appendChild(this._elements.bgContainer);}
else
this._elements.container.style.backgroundImage='url('+this._properties.balloons[pos]+')';this._elements.container.style.backgroundRepeat='no-repeat';this._elements.container.style.backgroundColor='transparent';if(Browser.isMSIE())this._elements.container.style.backgroundAttachment='fixed';this._elements.container.style.backgroundPosition='top left';var cx=0;var cy=0;var zx=0;var zy=0;switch(pos)
{case 1:cx=this._properties.pointerDims[0];cy=this._properties.pointerDims[1];zx=this._properties.balloonCoords.x-parseInt(this._elements.container.style.width);zy=this._properties.balloonCoords.y;break;case 2:cx=this._properties.pointerDims[0];cy=this._properties.pointerDims[1];zx=this._properties.balloonCoords.x;zy=this._properties.balloonCoords.y-parseInt(this._elements.container.style.height);break;case 3:cx=this._properties.pointerDims[0];cy=this._properties.pointerDims[1];zx=this._properties.balloonCoords.x-parseInt(this._elements.container.style.width);zy=this._properties.balloonCoords.y-parseInt(this._elements.container.style.height);break;default:case 0:cx=this._properties.pointerDims[0];cy=this._properties.pointerDims[1];zx=this._properties.balloonCoords.x;zy=this._properties.balloonCoords.y;break;}
this._elements.container.style.left=zx+"px";this._elements.container.style.top=zy+"px";if(this._elements.inner)this._elements.inner.style.left=(cx+this._properties.innerMargin)+'px';if(this._elements.inner)this._elements.inner.style.top=(cy+this._properties.innerMargin)+'px';if(this._elements.inner&&pos<2)this._elements.inner.style.marginTop='15px';},_draw:function()
{Element.setStyle(this._elements.container,this._properties.balloonStyle);if(this.options.dataURL&&!this._properties.drawn)
{var cont=new Ajax.Request(this.options.dataURL,{asynchronous:false,method:this.options.method});var doHTML=false;if(cont.transport.responseXML)
{var xml=cont.transport.responseXML.getElementsByTagName('HelpBalloon')[0];if(xml)
{xmlTitle=xml.getElementsByTagName('title')[0];if(xmlTitle)this.options.title=xmlTitle.firstChild.nodeValue;xmlContent=xml.getElementsByTagName('content')[0];if(xmlContent)this.options.content=xmlContent.firstChild.nodeValue;}
else
doHTML=true;}
else
doHTML=true;if(doHTML)
{var htmlTitle=cont.transport.responseText.match(/\<title\>([^\<]+)\<\/title\>/gi);if(htmlTitle)
{htmlTitle=htmlTitle.toString().replace(/\<title\>|\<\/title\>/gi,'');this.options.title=htmlTitle;}
this.options.content=cont.transport.responseText;}}
this._elements.inner=document.createElement('div');this._elements.inner.style.position='absolute';this._elements.inner.style.width=this._properties.innerDims[0]+'px';this._elements.inner.style.height=this._properties.innerDims[1]+'px';var title=document.createElement('div');title.innerHTML=this.options.title;title.style.fontFamily='verdana';title.style.fontSize='1.2em';title.style.fontWeight='bold';title.style.color='black';title.style.width=(this._properties.innerDims[0]-this._properties.buttonHeight)+'px';title.style.height=this._properties.buttonHeight+'px';title.style.position='absolute';title.style.overflow='hidden';title.style.top='0px';title.style.left='0px';this._elements.inner.appendChild(title);var closer=null;if(Browser.isMSIE()&&this._properties.button.toLowerCase().indexOf('.png')>-1)
{closer=document.createElement('div');closer.style.width=this._properties.buttonHeight+'px';closer.style.height=this._properties.buttonHeight+'px';closer.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this._properties.button+"', sizingMethod='crop')";}
else
{closer=new Image(this._properties.buttonHeight,this._properties.buttonHeight);closer.src=this._properties.button;}
Event.observe(closer,'click',this.toggle.bindAsEventListener(this));closer.style.cursor='pointer';closer.title='Click to close this balloon';closer.style.position='absolute';closer.style.top='0px';closer.style.left='135px';this._elements.inner.appendChild(closer);var contents=document.createElement('div');contents.style.width=this._properties.innerDims[0]+'px';contents.style.width='150px';contents.style.height=(this._properties.innerDims[1]-parseInt(title.style.height))+'px';contents.style.overflow='auto';contents.style.position='absolute';contents.style.top=parseInt(title.style.height)+'px';contents.style.left="0px";contents.style.fontFamily='verdana';contents.style.fontWeight='normal';contents.style.color='black';contents.innerHTML=this.options.content;this._elements.inner.appendChild(contents);this._elements.container.appendChild(this._elements.inner);document.getElementsByTagName('body')[0].appendChild(this._elements.container);this._properties.drawn=true;},_getXY:function(obj)
{var pos=Position.cumulativeOffset(obj)
var y=pos[1];var x=pos[0];var x2=x+parseInt(obj.offsetWidth);var y2=y+parseInt(obj.offsetHeight);return{'x':x,'y':y,'x2':x2,'y2':y2};},_isChild:function(obj)
{var i=15;do{if(obj==this._elements.container)
return true;obj=obj.parentNode;}while(obj&&i--);return false},_isOver:function(this_obj)
{if(!this._properties.visible)return false;if(this_obj==this._elements.container||this._isChild(this_obj))return false;var this_coords=this._getXY(this_obj);var that_coords=this._getXY(this._elements.container);if((((this_coords.x>=that_coords.x&&this_coords.x<=that_coords.x2)||(this_coords.x2>=that_coords.x&&this_coords.x2<=that_coords.x2))&&((this_coords.y>=that_coords.y&&this_coords.y<=that_coords.y2)||(this_coords.y2>=that_coords.y&&this_coords.y2<=that_coords.y2)))){return true;}
else
return false;},_showLowerElements:function()
{var elements=this._getWeirdAPIElements();for(var i=0;i<elements.length;i++)
{if(this._isOver(elements[i]))
{if(elements[i].style.visibility!='visible'&&elements[i].hiddenBy==this)
{elements[i].style.visibility='visible';elements[i].hiddenBy=null;}}}},_hideLowerElements:function()
{var elements=this._getWeirdAPIElements();for(var i=0;i<elements.length;i++)
{if(this._isOver(elements[i]))
{if(elements[i].style.visibility!='hidden')
{elements[i].style.visibility='hidden';elements[i].hiddenBy=this;}}}},_getWeirdAPIElements:function()
{if(!document.all)return[];var objs=['select','input','object'];var elements=[];for(var i=0;i<objs.length;i++)
{var e=document.getElementsByTagName(objs[i]);for(var j=0;j<e.length;j++)
{elements.push(e[j]);}}
return elements;},_hideOtherHelps:function(e)
{if(!e)e=window.event;var divs=document.getElementsByTagName('div');for(var i=0;i<divs.length;i++)
{if(divs[i]._HelpBalloon&&divs[i]._HelpBalloon._properties.visible&&(divs[i]!=this._elements.container))
divs[i]._HelpBalloon.toggle(e);}}};R.history=function(){var handler=null;return{initialize:function(handler){iframe=$('history-manager-iframe');if(iframe==null){new Insertion.Bottom(document.body,"<iframe id='history-manager-iframe' src='/blank.html' style='width:0;height:0;display:none;'>");iframe=$('history-manager-iframe');}
LocationHash.init(handler,iframe);},go:function(newHash){LocationHash.go(newHash);}};}();R.issues=function(){var cancelNavigate=false;return{track:function(postId){new Ajax.Request('/issues/'+postId+'/mini',{method:'get'});},initialize:function(){triggeredMarkdownEditor('issue_description');R.utils.applyFancyTables();},updateMarker:function(checkbox,issueId,marker){var value=$F(checkbox)||'off';new Ajax.Request('/issues/'+issueId+'/mark?marker='+marker+"&value="+value);},quickEdit:function(id){var url='/issues/'+id+'/quick_edit';RedBox.open('issue_box',url,{method:'get'});R.issues.cancelNavigate=true;}};}();R.logger={toggle:function(){},move:function(){},resize:function(){},clear:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){},profile:function(){}};R.maps=function(){return{geocodeForm:function(form,input,options){options=$H({address:'address_field',latitude:'lat_field',longitude:'lng_field',accuracy:'accuracy_field',geocoded:'geo_field'}).merge(options);if($(input).value==''){return true;}
if($(options.geocoded).value!=''){return true;}
if(options.indicator){var indicator=options.indicator;if(indicator==true){Element.show('default_indicator');}else if(indicator){Element.show(indicator);}}
var form=form;R.maps.geocode($(input).value,function(results){if(options.indicator){}
var success=results.Status.code==200&&results.Placemark.length>0;$(options.geocoded).value=success;if(success){var placemark=results.Placemark[0];$(options.address).value=placemark.address;$(options.latitude).value=placemark.Point.coordinates[1];$(options.longitude).value=placemark.Point.coordinates[0];$(options.accuracy).value=placemark.AddressDetails.Accuracy;form.submit();}});return false;},geocode:function(address,callback){var geocoder=new GClientGeocoder();geocoder.getLocations(address,callback);}}}();R.messages=function(){var selectedMessages=function(){var values=new Array();$$('#message_list .message_checkbox input').each(function(element){if(element.checked){values.push(getId(element));}});return values;};var showMessageIndicator=function(){Element.show('default_indicator');};var hideMessageIndicator=function(){Element.hide('default_indicator');};return{deleteSelectedMessages:function(){if(confirm('Are you sure that you want to delete the selected messages?')){showMessageIndicator();new Ajax.Request('/messages/destroy_collection',{asynchronous:true,evalScripts:true,onComplete:hideMessageIndicator,postBody:'message_ids='+selectedMessages().join(','),method:'delete'});}},toggleSelectedMessages:function(toggler){$$('#message_list .message_checkbox input').each(function(element){element.checked=toggler.checked;});},saveSelectedMessages:function(){showMessageIndicator();new Ajax.Request('/messages/archive_collection',{asynchronous:true,evalScripts:true,onComplete:hideMessageIndicator,postBody:'message_ids='+selectedMessages().join(','),method:'put'});},messageNotFound:function(id){alert('This message is no longer available. Did you delete it? Try refreshing the page');var msg=$("message_row_"+id);if(msg){Element.hide(msg);}},mark:function(id,checkbox){var action=checkbox.checked?'mark_read':'mark_unread';new Ajax.Request('/messages/'+id+'/'+action,{method:'put'});},open:function(id){new Ajax.Request('/messages/'+id,{asynchronous:true,evalScripts:true,method:'get',on404:function(request){R.messages.messageNotFound(id);},onComplete:function(request){Element.hide('default_indicator');},onLoading:function(request){Element.show('default_indicator');}});},initialize:function(){$$('#message_list .message_checkbox input').each(function(element){element.checked=false;});$$('#user_messages_panel tbody tr').each(function(element){Event.observe(element,'click',function(event){var clicked=Event.element(event)
var parent=clicked.parentNode;if(!Element.hasClassName(clicked,'message_checkbox')&&!Element.hasClassName(parent,'message_checkbox')){element.getElementsByTagName('a')[0].onclick();}});});}};}();R.organizer=function(){var selection=null;var lastChoice=null;return{addToSetWithSelect:function(select,itemId,typeId){collectionId=select.options[select.selectedIndex].value;if(collectionId!=''){R.organizer.addToSet(collectionId,itemId,'',typeId);}},addToSet:function(collectionId,itemId,tagId,typeId){new Ajax.Request('/collections/'+collectionId+'/add?item_id='+itemId+"&tag_id="+tagId+"&collectionTypeId="+typeId,{method:'get'});},removeFromSet:function(collectionId,itemId,tagId,typeId){new Ajax.Request('/collections/'+collectionId+'/remove?item_id='+itemId+"&tag_id="+tagId+"&collectionTypeId="+typeId,{method:'get'});},choose:function(type,index,itemId){if(lastChoice==itemId&&Element.visible('chooser')){Element.hide('chooser');}else{lastChoice=itemId;new Ajax.Request('/collections/choose?collection_type_id='+type+'&index='+index+'&item_id='+itemId);}},editTags:function(type,itemId,tag){url='/collections/edit_tags?collection_type_id='+type+'&item_id='+itemId;if(tag){url+="&tag="+tag;}
new Ajax.Request(url);},reloadTags:function(type,itemId){new Ajax.Request('/collections/reload_tags?collection_type_id='+type+'&item_id='+itemId);},hideChooser:function(){Element.hide('chooser');},fullscreen:function(){Element.toggleClassName(document.body,'fullscreen');},highlightSelection:function(selectedId){var collections=$('collection_inner_list').childNodes;for(var i=0;i<collections.length;i++){if(collections[i].id==selectedId){collections[i].className='selected';}else if(collections[i].className=='selected'){collections[i].className='';}}
var tags=$('tag_list').childNodes;for(var i=0;i<tags.length;i++){if(tags[i].id==selectedId){tags[i].className='selected';}else if(tags[i].className=='selected'){tags[i].className='';}}},prepareSet:function(type){new Ajax.Request('/collections/prepare?collection_type_id='+type);},selectSet:function(id){R.organizer.hideChooser();new Ajax.Request('/collections/'+id+'/select',{method:'get'});},deleteSet:function(id){new Ajax.Request('/collections/'+id,{method:'delete'});},editSet:function(id){new Ajax.Request('/collections/'+id+'/edit',{method:'get'});},reloadSets:function(type){new Ajax.Request('/collections/reload?collection_type_id='+type);},selectAll:function(type){R.organizer.hideChooser();new Ajax.Request('/collections/select_tag?collection_type_id='+type);R.organizer.highlightSelection("folder_"+type);},selectTag:function(link,tag,type){R.organizer.hideChooser();if(selection){selection.style.background='';}
selection=link;link.style.background='white';new Ajax.Request('/collections/select_tag?collection_type_id='+type+'&tag='+tag);},showChooser:function(index){var chooser=$('chooser');var anchor=$('selector_'+index);var pos=Position.page(anchor);chooser.style.top=(parseInt(pos[1])+30)+"px";chooser.style.left=(parseInt(pos[0])-12)+"px";chooser.show();}}}();R.people=function(){return{siteChooser:function(){RedBox.open('chooser',R.utils.prependPath('choose_sites',true));}};}();R.patterns=function(){return{findByUrl:function(url,index){new Ajax.Request('/patterns/find_by_url?url='+encodeURIComponent(url)+"&index="+index,{method:'get'});},notEditable:function(permalink){RedBox.open('not_editable','/patterns/library/'+permalink+'/not_editable');},validateEditForm:function(){var comment=$('pattern_change_comment');if(comment&&comment.value==''){alert('Please describe the change that you are making - it is used for a history of revisions.');comment.focus();return false;}else{return true;}},searchDialog:function(typePrefix,options){var name;if(options){name=options.name;}
if(!name&&$(typePrefix+'_name')){name=$F(typePrefix+'_name');}
if(name!=''){name=(typeof encodeURIComponent=='undefined')?escape(name):encodeURIComponent(name);}
var box=typePrefix+'_redbox';var url='/patterns/search_dialog?q='+name
if(options){if(options.contribute){url+="&contribute=true";}
if(options.linkable==false){url+="&linkable=false";}
if(options.project){url+="&project="+options.project;}
if(options.queuedProject){url+="&queued_project="+options.queuedProject;}}
initializeRedbox(box);RedBox.loading();new Ajax.Updater(box,url,{asynchronous:true,onComplete:function(request){RedBox.addHiddenContent(box);},evalScripts:true});}};}();R.patterns.search=function(){var initialized=false;return{initialize:function(){if(initialized){return;};initialized=true;},onsubmit:function(){},refresh:function(){R.patterns.search.onsubmit();$('search_form').submit();},resort:function(){R.patterns.search.refresh();},reopen:function(id){R.patterns.search.initialize();},filterKeypress:function(attribute){Element.hide(attribute+"_indicator");Element.show(attribute+"_add");},filterAdded:function(attribute,value){if($(attribute+"_input")){Element.hide(attribute+"_indicator");$(attribute+"_input").value='';}},addFilter:function(attribute){R.patterns.search.refresh();},removeFilter:function(attribute,value){R.patterns.search.refresh();},changeFilter:function(attribute,value,direction){$(direction+'_attribute').value=attribute;$(direction+'_value').value=value;var params=Form.serialize('search_form')
new Ajax.Request(prependPath(direction+'_filter'),{asynchronous:true,evalScripts:true,parameters:params,method:'get'});},filtersChanged:function(){$('search_filters').innerHTML='';$A(['add_attribute','add_value','remove_attribute','remove_value']).each(function(f){$(f).value='';});}}}();R.patternSources=function(){return{periodicalClicked:function(checkbox){var value=$F(checkbox);if(value){$('periodical_fields').show();}else{$('periodical_fields').hide();}}}}();R.photos=function(){return{zoomer:function(photo,count){photo=$(photo);var zoomerId=photo.id+"_zoomer";var zoomer=$(zoomerId);if(!zoomer){var inner="";if(count==1){inner='1 <img src="/images/silk-image.png">';}else if(count){inner=count+' <img src="/images/silk-images.png">';}else{inner='<img src="/images/silk-magnifier_zoom_in.png">';}
var html='<a href="#" id="'+zoomerId+'"class="zoomer" onclick="R.photos.zoom(\''+photo.id+'\', true); return false;">'+inner+'</a>';if(photo.tagName=='A'){photo.innerHTML=html;}else{new Insertion.After(photo,html);}}else{if(!Element.visible(zoomer)){zoomer.show();}}},hideZoomer:function(photo){photo=$(photo);var zoomer=$(photo.id+"_zoomer");if(zoomer){zoomer.hide();}},zoom:function(element,generic){element=$(element);var box=element.id+"_box";initializeRedbox(box);var page=window.location.search.parseQuery()["page"]
var page=!page?"":"&page="+page;var url;if(generic){url='/photos/slideshow?start='+getId(element);}else{url=prependPath('slideshow?start='+getId(element)+page);url=url.replace("/edit/","/");}
RedBox.loading({fade:false});new Ajax.Updater(box,url,{method:'get',asynchronous:true,onComplete:function(request){RedBox.addHiddenContent(box);slideshowRedbox();},evalScripts:true});},slurp:function(url,photographableType,photographableId,login){new Ajax.Request('/photos/slurp',{parameters:{url:url,photographable_type:photographableType,photographable_id:photographableId,copyright:login}});},photobucketPageChanged:function(pager){var href=pager.href;var qs=href.substring(href.indexOf('?')+1);var page=qs.parseQuery()['page'];$('page_field').value=page;$('photobucket_form').onsubmit();},scheduleProgressCheck:function(key){setTimeout(function(){new Ajax.Request('/photos/progress?key='+key,{asynchronous:true,evalScripts:true,method:'get',on500:function(){$('flickr_search').innerHTML='Slurp failed! The photo slurper may not be working properly - try again later.'}});},1000);},rate:function(select,type,id){var value=select.options[select.selectedIndex].value;$('rating_progress').show();new Ajax.Request('/photos/rate?photographable_id='+id+"&photographable_type="+type+"&value="+value);}}}();R.products=function(){var currencies={};return{setCurrencies:function(currencyHash){currencies=currencyHash;},freeSelected:function(checkbox){if($F(checkbox)){Form.Element.disable('product_price');Form.Element.disable('product_currency');$('free_icon').show();}else{Form.Element.enable('product_price');Form.Element.enable('product_currency');$('free_icon').hide();}},currencySelected:function(select){var value=$F(select);var currency=currencies[value];if(currency){var symbol=$('currency_symbol');if(symbol){symbol.innerHTML=" ("+currency.symbol+")";}}}}}();R.projects=function(){return{deleteProject:function(projectId,view,title){var message='Are you sure that you want to delete this project permanently?';if(title){message='Are you sure that you want to delete "'+title.innerHTML.strip()+'" permanently?'}
if(confirm(message)){var url=prependPath(projectId+'/destroy');var parameters=view!=null?"view="+view:"";new Ajax.Request(url,{asynchronous:true,evalScripts:true,method:'post',postBody:parameters});}},craftSelected:function(select){var value=$F(select);if(value=='other'){R.projects.togglePatternDetails(false);Element.show('other_craft');Element.hide('continue');Element.hide('pattern_origins');Element.hide('pattern_primary');}else if(value==5){R.projects.togglePatternDetails(false);Element.hide('other_craft');Element.show('continue');Element.hide('pattern_origins');Element.hide('pattern_primary');$('prepare_project_form_pattern_origin_id_1').checked=true;}else{R.projects.togglePatternDetails(true);Element.hide('other_craft');Element.show('continue');Element.show('pattern_origins');Element.show('pattern_primary');}},patternSelected:function(patternId,name){if($('project_pattern_id')){$('project_pattern_id').value=patternId;$('project_pattern_name').value=name;suggestionsClosed('project_pattern');}},showProgressControl:function(projectId){Element.toggle("project_"+projectId+"_progress_rater");},togglePatternDetails:function(show){if(show){Element.show('pattern_details');}else{Element.hide('pattern_details');}},prepareWithPattern:function(patternId){$('prepare_project_form_pattern_id').value=patternId;$('prepare_project_form_pattern_selected').value=1;$('prepare_project_form').submit();},preparePageChanged:function(link){var href=link.href;var qs=href.substring(href.indexOf('?')+1);var page=qs.parseQuery()['page'];$('prepare_project_page').value=page;$('prepare_project_form').submit();},helpful:function(url,yes){$('helpful_link').innerHTML="<img src='/images/circle-ball-dark-antialiased.gif' id='helpful_button' style='padding: 1px;'>";if($('clear_helpful_link')){$('clear_helpful_link').innerHTML="";}
url+=yes?"?helpful=1":"?helpful=0"
new Ajax.Request(url);},removeTool:function(projectId,toolId){if(confirm("Are you sure that you want to remove this tool?")){var url=R.utils.prependPath('../remove_tool');url+="?tool_id="+toolId;new Ajax.Request(url);}},statusChanged:function(projectId,select){var progress=$('project_'+projectId+'_progress_field');if(progress){if($F(select)!='1'){Element.hide(progress);}else{Element.show(progress);}}}};}();R.queue=function(){var adjustmentUser;return{createCollection:function(){R.collections.create('queue');},adjust:function(user,queuedProjectId,existing){adjustmentUser=user;var url='/people/'+user+'/queue/'+queuedProjectId+'/adjust?existing='+existing
RedBox.open('adjust_queue',url,{onComplete:function(request){RedBox.addHiddenContent('adjust_queue');R.queue.initializeAdjuster();}});},initializeAdjuster:function(){Sortable.create('top_of_queue',{tag:'div',only:'queued_item',onUpdate:function(){R.queue.saveAdjustment();}});},destroyAndAdjust:function(user,id){var url="/people/"+user+"/queue/"+id+"/destroy_and_adjust";new Ajax.Request(url,{method:'delete',onComplete:function(){R.queue.initializeAdjuster();}});},sortOrderEdited:function(input,originalSort){if(parseInt($(input).value)!=originalSort){$('queue_order_overlay').show();}},saveAdjustment:function(inPlace){var endFound=false;var order="";var end="";$A($('top_of_queue').childNodes).each(function(node){if(node.id=='sentinel'){endFound=true;}
if(node.className.indexOf('queued_item')>=0&&node.id!='dummy_item'){if(endFound&&end==""){end=getId(node);}else{if(order.length>0)order+=","
order+=getId(node);}}});var url="/people/"+adjustmentUser+"/queue/save_adjustment?order="+order+"&end="+end;if(inPlace){url+="&in_place=true";}
Element.show('wait');new Ajax.Request(url,{method:'post',onComplete:function(){Element.hide('wait');}});},addToQueue:function(user,parameters){if(parameters==null){parameters={}}
adjustmentUser=user;var id='add_to_queue_dialog';R.utils.initializeRedbox(id);RedBox.loading();new Ajax.Updater(id,'/people/'+user+'/queue/new?'+$H(parameters).toQueryString(),{asynchronous:true,evalScripts:true,method:'get',onComplete:function(request){RedBox.addHiddenContent(id);}});}};}();R.quicknav=function(){return{clicked:function(id,base){var action='quicknav';var url=R.utils.prependPath(id+'/'+action,true);if(base){url=base+'/'+id+'/'+action;}
new Ajax.Request(url,{method:'get'});},prepare:function(){var q=$('quicknav');if(q){q.hide();}else{new Insertion.Bottom(document.body,'<div id="quicknav" style="display: none;"></div>');Element.observe(document.body,'click',function(e){var ticky_box=$(Event.element(e)).up('.ticky_item');if(!ticky_box){$('quicknav').hide();}});}},show:function(id,options){var quicknav=$('quicknav');var top=options&&options.top!=undefined?options.top:4;var left=options&&options.left!=undefined?options.left:159;var selector=$("forum_post_"+id+"_user");if(!selector){selector=$("quick_selector_"+id);var position=Position.cumulativeOffset(selector);quicknav.style.top=(parseInt(position[1])-top)+"px";quicknav.style.left=(parseInt(position[0])-left)+"px";}else{var position=Position.cumulativeOffset(selector);quicknav.style.top=(parseInt(position[1])+110)+"px";quicknav.style.left=(parseInt(position[0]))+"px";}
new Effect.SlideDown('quicknav',{duration:.25});}};}();var RedBox={hiddenContentIds:new Array(),open:function(boxId,url,options){if(!options){options={};}
if(!$(boxId)){new Insertion.Bottom(document.body,"<div id='"+boxId+"'></div>");}
options=$H({onComplete:function(request){RedBox.addHiddenContent(boxId);},method:'get'}).merge(options);RedBox.loading();new Ajax.Updater(boxId,url,options);},makeDraggable:function(id,drag_handle){if($(id)){new Draggable($(id).parentNode,{handle:drag_handle,ghosting:false,starteffect:null,endeffect:null});}},showInline:function(id){this.showOverlay();new Effect.Appear('RB_window',{duration:0.4,queue:'end'});Element.scrollTo('RB_window');this.cloneWindowContents(id);},loading:function(options){RedBox.showOverlay(options);Element.show('RB_loading');},addHiddenContent:function(id){this.removeChildrenFromNode($('RB_window'));this.moveChildren($(id),$('RB_window'));Element.hide('RB_loading');new Effect.Appear('RB_window',{duration:0.3,queue:'end'});this.setWindowPosition();RedBox.hiddenContentIds.push(id);},close:function(){Element.removeClassName(document.body,'picture_show');if(!Element.visible('content')){$('content').style.display='';Element.hide('RB_window');Element.hide('RB_overlay');RedBox.showSelectBoxes();}else{Element.hide('RB_window');Element.hide('RB_overlay');RedBox.showSelectBoxes();}},showOverlay:function(options){if($('RB_redbox')){Element.update('RB_redbox',"");new Insertion.Bottom($('RB_redbox'),'<div id="RB_window" style="display: none;"></div><div id="RB_overlay" style="display: none;"></div>');}else{new Insertion.Bottom(document.body,'<div id="RB_redbox" align="center"><div id="RB_window" style="display: none;"></div><div id="RB_overlay" style="display: none;"></div></div>');}
new Insertion.Bottom('RB_redbox','<div id="RB_loading" style="display: none"></div>');Event.observe('RB_overlay','click',function(event){RedBox.close();});this.setOverlaySize();this.hideSelectBoxes();if(!options||options.fade){new Effect.Appear('RB_overlay',{duration:0.0,to:0.35,queue:'end'});}},setOverlaySize:function(){if(window.innerHeight&&window.scrollMaxY)
{yScroll=window.innerHeight+window.scrollMaxY;}
else if(document.body.scrollHeight>document.body.offsetHeight)
{yScroll=document.body.scrollHeight;}
else
{yScroll=document.body.offsetHeight;}
$("RB_overlay").style['height']=yScroll+"px";},setWindowPosition:function(){var pagesize=this.getPageSize();$("RB_window").style['width']='auto';$("RB_window").style['height']='auto';var dimensions=Element.getDimensions($("RB_window"));var width=dimensions.width;var height=dimensions.height;$("RB_window").style['left']=((pagesize[0]-width)/2)+"px";$("RB_window").style['top']=((document.documentElement.scrollTop||document.body.scrollTop)+15)+"px";},getPageSize:function(){var de=document.documentElement;var w=window.innerWidth||self.innerWidth||(de&&de.clientWidth)||document.body.clientWidth;var h=window.innerHeight||self.innerHeight||(de&&de.clientHeight)||document.body.clientHeight;arrayPageSize=new Array(w,h)
return arrayPageSize;},removeChildrenFromNode:function(node){while(node.hasChildNodes()){node.removeChild(node.firstChild);}},moveChildren:function(source,destination){while(source.hasChildNodes()){destination.appendChild(source.firstChild);}},cloneWindowContents:function(id){var content=$(id).cloneNode(true);content.style['display']='block';$('RB_window').appendChild(content);this.setWindowPosition();},hideSelectBoxes:function(){$$('select').each(function(e){e.style.visibility="hidden";});$$('textarea').each(function(e){e.style.overflow="hidden";});},showSelectBoxes:function(){$$('select').each(function(e){e.style.visibility="visible";});$$('textarea').each(function(e){e.style.overflow="";});}}
R.search=function(){var documentObserver=false;var autocompleters={};return{initialize:function(){R.utils.observeHover('search_actions','a');if($('filter_menu_button')){R.menu.setup('filter_menu_button','sidebar');}
R.search.updateViewIcon();},autocomplete:function(index,id){if(autocompleters[index]){autocompleter.onBlur=function(){};autocompleter.onKeyPress=function(){};}
if(id){url=prependPath('autocomplete/'+id);autocompleters[index]=new Ajax.Autocompleter('add_'+index,'suggestions_'+index,url,{});}},positionFilterEntry:function(id,prefix,group){Element.show($('filter_entry'));var oldLeft=Position.cumulativeOffset($("filter_entry"))[0];var left=10;var anchor=$('filter_'+id);if(anchor){left=Position.cumulativeOffset(anchor)[0];}
new Effect.MoveBy('filter_entry',0,left-oldLeft);if($('add_0')){$('add_0').focus();}else if($('add')){$('add_id').focus();}},positionFilterEntryOld:function(id,prefix){new Effect.MoveBy('filter_entry',top,left,{duration:0.2,mode:'absolute',afterFinish:function(){if($('add_value')){$('add_value').activate();}}});},removeFilter:function(id){$('r').value=id;R.search.applyFilter();},prepareFilter:function(type,id){R.search.editFilter(type,id);},editFilter:function(type,id,prefix,groupId){if($('add_id')){$('add_id').value='';}
var url='/'+type+'/search/edit_filter/'+id;var params=Form.serialize($('filter_search_form'));params['search']=type;if(prefix)params['prefix']=prefix;if(groupId)params['group_id']=groupId;new Ajax.Request(url,{parameters:params,evalScripts:true});},cancelFilterEntry:function(groupId){Element.hide($('filter_entry'));},applyFilter:function(addId,addValue,replaceValue,reload){R.menu.collapse();if(addId&&addValue==''){var typeHack=(document.location.pathname+"").split('/')[1];R.search.editFilter(typeHack,addId);return;}
R.search.updateViewIcon();R.search.spinner();if($('apply')){$('apply').value='1';}
var skipForm=addId&&addValue;var params=R.search.formParameters(skipForm);var attr=replaceValue?'add_0':'add';var append=null;if(skipForm){params['add_id']=addId;params[attr]=addValue;params['apply']=1;append="add_id="+addId+"&"+attr+"="+addValue+"&apply="+1;}
R.search.storeHistory(append);if(reload){document.location.href=$('filter_search_form').action+"?"+$H(params).toQueryString();}else{new Ajax.Request($('filter_search_form').action,{parameters:params,evalScripts:true});}},formParameters:function(skipForm){var params=$H(Form.serialize('filter_search_form'));if($('filter_entry_form')&&!skipForm){params=params.merge($H(Form.serialize('filter_entry_form')));}
return params;},storeHistory:function(append){var history=Form.serializeElements(Form.getElements('filter_search_form'),false);if($('filter_entry_form')){history+='&'+Form.serializeElements(Form.getElements('filter_entry_form'),false);}
if(append){history+="&"+append;}
dhtmlHistory.add(history+"&history=1",null);},clearQuery:function(){$('query').value='';R.search.applyFilter();},filterApplied:function(){if($('indicator')){Element.hide('indicator');}
if($('apply')){$('apply').value='0';}},filterPanelSelected:function(selected){$A(['simple','advanced']).each(function(n){if(n==selected){Element.addClassName(n+'_filter_nav','active');Element.show(n+'_filter_panel');}else{Element.removeClassName(n+'_filter_nav','active');Element.hide(n+'_filter_panel');}});if(selected=='simple'){$('add_multi').value='0';}else{$('add_multi').value='1';}},historyChanged:function(string){if(string&&string.indexOf('history=1')>=0){Element.update($('search_results'),'');var form=$('filter_search_form');R.search.spinner();new Ajax.Request(form.action,{parameters:string,evalScripts:true});}},modifierSelected:function(select,index){var modifier=$F(select);$A(['and','or','not']).each(function(m){if(m==modifier){$("add_"+index).addClassName("boolean_"+m);$("mod_"+index).addClassName("modifier_"+m);}else{$("add_"+index).removeClassName("boolean_"+m);$("mod_"+index).removeClassName("modifier_"+m);}});},modifiersInitialized:function(indexes){$A(indexes).each(function(i){R.search.modifierSelected($('mod_'+i),i)});},cleanForm:function(string){},resort:function(){R.search.applyFilter(null,null,null,true);},updateViewIcon:function(){if($('view')){$('view_image').src="/images/view-"+$F('view')+".png";}},changeView:function(){R.search.applyFilter(null,null,null,true);},sliderMoved:function(values){var from=Math.round(values[0]*10)/10;var to=Math.round(values[1]*10)/10;$('add_0').value=from;$('add_0_end').value=to;$('slider_text').innerHTML=from+" to "+to;},sliderChanged:function(value){R.search.sliderMoved(value);R.search.applyFilter();},showAdvanced:function(){$('search_body').addClassName('advanced_search');$('filters').show();if($('advanced_link')){$('advanced_link').hide();}},spinner:function(){$('result_counts').innerHTML='<img src="/images/circle-ball-dark-antialiased.gif"/>';},selectAction:function(){if(!documentObserver){Event.observe(document,'click',function(e){if(Event.element(e)&&Event.element(e).id!='selector'&&Event.element(e).id!='search_actions'){Element.hide('search_actions');}
documentObserver=true;});}
Element.show('search_actions');}}}();Autocompleter.Filters=Class.create();Autocompleter.Filters.prototype=Object.extend(new Autocompleter.Base(),{initialize:function(element,update,array,options){this.baseInitialize(element,update,options);this.options.array=array;},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this));},selectEntry:function(){if(this.getCurrentEntry().id=='suggestion_anchor'){return;}
this.active=false;this.element.value=this.element.value.replace(": ",":").replace(this.getToken(),'');var parts=this.getCurrentEntry().id.split(':');var prefix=parts[0];var value='';if(parts.length>1)value=parts[1];R.search.applyFilter(prefix,value);},getToken:function(){caret=R.utils.getCaretInfo(this.element).caret;var parts=this.element.value.replace(": ",":").split(/\s+/);var part=parts[0];var pos=0;for(var i=0;i<parts.length;i++){for(var j=0;j<parts[i].length;j++){if(pos<caret)part=parts[i];pos++;}
pos++;}
return part;},setOptions:function(options){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,fullSearch:false,selector:function(instance){var ret=[];var partial=[];var token=instance.getToken();var count=0;ret.push("<li id='suggestion_anchor'>&nbsp;</li>");for(var i=0;i<instance.options.array.length&&ret.length<instance.options.choices;i++){var entry=token;var elem=instance.options.array[i][0];var id=instance.options.array[i][1];var prefix=null;var foundPos=null;if(id[id.length-1]==':'&&entry.indexOf(':')>0){var parts=entry.split(':');var prefix=parts[0];if(elem.toLowerCase().indexOf(prefix.toLowerCase())>=0){entry=parts[1];elem=elem+": "+entry;id=id+entry;foundPos=elem.toLowerCase().indexOf(entry.toLowerCase());}}
if(!foundPos){foundPos=elem.toLowerCase().indexOf(entry.toLowerCase());}
while(foundPos!=-1){if(foundPos==0&&elem.length!=entry.length){ret.push("<li id='"+id+"'><strong>"+elem.substr(0,entry.length)+"</strong>"+
elem.substr(entry.length)+"</li>");break;}else if(entry.length>=instance.options.partialChars&&instance.options.partialSearch&&foundPos!=-1){if(instance.options.fullSearch||/\s/.test(elem.substr(foundPos-1,1))){partial.push("<li id='"+id+"'>"+elem.substr(0,foundPos)+"<strong>"+
elem.substr(foundPos,entry.length)+"</strong>"+elem.substr(foundPos+entry.length)+"</li>");break;}}
foundPos=elem.toLowerCase().indexOf(entry.toLowerCase(),foundPos+1);}}
if(partial.length)
ret=ret.concat(partial.slice(0,instance.options.choices-ret.length))
if(ret.length==1)ret=[];return"<ul>"+ret.join('')+"</ul>";}},options||{});}});R.searchlight=function(){var pendingSearch;var opened=false;var starSearch=null;var exactSearch=null;var previousSearch=null
var eventHandlersRegistered=false;var highlightedItem=-1;var currentlySelected=null;return{tabClicked:function(){if(Element.visible('searchlight')){R.searchlight.close();}else{R.searchlight.open();}},open:function(){$('search_tab').style.backgroundImage="url(/images/nav-tab-2-lit.png)"
Element.show($('searchlight'));$('searchlight_term').focus();if(!eventHandlersRegistered){Element.observe(document.body,'keypress',function(e){R.searchlight.keyUp(e);});eventHandlersRegistered=true;}
if($('searchlight_term').value!=''){R.searchlight.search();}},close:function(e){$('search_tab').style.backgroundImage=null;$('searchlight').hide();var evt=e?e:window.event;if(evt){Event.stop(evt);}
$('searchlight_progress').innerHTML='';},keyUp:function(event){if(starSearch){window.clearTimeout(starSearch);startSearch=null;}
if(event.keyCode==Event.KEY_DOWN||event.keyCode==Event.KEY_UP){if(event.keyCode==Event.KEY_DOWN){highlightedItem++;}else if(event.keyCode==Event.KEY_UP){highlightedItem--;}
var selected=$$('#searchlight_results a')[highlightedItem];if(selected){if(currentlySelected){currentlySelected.style.backgroundColor="";}
currentlySelected=selected;selected.style.backgroundColor="#c2ebb1";}}
starSearch=window.setTimeout("R.searchlight.search(true);",350);},searchCompleted:function(){var needHeight=($('searchlight').getHeight()+200);if(needHeight>document.viewport.getHeight()){$('page').style.minHeight=needHeight+"px";}else{$('page').style.minHeight="100%";}},search:function(star){var query=$('searchlight_term').value;if(query.length>2&&previousSearch!=query){previousSearch=query;$('searchlight_progress').innerHTML="<img src='/images/progress.gif' />";if(pendingSearch){clearTimeout(pendingSearch);}
pendingSearch=setTimeout(function(){new Ajax.Request('/searchlight/search?query='+encodeURIComponent(query),{method:'get'});},200);}}}}();R.shop=function(){var checkedOut=false;return{buyPattern:function(patternId){RedBox.open('buy_pattern_box','/patterns/library/'+patternId+"/buy");},buyEbook:function(patternId){RedBox.open('buy_pattern_box','/patterns/sources/'+patternId+"/buy");},freePattern:function(patternId){RedBox.open('buy_pattern_box','/patterns/library/'+patternId+"/free");},addToCart:function(productId){new Ajax.Request('/carts/add/'+productId);},showCart:function(){RedBox.open('cart_box','/carts/dialog');},cartKeypress:function(cartId){Element.show('cart_'+cartId+'_save');},checkout:function(){if(checkedOut){document.location.href='/carts';}else{checkoutOut=true;document.forms["paypal_form"].target="_top";window.setTimeout('document.forms["paypal_form"].submit();',1000);}},saveCart:function(cartId){form=$('cart_'+cartId);var indicator=$('cart_'+cartId+'_indicator');var save=$('cart_'+cartId+'_save');Element.show(indicator);new Ajax.Request('/carts/'+cartId,{method:'put',parameters:Form.serialize(form),onComplete:function(){Element.hide(indicator);Element.hide(save);}});}};}();R.shops=function(){return{validateEditForm:function(){var comment=$('shop_change_comment');if(comment.value==''){alert('Please describe the change that you are making - it is used for a history of revisions.');comment.focus();return false;}else{return true;}},initialize:function(){}}}();R.stashes=function(){return{deleteStash:function(stashId,view,title){var message='Are you sure that you want to delete this stashed yarn permanently?';if(title){message='Are you sure that you want to delete "'+title.innerHTML.strip()+'" permanently?'}
if(confirm(message)){var url=R.utils.prependPath(stashId,true);var parameters=view!=null?"method=_delete&view="+view:"method=_delete";new Ajax.Request(url,{asynchronous:true,evalScripts:true,method:'delete'});}},prepareWithYarn:function(yarnId){$('prepare_pack_form_yarn_id').value=yarnId;$('prepare_pack_form_yarn_selected').value=1;$('prepare_pack_form').submit();},toggleYarnDetails:function(show,options){options&&options.local?Element.show('local_shop_details'):Element.hide('local_shop_details')
options&&options.online?Element.show('online_shop_details'):Element.hide('online_shop_details')
if(show){Element.show('yarn_details');}else{Element.hide('yarn_details');}},selectForProject:function(projectId,user){RedBox.open('stash_selection','/people/'+user+'/stash/prepare_select?project_id='+projectId);}};}();R.store=function(){return{initialize:function(){if(document.body.className.indexOf('reviews_action')>=0){triggeredMarkdownEditor('comment_text');}},statisticsSummaryOver:function(productAttachmentId){var o=$("attachment_link_"+productAttachmentId).parentNode.parentNode;$("attachment_link_"+productAttachmentId).style.color='white';o.style.backgroundColor='black';},statisticsSummaryOut:function(productAttachmentId){var o=$("attachment_link_"+productAttachmentId).parentNode.parentNode;$("attachment_link_"+productAttachmentId).style.color='';o.style.backgroundColor='';o.style.fontWeight='';},terms:function(){RedBox.open('terms','terms');},processingGift:function(){$('buttons').innerHTML="<img src='/images/circle-ball-antialiased.gif' />";}}}();R.swatch=function(){swatchList=null;return{addCode:function(){$('submit').hide();$('indicator').show();var code=$('code').value;$('code').value='';new Ajax.Request("/swatch/add?code="+code);},removeCode:function(code){new Ajax.Request("/swatch/remove?code="+code);},setSwatching:function(set){swatchList=$A(set);},isSwatching:function(code){return swatchList&&swatchList.indexOf(code)>=0;}};}();R.tags=function(){var findTagList=function(taggableId){if($('project_tag_list'))return $('project_tag_list');if($('stash_tag_list'))return $('stash_tag_list');if($('product_family_tag_list'))return $('product_family_tag_list');if(taggableId&&$('bookmark_'+taggableId+'_tag_list'))return $('bookmark_'+taggableId+'_tag_list');return null;};return{addRestrictedTag:function(select){new Ajax.Request('add_tag',{parameters:{tag:$F(select)}});},tagDialog:function(options){if(!options)options={}
var tags="";var list=findTagList(options.taggableId);if(list){tags=list.value;}
var url='/tags/dialog?taggable_id='+options.taggableId+"&taggable_type="+options.taggableType+"&tags="+encodeURIComponent(tags);if(options.lookupTags)url+="&lookup_tags=true";if(options.specialEvent)url+="&special_event="+options.specialEvent;var box=R.utils.initializeRedbox('tag_box');RedBox.loading();new Ajax.Updater(box,url,{asynchronous:true,onComplete:function(request){RedBox.addHiddenContent(box);},evalScripts:true});},hideInPlace:function(fade){var e=fade?Effect.Fade:Effect.SlideUp;new e('inplace_tag_editor',{afterFinish:function(){Element.remove('inplace_tag_editor');}});},selectDialogTag:function(element,name){var tags=$('tag_dialog_tag_list').value.split(' ');if(tags.indexOf(name)>=0){Element.removeClassName(element.parentNode,'selected_tag');$('tag_dialog_tag_list').value=$A(tags).without(name).join(' ');}else{Element.addClassName(element.parentNode,'selected_tag');$('tag_dialog_tag_list').value+=' '+name;}},saveDialogTags:function(user,taggableType,taggableId){var tags=$('tag_dialog_tag_list').value;var list=findTagList(taggableId);if(list){list.value=tags;}else if(taggableType=='Bookmark'){var url='/people/'+user+'/bookmarks/'+taggableId+'/tag?bookmark[tags_list]='+encodeURIComponent(tags);new Ajax.Request(url,{asynchronous:true,evalScripts:true});}
RedBox.close();}};}();R.time=function(){return{checkTimeZone:function(){R.time.setTimeZone();},setTimeZone:function(){var date=new Date();date.setTime(date.getTime()+(60*60*1000));var expires="; expires="+date.toGMTString();document.cookie="timezone="+(-date.getTimezoneOffset()*60)+expires+"; path=/";}};}();R.tools=function(){return{selectForProject:function(projectId,user){RedBox.open('tool_selection','/people/'+user+'/tools/prepare_select?project_id='+projectId);}};}();R.swfupload=function(){return{fileQueued:function(file){try{var txtFileName=$("filename");txtFileName.value=file.name;}catch(e){}},debug:function(message){if(("console"in window)&&("firebug"in console)){console.debug(message);}},reset:function(){$('filename').value='';},success:function(file,uploadId){$("upload_id_field").value=uploadId;$('filename').value='';$('swfupload_form').onsubmit();},loadFailed:function(){var form=$('swfupload_form');message="<a href='http://get.adobe.com/flashplayer/'><img src='/images/get_adobe_flash_player.png' class='inline' border='0'></a>"
message+="<span style='font-size:1.2em;'>Uploading requires Flash 9.0 or higher.</span><br/>";message+="Get the latest version of Flash at <a href='http://get.adobe.com/flashplayer/'>http://get.adobe.com/flashplayer</a>.";form.innerHTML=message;},expressInstall:function(){alert('express');},progress:function(file,bytesLoaded,bytesTotal){var progress_bar=$('slurper_progress');progress_bar.show();if($('progress_message')){$('progress_message').innerHTML="Uploaded "+parseInt(bytesLoaded/1000)+" of "+parseInt(bytesTotal/1000)+" KB"
$('progress_update').innerHTML=Math.round(bytesLoaded/bytesTotal*100.0)+"%"}}}}();R.upload=function(){var checkInterval=500;var nginxCheckInterval=250;var WIDTH=120;var NUDGE=2;var uploadProgress=null;return{reset:function(bar_container){var bar=$(bar_container).down('.progress_bar');bar.setStyle({'background-position':WIDTH+"px"});},draw:function(bar_container,percent,status,message){bar_container=$(bar_container);var bar=bar_container.down('.progress_bar');var fill=120+parseInt(percent*(WIDTH+NUDGE));$(bar).setStyle({'background-position':fill+"px"});bar_container.down('.status').innerHTML=status;bar_container.down('.message').innerHTML=message;},status:function(bar_container,status){bar_container=$(bar_container);bar_container.down('.status').innerHTML=status;},checkUploadProgress:function(progressId,options){uploadProgress=setTimeout(function(){new Ajax.Request('/nginx_progress',{method:'get',requestHeaders:{"X-Progress-ID":progressId},onSuccess:function(transport){var response=eval(transport.responseText);var progress_bar=$('upload_progress');if(response.state=='starting'){R.upload.checkUploadProgress(progressId,options);}else if(response.state=='uploading'&&response.received<response.size){var status=response.state+" (step 1 of 2)";var message="Received "+parseInt(response.received/1000)+" of "+parseInt(response.size/1000)+" KB"
R.upload.draw(progress_bar,response.received/response.size,status,message);R.upload.checkUploadProgress(progressId,options);}
if(response.state=='error'||response.state=='finished'||response.state=='done'||(response.state=='uploading'&&response.received==response.size)){R.upload.reset('upload_progress');}}});},nginxCheckInterval);},checkProcessProgress:function(progressId,options){if(uploadProgress){clearTimeout(uploadProgress);}
setTimeout(function(){new Ajax.Request('/documents/progress',{method:'get',parameters:{"X-Progress-ID":progressId},onSuccess:function(transport){var response=eval(transport.responseText);if(response.complete){var progress_bar=$('upload_progress');progress_bar.down('.status').innerHTML="";progress_bar.down('.message').innerHTML="Done!"
progress_bar.down('.progress_bar').setStyle({'background-position':(WIDTH*2)+"px"});new Effect.Fade(progress_bar);if(options.onComplete){var url=prependPath(options.onComplete).replace('/edit/','/');new Ajax.Request(url+"?document_id="+response.documentId,{method:'get'});}
form.down('.clicker').show();}else{if(response.progress){R.upload.draw('upload_progress',response.progress/100.0,"Storing uploaded file (step 2 of 2)",response.progress+"% complete");}else{R.upload.status('upload_progress',"Storing uploaded file (step 2 of 2)");}
R.upload.checkProcessProgress(progressId,options);}}});},checkInterval);},uploadProgress:function(form,options){form=$(form);form.down('.clicker').hide();var progressId="";for(i=0;i<32;i++){progressId+=Math.floor(Math.random()*16).toString(16);}
form.action=form.action.split('?')[0]+"?X-Progress-ID="+progressId;var progress_bar=$('upload_progress');progress_bar.show();R.upload.draw(progress_bar,0,"Uploading to Ravelry (step 1 of 2)","Starting...");R.upload.checkUploadProgress(progressId,options);}}}();R.utils=function(){var executors=new Object();return{callback:function(dummy,func){func();},selectOption:function(id,value){var options=$(id).options;for(var i=0;i<options.length;i++){if(options[i].value==value){options[i].selected=true;}}},initializeRedbox:function(id){if(!$(id)){new Insertion.Bottom(document.body,"<div id='"+id+"'></div>");}
return id;},prependPath:function(s,normalize){var path=document.location.pathname;if(path.charAt(path.length-1)!='/'){path+='/'}
if(normalize){path=path.replace(/\/stash\/(used|trade|handspun|gone)\//,'/stash/');path=path.replace(/\/people\/(.*?)\/(edit)\//,'/people/$1/');}
return path+s;},increment:function(id){$(id).value=parseInt($(id).value)+1;},keyCode:function(ev){return ev.keyCode?ev.keyCode:ev.which?ev.which:ev.charCode;},followFirstLink:function(element,new_window){var elements=element.getElementsByTagName('a');if(elements.length>0){var href=elements[0].getAttribute('href');if(!new_window){document.location.href=href;}else{window.open(href);}
return true;}else{return false;}},observeHover:function(root,selector){var parent=$(root);if(parent){Element.getElementsBySelector(root,selector).each(function(element){Event.observe(element,'mouseover',function(){Element.addClassName(element,'hover');});Event.observe(element,'mouseout',function(){Element.removeClassName(element,'hover');});});}},clickFollowsFirstLink:function(root,selector){var parent=$(root);if(parent){if(selector){Element.getElementsBySelector(root,selector).each(function(element){Event.observe(element,'click',function(e){if(Event.element(e).tagName!='A'){R.utils.followFirstLink(element);}});});}else{Event.observe(root,'click',function(e){if(Event.element(e).tagName!='A'){R.utils.followFirstLink(root);}});}}},captureEnterKey:function(e){var evt=e?e:window.event;if(evt&&evt.keyCode==13){Event.stop(evt);return false;}else{return true;}},applyFancyTables:function(id){var tables=id?[$(id)]:document.getElementsByTagName('table');$A(tables).each(function(table){var addHovers=Element.hasClassName(table,'grid')&&!Element.hasClassName(table,'nohover');var followLinks=Element.hasClassName(table,'clickable');if(addHovers||followLinks){var rows=table.getElementsByTagName('tr');for(i=0;i<rows.length;i++){var row=rows[i];if(addHovers){row.onmouseover=function(){Element.addClassName(this,'hover');};row.onmouseout=function(){Element.removeClassName(this,'hover');};}
if(followLinks){row.onclick=R.utils.tableRowClicked;}}}});},highlightTextArea:function(textarea,index){var ta1=$(textarea)
var str=ta1.value+" ";var num=parseInt(index);if(!num||(num<1)||isNaN(num))num=1;var start=0;var idx=0;while(--num>0){do{idx=str.search(/\W/)+1;start+=idx;str=str.substring(idx,str.length);}while(str.search(/\W/)===0);}
if(typeof(ta1.selectionStart)=='number'){setTimeout(function(){ta1.focus();ta1.select();ta1.selectionStart=start;ta1.selectionEnd=start+str.search(/\W/);},1);}else if(document.selection&&document.selection.createRange){setTimeout(function(){ta1.focus();ta1.select();var rng=document.selection.createRange();rng.collapse();rng.moveStart('character',start);rng.moveEnd('character',str.search(/\W/));rng.select();},1);}},tableRowClicked:function(e){var evt=e?e:window.event;var table=Event.findElement(evt,'table');var clickableStatus=Element.hasClassName(table,'topics');var followLinks=Element.hasClassName(table,'clickable');var skipLink=false;if(clickableStatus){var status=Event.findElement(evt,'td');if(status&&status.className&&Element.hasClassName(status,'status')){skipLink=true;var topicId=getId(this);R.forums.topicTools('all',topicId,'glance',evt);}}
var clicked=Event.findElement(evt,'a');if(!skipLink&&(!clicked||!clicked.getAttribute||!clicked.getAttribute('href'))){var preferred=Element.getElementsBySelector(this,'.preferred').first();if(preferred==null){preferred=this;}
navigateToFirstLink(preferred);}
if(skipLink){Event.stop(evt);}},cleanRedboxForms:function(){$A(RedBox.hiddenContentIds).each(function(id){var element=$(id);if(element){var div=document.createElement("div");div.id=element.id
Element.remove(element);document.body.appendChild(div);}});},updateAutosubmitForms:function(selector){$$(selector).each(function(form){R.utils.updateAutosubmitForm(form);});},updateAutosubmitForm:function(form){form=$(form);if(form.tagged){return;}
form.tagged=true;Element.getElementsBySelector(form,'select').each(function(element){Event.observe(element,'change',function(){var p=element.parentNode;while(!p.onsubmit)p=p.parentNode;if(p)p.onsubmit();});Event.observe(element,'keypress',function(){var p=element.parentNode;while(!p.onsubmit)p=p.parentNode;if(p)p.onsubmit();});});Element.getElementsBySelector(form,'input').each(function(element){new Form.Element.Observer(element,.3,function(e){var formId=form.id;if(formId){if(executors[formId]){window.clearTimeout(executors[formId]);}
executors[formId]=window.setTimeout('$("'+formId+'").onsubmit();',500);}});});},radio:function(formId,radioGroup){return Form.getInputs(formId,'radio',radioGroup).find(function(radio){return radio.checked;}).value;},draft:function(textarea,id){var expires=new Date((new Date()).getTime()+(1000*60*60*24));try{var text=textarea.value;if(text!=""){setCookie('draft_'+id,text,expires);}}catch(e){}
return true;},clearDraft:function(id){deleteCookie('draft_'+id);},getDraft:function(id){return getCookie('draft_'+id);},checkForDrafts:function(){var link=$('recover_draft');if(link&&R.utils.getDraft('forum_post')){Element.show(link);}},recoverDraft:function(textarea,id){if(textarea.value==""||confirm('Are you sure that you want to replace your post with the last saved draft?')){textarea.value=R.utils.getDraft(id);R.utils.clearDraft(id);Element.hide('recover_draft');}},popup:function(custom_options){options={url:'#',width:600,height:500,name:'_blank',location:'no',menubar:'no',toolbar:'no',status:'yes',scrollbars:'yes',resizable:'yes',left:'',top:'',normal:false};Object.extend(options,custom_options||{});if(options.normal){options.menubar="yes";options.status="yes";options.toolbar="yes";options.location="yes";}
options.width=options.width<screen.availWidth?options.width:screen.availWidth;options.height=options.height<screen.availHeight?options.height:screen.availHeight;var openoptions='width='+options.width+',height='+options.height+',location='+options.location+',menubar='+
options.menubar+',toolbar='+options.toolbar+',scrollbars='+options.scrollbars+',resizable='+options.resizable+',status='+options.status;if(options.top!="")openoptions+=",top="+options.top;if(options.left!="")openoptions+=",left="+options.left;window.open(options.url,options.name,openoptions);return false;},getCaretInfo:function(textbox){var docObj=textbox.ownerDocument;var result={start:0,end:0,caret:0};if(navigator.appVersion.indexOf("MSIE")!=-1){if(textbox.tagName.toLowerCase()=="textarea"){if(textbox.value.charCodeAt(textbox.value.length-1)<14){textbox.value=textbox.value.replace(/34/g,'')+String.fromCharCode(28);}
var oRng=docObj.selection.createRange();var oRng2=oRng.duplicate();oRng2.moveToElementText(textbox);oRng2.setEndPoint('StartToEnd',oRng);result.end=textbox.value.length-oRng2.text.length;oRng2.setEndPoint('StartToStart',oRng);result.start=textbox.value.length-oRng2.text.length;result.caret=result.end;if(textbox.value.substr(textbox.value.length-1)==String.fromCharCode(28)){textbox.value=textbox.value.substr(0,textbox.value.length-1);}}else{var range=docObj.selection.createRange();var r2=range.duplicate();result.start=0-r2.moveStart('character',-100000);result.end=result.start+range.text.length;result.caret=result.end;}}else{result.start=textbox.selectionStart;result.end=textbox.selectionEnd;result.caret=result.end;}
if(result.start<0){result={start:0,end:0,caret:0};}
return result;}};}();R.welcome=function(){return{initialize:function(){R.time.setTimeZone();}};}();R.wiki=function(){return{initialize:function(){$$('table#revisions tbody tr','table#pages tbody tr').each(function(element){Event.observe(element,'click',function(event){navigateToFirstLink(element);});});},highlightBrokenLinks:function(links){if(links.length==0){return;}
links=$A(links);$$("#wiki_content a").each(function(element){if(links.indexOf(element.href)>=0){Element.addClassName(element,'broken');new Effect.Highlight(element,{startcolor:'#ff0000',endcolor:'#ffffff'});}});}};}();R.yarns=function(){return{validateEditForm:function(){var comment=$('yarn_change_comment');if(comment.value==''){alert('Please describe the change that you are making - it is used for a history of revisions.');comment.focus();return false;}else{return true;}},notEditable:function(permalink){RedBox.open('not_editable','/yarns/library/'+permalink+'/not_editable');},searchBrandDialog:function(){var url='/yarns/brands/search_dialog?q='+name
RedBox.open('brand_dialog_box',url);},searchDialog:function(typePrefix,options){if(!options){options={};}
var name=options.name;if(typePrefix&&(name==null||name=='')&&$(typePrefix+'_name')){name=$F(typePrefix+'_name');}else{name='';}
var box=typePrefix+'_redbox';var url='/yarns/search_dialog?q='+name;if(options){if(options.contribute){url+="&contribute=true";}
if(options.stash){url+="&stash="+options.stash;}
if(options.linkable==false){url+="&linkable=false";}
if(options.advertising==true){url+="&advertising=true";}}
initializeRedbox(box);RedBox.loading();new Ajax.Updater(box,url,{asynchronous:true,onComplete:function(request){RedBox.addHiddenContent(box);},evalScripts:true});}};}();R.onload=function(){var stack=[];var interval;var loaded=false;return{setLoaded:function(){loaded=true;R.onload.doPoll();},doPoll:function(){var notFound=[];for(var i=0;i<stack.length;i++){if(document.getElementById(stack[i].id)){stack[i].callback();}else{notFound.push(stack[i]);}}
stack=notFound;if(notFound.length<1||loaded){R.onload.stopPolling();}},startPolling:function(){if(interval){return;}
interval=setInterval(R.onload.doPoll,10);},stopPolling:function(){if(!interval){return;}
clearInterval(interval);interval=null;},onAvailable:function(id,callback){stack.push({id:id,callback:callback});R.onload.startPolling();}};}();addDOMLoadEvent(function(){R.utils.observeHover('navigation','li');R.utils.observeHover('tabset','span');R.utils.observeHover('notebook_menu','li');R.utils.clickFollowsFirstLink('notebook_menu','li');R.utils.cleanRedboxForms();updateEndlessPageless();if(!Browser.isMSIE6()&&$('notebook_menu')){Event.observe($('notebook_tab'),'mouseover',function(){if(!Element.visible('notebook_menu')){Element.show('notebook_menu');}});Event.observe($('notebook_tab'),'mouseout',function(){Element.hide('notebook_menu');return true;});}
var initializers=new Object();initializers['notebook']=notebookLoaded;initializers['projects']=projectsLoaded;initializers['stash']=stashLoaded;initializers['patterns']=patternsLoaded;initializers['people']=peopleLoaded;initializers['designers']=designersLoaded;initializers['knitalongs']=knitalongsLoaded;initializers['yarn_companies']=yarnCompaniesLoaded;initializers['yarns']=yarnsLoaded;initializers['discussions']=discussionsLoaded;initializers['topics']=topicsLoaded;initializers['pattern_sources']=patternSourcesLoaded;initializers['admin']=adminLoaded;initializers['help']=helpLoaded;initializers['groups']=groupsLoaded;initializers['pages']=groupsLoaded;initializers['events']=R.events.initialize;initializers['welcome']=R.welcome.initialize;initializers['pattern_search']=R.patterns.search.initialize;initializers['issues']=R.issues.initialize;initializers['wiki']=R.wiki.initialize;initializers['shops']=R.shops.initialize;initializers['product_families']=R.store.initialize;initializers['products']=R.store.initialize;initializers['topics']=R.forums.initializeTopic;initializers['manager_ads']=function(){R.manager.ads.initialize()};initializers['advertisers']=function(){R.advertisers.initializer.initialize();};R.onload.setLoaded();var mainClass="";if(document.body.className){var bodyClasses=document.body.className.split(' ');if(bodyClasses.length>0){mainClass=bodyClasses[0];}}
initializer=initializers[mainClass];if(initializer){initializer();}
R.utils.applyFancyTables();$A(document.getElementsByTagName('form')).each(function(form){if(Element.hasClassName(form,'autosave')){Element.getElementsBySelector(form,'input','select','textarea').each(function(element){Event.observe(element,'keyup',function(){saveRequired();});});Element.getElementsByClassName(form,'textarea_preview').each(function(element){Event.observe(element,'click',function(){saveRequired();});});}
if(false){Element.getElementsByClassName(form,'.suggestable').each(function(element){var indicator=$(element.id+"_indicator");if(indicator&&element.value==""){indicator.src="/images/silk-none.png"}
if(indicator){Event.observe(element,'keyup',function(event){indicator.src=element.value==""?"/images/silk-none.png":"/images/silk-link.png";});}});}});updateMenuLinks();Event.observe(document,'click',function(ev){var clicked=ev?ev.target:window.event.srcElement;if(clicked&&clicked.tagName=='SPAN'&&(Element.hasClassName(clicked,'clicker')||Element.hasClassName(clicked,'clicker_icon'))){var targets=clicked.getElementsByTagName('a');if(targets.length==0){targets=clicked.getElementsByTagName('button');}
if(targets.length==1){target=targets[0];if(target.fireEvent){target.fireEvent('click');}else if(document.createEvent){clicking=document.createEvent("MouseEvents");clicking.initMouseEvent('click',true,true,window,1,1,1,1,1,false,false,false,false,0,target);target.dispatchEvent(clicking);}}}});if(window.editor_fields){loadRichText(window.editor_fields);}
if(window.swfupload_onload){R.swfupload.reset();}
R.time.checkTimeZone();Event.observe(document,'click',R.analytics.reportOutclick);if($('chatters')){new Effect.Appear('chatters');}});if(!("console"in window)||!("firebug"in console)){var names=["log","debug","info","warn","error","assert","dir","dirxml","group","groupEnd","time","timeEnd","count","trace","profile","profileEnd"];window.console={};for(var i=0;i<names.length;++i){window.console[names[i]]=function(){}}}