var Autocompleter=new Class({Implements:[Options,Events],options:{minLength:1,markQuery:true,width:"inherit",maxChoices:10,injectChoice:null,customChoices:null,emptyChoices:null,visibleChoices:true,className:"autocompleter-choices",zIndex:42,delay:400,observerOptions:{},fxOptions:{},autoSubmit:false,overflow:false,overflowMargin:25,selectFirst:false,filter:null,filterCase:false,filterSubset:false,forceSelect:false,selectMode:true,choicesMatch:null,multiple:false,separator:", ",separatorSplit:/\s*[,;]\s*/,autoTrim:false,allowDupes:false,cache:true,relative:false},initialize:function(b,a){this.element=$(b);this.setOptions(a);this.build();this.observer=new Observer(this.element,this.prefetch.bind(this),$merge({delay:this.options.delay},this.options.observerOptions));this.queryValue=null;if(this.options.filter){this.filter=this.options.filter.bind(this)}var c=this.options.selectMode;this.typeAhead=(c=="type-ahead");this.selectMode=(c===true)?"selection":c;this.cached=[]},build:function(){if($(this.options.customChoices)){this.choices=this.options.customChoices}else{this.choices=new Element("ul",{"class":this.options.className,styles:{zIndex:this.options.zIndex}}).inject(document.body);this.relative=false;if(this.options.relative){this.choices.inject(this.element,"after");this.relative=this.element.getOffsetParent()}this.fix=new OverlayFix(this.choices)}if(!this.options.separator.test(this.options.separatorSplit)){this.options.separatorSplit=this.options.separator}this.fx=(!this.options.fxOptions)?null:new Fx.Tween(this.choices,$merge({property:"opacity",link:"cancel",duration:200},this.options.fxOptions)).addEvent("onStart",Chain.prototype.clearChain).set(0);this.element.setProperty("autocomplete","off").addEvent((Browser.Engine.trident||Browser.Engine.webkit)?"keydown":"keypress",this.onCommand.bind(this)).addEvent("click",this.onCommand.bind(this,[false])).addEvent("focus",this.toggleFocus.create({bind:this,arguments:true,delay:100})).addEvent("blur",this.toggleFocus.create({bind:this,arguments:false,delay:100}))},destroy:function(){if(this.fix){this.fix.destroy()}this.choices=this.selected=this.choices.destroy()},toggleFocus:function(a){this.focussed=a;if(!a){this.hideChoices(true)}this.fireEvent((a)?"onFocus":"onBlur",[this.element])},onCommand:function(b){if(!b&&this.focussed){return this.prefetch()}if(b&&b.key&&!b.shift){switch(b.key){case"enter":if(this.element.value!=this.opted){return true}if(this.selected&&this.visible){this.choiceSelect(this.selected);return !!(this.options.autoSubmit)}break;case"up":case"down":if(!this.prefetch()&&this.queryValue!==null){var a=(b.key=="up");this.choiceOver((this.selected||this.choices)[(this.selected)?((a)?"getPrevious":"getNext"):((a)?"getLast":"getFirst")](this.options.choicesMatch),true)}return false;case"esc":case"tab":this.hideChoices(true);break}}return true},setSelection:function(f){var g=this.selected.inputValue,h=g;var a=this.queryValue.length,c=g.length;if(g.substr(0,a).toLowerCase()!=this.queryValue.toLowerCase()){a=0}if(this.options.multiple){var e=this.options.separatorSplit;h=this.element.value;a+=this.queryIndex;c+=this.queryIndex;var b=h.substr(this.queryIndex).split(e,1)[0];h=h.substr(0,this.queryIndex)+g+h.substr(this.queryIndex+b.length);if(f){var d=h.split(this.options.separatorSplit).filter(function(k){return this.test(k)},/[^\s,]+/);if(!this.options.allowDupes){d=[].combine(d)}var j=this.options.separator;h=d.join(j)+j;c=h.length}}this.observer.setValue(h);this.opted=h;if(f||this.selectMode=="pick"){a=c}this.element.selectRange(a,c);this.fireEvent("onSelection",[this.element,this.selected,h,g])},showChoices:function(){var c=this.options.choicesMatch,b=this.choices.getFirst(c);this.selected=this.selectedValue=null;if(this.fix){var e=this.element.getCoordinates(this.relative),a=this.options.width||"auto";this.choices.setStyles({left:e.left,top:e.bottom,width:(a===true||a=="inherit")?e.width:a})}if(!b){return}if(!this.visible){this.visible=true;this.choices.setStyle("display","");if(this.fx){this.fx.start(1)}this.fireEvent("onShow",[this.element,this.choices])}if(this.options.selectFirst||this.typeAhead||b.inputValue==this.queryValue){this.choiceOver(b,this.typeAhead)}var d=this.choices.getChildren(c),f=this.options.maxChoices;var j={overflowY:"hidden",height:""};this.overflown=false;if(d.length>f){var k=d[f-1];j.overflowY="scroll";j.height=k.getCoordinates(this.choices).bottom;this.overflown=true}this.choices.setStyles(j);this.fix.show();if(this.options.visibleChoices){var h=document.getScroll(),l=document.getSize(),g=this.choices.getCoordinates();if(g.right>h.x+l.x){h.x=g.right-l.x}if(g.bottom>h.y+l.y){h.y=g.bottom-l.y}window.scrollTo(Math.min(h.x,g.left),Math.min(h.y,g.top))}},hideChoices:function(a){if(a){var c=this.element.value;if(this.options.forceSelect){c=this.opted}if(this.options.autoTrim){c=c.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator)}this.observer.setValue(c)}if(!this.visible){return}this.visible=false;if(this.selected){this.selected.removeClass("autocompleter-selected")}this.observer.clear();var b=function(){this.choices.setStyle("display","none");this.fix.hide()}.bind(this);if(this.fx){this.fx.start(0).chain(b)}else{b()}this.fireEvent("onHide",[this.element,this.choices])},prefetch:function(){var f=this.element.value,e=f;if(this.options.multiple){var c=this.options.separatorSplit;var a=f.split(c);var b=this.element.getSelectedRange().start;var g=f.substr(0,b).split(c);var d=g.length-1;b-=g[d].length;e=a[d]}if(e.length<this.options.minLength){this.hideChoices()}else{if(e===this.queryValue||(this.visible&&e==this.selectedValue)){if(this.visible){return false}this.showChoices()}else{this.queryValue=e;this.queryIndex=b;if(!this.fetchCached()){this.query()}}}return true},fetchCached:function(){return false;if(!this.options.cache||!this.cached||!this.cached.length||this.cached.length>=this.options.maxChoices||this.queryValue){return false}this.update(this.filter(this.cached));return true},update:function(b){this.choices.empty();this.cached=b;var a=b&&$type(b);if(!a||(a=="array"&&!b.length)||(a=="hash"&&!b.getLength())){(this.options.emptyChoices||this.hideChoices).call(this)}else{if(this.options.maxChoices<b.length&&!this.options.overflow){b.length=this.options.maxChoices}b.each(this.options.injectChoice||function(d){var c=new Element("li",{html:this.markQueryValue(d)});c.inputValue=d;this.addChoiceEvents(c).inject(this.choices)},this);this.showChoices()}},choiceOver:function(c,d){if(!c||c==this.selected){return}if(this.selected){this.selected.removeClass("autocompleter-selected")}this.selected=c.addClass("autocompleter-selected");this.fireEvent("onSelect",[this.element,this.selected,d]);if(!this.selectMode){this.opted=this.element.value}if(!d){return}this.selectedValue=this.selected.inputValue;if(this.overflown){var f=this.selected.getCoordinates(this.choices),e=this.options.overflowMargin,g=this.choices.scrollTop,a=this.choices.offsetHeight,b=g+a;if(f.top-e<g&&g){this.choices.scrollTop=Math.max(f.top-e,0)}else{if(f.bottom+e>b){this.choices.scrollTop=Math.min(f.bottom-a+e,b)}}}if(this.selectMode){this.setSelection()}},choiceSelect:function(a){if(a){this.choiceOver(a)}this.setSelection(true);this.queryValue=false;this.hideChoices()},filter:function(a){return(a||this.tokens).filter(function(b){return this.test(b)},new RegExp(((this.options.filterSubset)?"":"^")+this.queryValue.escapeRegExp(),(this.options.filterCase)?"":"i"))},markQueryValue:function(a){return(!this.options.markQuery||!this.queryValue)?a:a.replace(new RegExp("("+((this.options.filterSubset)?"":"^")+this.queryValue.escapeRegExp()+")",(this.options.filterCase)?"":"i"),'<span class="autocompleter-queried">$1</span>')},addChoiceEvents:function(a){return a.addEvents({mouseover:this.choiceOver.bind(this,[a]),mousedown:this.choiceSelect.bind(this,[a])})}});var OverlayFix=new Class({initialize:function(a){if(Browser.Engine.trident){this.element=$(a);this.relative=this.element.getOffsetParent();this.fix=new Element("iframe",{frameborder:"0",scrolling:"no",src:"javascript:false;",styles:{position:"absolute",border:"none",display:"none",filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)"}}).inject(this.element,"after")}},show:function(){if(this.fix){var a=this.element.getCoordinates(this.relative);delete a.right;delete a.bottom;this.fix.setStyles($extend(a,{display:"",zIndex:(this.element.getStyle("zIndex")||1)-1}))}return this},hide:function(){if(this.fix){this.fix.setStyle("display","none")}return this},destroy:function(){if(this.fix){this.fix=this.fix.destroy()}}});Element.implement({getSelectedRange:function(){if(!Browser.Engine.trident){return{start:this.selectionStart,end:this.selectionEnd}}var e={start:0,end:0};var a=this.getDocument().selection.createRange();if(!a||a.parentElement()!=this){return e}var c=a.duplicate();if(this.type=="text"){e.start=0-c.moveStart("character",-100000);e.end=e.start+a.text.length}else{var b=this.value;var d=b.length-b.match(/[\n\r]*$/)[0].length;c.moveToElementText(this);c.setEndPoint("StartToEnd",a);e.end=d-c.text.length;c.setEndPoint("StartToStart",a);e.start=d-c.text.length}return e},selectRange:function(d,a){if(Browser.Engine.trident){var c=this.value.substr(d,a-d).replace(/\r/g,"").length;d=this.value.substr(0,d).replace(/\r/g,"").length;var b=this.createTextRange();b.collapse(true);b.moveEnd("character",d+c);b.moveStart("character",d);b.select()}else{this.focus();this.setSelectionRange(d,a)}return this}});Autocompleter.Base=Autocompleter;Autocompleter.Local=new Class({Extends:Autocompleter,options:{minLength:0,delay:200},initialize:function(b,c,a){this.parent(b,a);this.tokens=c},query:function(){this.update(this.filter())}});Autocompleter.Request=new Class({Extends:Autocompleter,options:{postData:{},ajaxOptions:{},postVar:"value"},query:function(){var c=$unlink(this.options.postData)||{};c[this.options.postVar]=this.queryValue;var b=$(this.options.indicator);if(b){b.setStyle("display","")}var a=this.options.indicatorClass;if(a){this.element.addClass(a)}this.fireEvent("onRequest",[this.element,this.request,c,this.queryValue]);this.request.send({data:c})},queryResponse:function(){var b=$(this.options.indicator);if(b){b.setStyle("display","none")}var a=this.options.indicatorClass;if(a){this.element.removeClass(a)}return this.fireEvent("onComplete",[this.element,this.request])}});Autocompleter.Request.JSON=new Class({Extends:Autocompleter.Request,initialize:function(c,b,a){this.parent(c,a);this.request=new Request.JSON($merge({url:b,link:"cancel"},this.options.ajaxOptions)).addEvent("onComplete",this.queryResponse.bind(this))},queryResponse:function(a){this.parent();this.update(a)}});Autocompleter.Request.HTML=new Class({Extends:Autocompleter.Request,initialize:function(c,b,a){this.parent(c,a);this.request=new Request.HTML($merge({url:b,link:"cancel",update:this.choices},this.options.ajaxOptions)).addEvent("onComplete",this.queryResponse.bind(this))},queryResponse:function(a,b){this.parent();if(!b||!b.length){this.hideChoices()}else{this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice||function(c){var d=c.innerHTML;c.inputValue=d;this.addChoiceEvents(c.set("html",this.markQueryValue(d)))},this);this.showChoices()}}});Autocompleter.Ajax={Base:Autocompleter.Request,Json:Autocompleter.Request.JSON,Xhtml:Autocompleter.Request.HTML};var Observer=new Class({Implements:[Options,Events],options:{periodical:false,delay:1000},initialize:function(c,a,b){this.element=$(c)||$$(c);this.addEvent("onFired",a);this.setOptions(b);this.bound=this.changed.bind(this);this.resume()},changed:function(){var a=this.element.get("value");if($equals(this.value,a)){return}this.clear();this.value=a;this.timeout=this.onFired.delay(this.options.delay,this)},setValue:function(a){this.value=a;this.element.set("value",a);return this.clear()},onFired:function(){this.fireEvent("onFired",[this.value,this.element])},clear:function(){$clear(this.timeout||null);return this},pause:function(){if(this.timer){$clear(this.timer)}else{this.element.removeEvent("keyup",this.bound)}return this.clear()},resume:function(){this.value=this.element.get("value");if(this.options.periodical){this.timer=this.changed.periodical(this.options.periodical,this)}else{this.element.addEvent("keyup",this.bound)}return this}});var $equals=function(b,a){return(b==a||JSON.encode(b)==JSON.encode(a))};var VinesSearchAC=new Class({Extends:Autocompleter.Request.JSON,options:{postVar:"q",maxChoices:20,ajaxOptions:{method:"get",sendJson:false},markQuery:false,observerOptions:{delay:500},selectFirst:true,zIndex:9999,selectMode:false,fxOptions:false,onFocus:function(a){if(!a.hasClass("ready")){a.addClass("ready").setProperty("value","")}},injectChoice:function(d){var c="",b;if(typeof(d)=="string"){c=d;choice=new Element("li",{html:c});choice.inputValue=this.queryValue}else{d=new Hash(d);if(this.options.ignore_no_image&&!d.image_url){return}if(!d.content_type_id){arr=d.url.split("/");var a=arr[2];arr=a.split("-");d.pk=arr[1];d.content_type_id=arr[0]}if(d.image_url){c+='<img src="'+d.image_url+'" alt="" />'}c+='<span class="name">'+d.name+"</span>";c+='<span class="type">'+d.content_type+"</span>";if(d.alias_match){c+='<span class="alias">(alias match)</span>'}choice=new Element("li",{html:c});d.object_id=d.object_id||d.pk;choice.store("token",d);choice.inputValue=d.name}choice.inject(this.choices);this.addChoiceEvents(choice)}},initialize:function(e,c,b){if(!$(e)){return false}if($(e).get("tag")=="input"&&$(e).getStyle("display")!="none"){var a={styles:{display:"inline-block",position:"relative"}};var d=new Element("span",a);d.inject($(e),"before");$(e).inject(d);var f={src:MEDIA_URL+"vine/img/icons/loader-rating.gif",styles:{display:"none",position:"absolute",right:"5px",top:"50%","margin-top":"-8px"}};this.loading_img=new Element("img",f);this.loading_img.inject(d);this.addEvent("onRequest",function(){this.loading_img.setStyle("display","")}.bind(this));this.addEvent("onComplete",function(){this.loading_img.setStyle("display","none")}.bind(this))}this.parent(e,c,b)},update:function(a){a=a||[];if(a.length===0){a.include('<div class="no-results">Sorry, no results.</div>')}this.parent(a)},choiceSelect:function(a){var b=a.retrieve("token");if(!b){return false}if(this.options.callBackEvent){this.element.fireEvent(this.options.callBackEvent,b)}else{pageTracker._trackEvent("Search","Selection",this.element.value+":"+b.name+":"+b.content_type_id+":"+b.object_id);document.location.href=b.url}this.parent(a)},hideChoices:function(a){if(!this.choices){return}this.parent(a)}});VinesSearchAC.BaseWithAds=new Class({Extends:VinesSearchAC,initialize:function(c,b,a){this.adHtml="";var d=$(c);if(d){d.addEvent("adReceived",this.injectAd.bind(this))}this.parent(c,b,a)},injectAd:function(a,b){this.adHtml=new Element("div",{"class":"js-search-ad",html:'<img src="'+a+'" />'});this.adUrl=b},update:function(a){this.parent(a);if(a.length>2&&this.adHtml){this.addHtml.inject(this.choices.getChildren(":nth-child(2)"),"after")}},choiceSelect:function(b){var a=b.getChildren();if(a.length==1&&a[0].hasClass("js-search-ad")){window.open(this.adUrl,"_blank")}else{this.parent(b)}}});VinesSearchAC.WithSubMenus=new Class({Extends:VinesSearchAC,initialize:function(c,b,a){this.sub_menus={};this.parent(c,b,a)},hideChoices:function(a){if(!this.choices){return}if(this.selected&&this.selected.getElement("input")){this.sub_menus[this.selected.getElement("input").value].hideChoices(a)}this.parent(a)},onCommand:function(b){if(!b&&this.focussed){return this.prefetch()}if(b&&b.key&&!b.shift){if(!this.selected){return this.parent(b)}var a=this.sub_menus[this.selected.getElement("input").value];if(!a){return this.parent(b)}switch(b.key){case"up":case"down":if(a.selected){a.onCommand(b)}else{this.parent(b)}break;case"left":a.hideChoices();a.selected=a.selectedValue=null;break;case"right":a.showChoices();a.choiceOver(a.choices.getFirst());break;default:if(a.selected){a.onCommand(b)}else{this.parent(b)}break}}},choiceOver:function(b,f){if(!b||b==this.selected||!b.retrieve("token")){return}if(this.selected&&this.selected.getElement("input")){this.sub_menus[this.selected.getElement("input").value].hideChoices()}this.parent(b,f);var e=b.retrieve("token");var d=e.content_type_id+"-"+e.object_id;if(this.sub_menus[d]){this.sub_menus[d].showChoices()}else{var c=this.element.id+"-"+d;var a=new Element("input",{type:"text",value:d,id:c,styles:{display:"none"}});a.inject(b);a.addEvent(this.options.callBackEvent,function(h,j){this.element.fireEvent(this.options.callBackEvent,h)}.bind(this));var g=new VinesSearchAC.SubMenu(c,this.options.url2,$merge(this.options,{parentElement:b,selectFirst:false}));g.observer.fireEvent("onFired");this.sub_menus[d]=g}},destroy:function(){(new Hash(this.sub_menus)).each(function(b,a){this.sub_menus[a].destroy()}.bind(this));this.parent()},setSelection:function(){return false}});VinesSearchAC.SubMenu=new Class({Extends:VinesSearchAC,showChoices:function(){if(!this.options.parentElement.hasClass("autocompleter-selected")){return}this.parent();var a=this.options.parentElement.getCoordinates();this.choices.setStyles({top:a.top,left:a.left+100})}});VinesACWidgets={};function StartVinesAutoCompleteWidget(b,a){if($(b.id).hasClass("ready")&&VinesACWidgets[b.id]){return}VinesACWidgets[b.id]=new VinesAutoCompleteWidget(b,a)}VinesAutoCompleteWidget=new Class({options:{ct_ids:"",content_objects:[],content_type_id:null,object_id:null,disable_delete:false,disable_add:false,name:null,search_input:null,input_name:"assoc",input_values_with_ct:true,single_value:false},initialize:function(e,c){this.setOptions(c);var b=(Math.round((Math.random()*9)+1));var f=new Element("input",{styles:{border:"none","padding-top":"2px",background:"none"},id:b});f.inject(e);this.options.search_input=f;this.create({content_type_id:this.options.content_type_id,object_id:this.options.object_id,name:this.options.name,disable_delete:this.options.disable_delete});var g=this.options.content_objects;g.each(function(j,h){this.create(j)}.bind(this));if(this.options.disable_add){f.setProperty("disabled","true")}else{e.addEvent("click",function(){this.focus()}.bind(f));var a="Fire"+f.id;var d=new VinesSearchAC(f.id,"/autosearch/?ct_ids="+this.options.ct_ids,{callBackEvent:a,onSelection:function(){f.value=""}});$(f).addEvent(a,function(h,j){h.disable_delete=false;this.create(h,j)}.bind(this))}$(f).addEvent((Browser.Engine.trident||Browser.Engine.webkit)?"keydown":"keypress",this.onCommand.bindWithEvent(this));e.addClass("ready")},onCommand:function(c,a){if(c.key&&!c.shift){switch(c.key){case"backspace":search_input=this.options.search_input;if(search_input.value==""){var b=search_input.getPrevious();if(b&&!b.hasClass("disable_delete")){this.removeNode(b)}}}}},create:function(m,f){if(m.content_type_id==null||m.object_id==null||m.name==null){return}var k=m.object_id;var d=m.content_type_id;var b=m.name;var c=m.disable_delete;var l=d+"-"+k;if(this.options.content_objects.contains(l)&&$("text-complete-object"+l)){$("text-complete-object"+l).effect("background-color",{duration:600,transition:Fx.Transitions.linear}).start("#FFFF33","#FFFFff").chain(function(){$("text-complete-object"+l).setStyle("background-color","transparent")});return false}this.options.content_objects.extend([l]);var j=new Element("span",{id:"text-complete-object"+l,html:b,"class":"text-complete-object"});j.injectBefore(this.options.search_input).setProperty("content_type_id",d).setProperty("object_id",k);if(c){j.addClass("disable_delete")}else{var h=new Element("a",{html:" (x) ","class":"negative"});h.addEvent("click",function(){this.removeNode(h.parentNode)}.bind(this));h.inject(j)}var g=new Element("input");g.type="hidden";if(this.options.input_values_with_ct){g.value=d+"-"+k}else{g.value=k}g.name=this.options.input_name;g.inject(j);if(this.options.single_value){this.options.search_input.addClass("dn");this.options.search_input.setProperty("disabled","true")}},removeNode:function(a){var c=a.getProperty("content_type_id");var b=a.getProperty("object_id");a.remove();this.removeContentObjectElement(c+"-"+b);if(this.options.single_value&&(this.options.content_objects.length==0)){this.options.search_input.removeProperty("disabled");this.options.search_input.removeClass("dn")}},removeContentObjectElement:function(a){if(!this.options.content_objects.contains(a)){return false}for(i=0;i<this.options.content_objects.length;i++){if(this.options.content_objects[i]==a){this.options.content_objects.splice(i,1);return}}}});VinesAutoCompleteWidget.implement(new Events);VinesAutoCompleteWidget.implement(new Options);
