define(["cilantro/define/criteria"],function(a){function h(a){var b={};if(a.store===null||$.isEmptyObject(a.store))return;$.each(a.conditions,function(){b[this.concept_id]=this}),a.store.hasOwnProperty("concept_id")?App.hub.publish("UpdateQueryEvent",a.store,a.conditions[0]):$.each(a.store.children,function(a,c){App.hub.publish("UpdateQueryEvent",c,b[c.concept_id])}),c.children().last().click()}var b={},c=$("#condition-list"),d=$("#clear-conditions"),e=App.endpoints.session.scope,f=$("#no-conditions"),g=$("#get-report");return g.click(function(){window.location=App.endpoints.report}),d.click(function(){for(var a in b)b.hasOwnProperty(a)&&App.hub.publish("CriteriaRemovedEvent",b[a])}),App.hub.subscribe("UpdateQueryEvent",function(d,h){var i=d.concept_id,j;$.isEmptyObject(b)&&(f.hide(),g.fadeIn()),g.attr("disabled",!0);if(!h){var k={},l=b.hasOwnProperty(i)?"replace":"add";k[l]=d,$.patchJSON(e,JSON.stringify(k),function(f){g.removeAttr("disabled");var h=$.isEmptyObject(b);l==="replace"?(j=a.Criteria(d,e,f),b[i].replaceWith(j),j.fadeTo(300,.5,function(){j.fadeTo("fast",1)})):(j=a.Criteria(d,e,f),c.append(j),App.hub.publish("ConceptAddedEvent",i)),b[i]=j,j.addClass("selected"),j.siblings().removeClass("selected"),h&&$(c.children()[0]).find(".field-anchor").click()})}else j=a.Criteria(d,e,h),c.append(j),App.hub.publish("ConceptAddedEvent",i),b[i]=j,g.removeAttr("disabled");App.hub.publish("concept/request",i)}),App.hub.subscribe("CriteriaRemovedEvent",function(a,c){var d=a.data("constraint");b[d.concept_id].remove(),delete b[d.concept_id],c||(g.attr("disabled",!0),$.patchJSON(e,JSON.stringify({remove:d}),function(){g.removeAttr("disabled")})),App.hub.publish("ConceptDeletedEvent",d.concept_id),$.isEmptyObject(b)&&(f.fadeIn(),g.hide())}),App.hub.subscribe("concept/active",function(a){b[a.id]&&b[a.id].siblings().removeClass("selected"),b[a.id]&&b[a.id].addClass("selected")}),$.getJSON(e,h),App.hub.subscribe("report/revert",function(){for(var a in b)b.hasOwnProperty(a)&&App.hub.publish("CriteriaRemovedEvent",b[a],!0);$.getJSON(e,h)}),{retrieveCriteriaDS:function(a){var b=null;return a&&$.each(c.children(),function(c,d){if(!$(d).data("constraint"))return;$(d).data("constraint").concept_id==a&&(b=$(d).data("constraint"))}),b}}})