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