// (C) 2007-2010 Qualtrics, Inc.

window.Q_LogicEditorSchema=Class.create();Q_LogicEditorSchema.prototype={elements:null,initialize:function(opt_schema)
{this.elements=[];if(opt_schema)
{for(key in opt_schema)
{this.addElement(opt_schema[key]);}}},addElement:function(schemaElement)
{this.elements.push(schemaElement);},getElementById:function(id)
{for(var i=0,len=this.elements.length;i<len;++i)
{if(this.elements[i].id==id)
{return this.elements[i];}}}}
Qualtrics.schemaElementLibrary={Survey:{id:'Survey',description:getMessage('SiteWide','Survey'),fields:[{type:'select',fieldName:'SurveyID',labelKey:'Description',prompt:'Select Survey...',truncate:20,value:'$logicEditorFunction.getAjaxData(GetSurveyList)'}]},Question:{id:'Question',description:getMessage('SiteWide','Question'),fields:[{type:'select',fieldName:'QuestionID',labelKey:'Description',prompt:getMessage('SelectQuestion')+'...',truncate:20,value:'$logicEditorFunction.getAjaxData(GetQuestionList)'},{type:'select',fieldName:'ChoiceLocator',depends:'$field.QuestionID',valueKey:'Locator',labelKey:'Description',prompt:getMessage('EditSection','SelectChoice'),truncate:30,value:{$ajax:{action:'GetPipingOptionsByQuestionId',params:{QID:'$field.QuestionID',group:'QuestionLogic'}}}},{type:'text',depends:'$field.ChoiceLocator',value:getMessage('Is')},{type:'select',fieldName:'Operator',depends:{$field:'ChoiceLocator'},value:'$expressionFunction.getOperatorListTypeFromChoiceLocator'},{type:'hidden',fieldName:'QuestionIDFromLocator',value:'$function.Q_GlobalLogic.getQuestionIdFromLocator($field.ChoiceLocator)',optional:true},{type:'hidden',fieldName:'LeftOperand',value:'$function.Q_GlobalLogic.getQuestionLeftOperand($field.QuestionIDFromLocator, $field.ChoiceLocator, $field.Operator)'},{type:'textbox',fieldName:'RightOperand',depends:{$ifAny:['$field.Operator == "GreaterThan"','$field.Operator == "GreaterThanOrEqual"','$field.Operator == "LessThan"','$field.Operator == "LessThanOrEqual"','$field.Operator == "EqualTo"','$field.Operator == "NotEqualTo"','$field.Operator == "Contains"','$field.Operator == "DoesNotContain"','$field.Operator == "MatchesRegex"']}}]},EmbeddedField:{id:'EmbeddedField',description:getMessage('SiteWide','EmbeddedData'),fields:[{type:'textbox',fieldName:'LeftOperand'},{type:'text',value:getMessage('Is')},{type:'select',fieldName:'Operator',value:'$expressionFunction.getOperatorList(Numeric)'},{type:'textbox',fieldName:'RightOperand',depends:{$ifAny:['$field.Operator == "GreaterThan"','$field.Operator == "GreaterThanOrEqual"','$field.Operator == "LessThan"','$field.Operator == "LessThanOrEqual"','$field.Operator == "EqualTo"','$field.Operator == "NotEqualTo"','$field.Operator == "Contains"','$field.Operator == "DoesNotContain"','$field.Operator == "MatchesRegex"']}}]},EmbeddedFieldWithDropDowns:{id:'EmbeddedField',description:getMessage('SiteWide','EmbeddedData'),fields:[{type:'combobox',fieldName:'LeftOperand',prompt:'Field Name',action:'GetEmbeddedFieldNames',params:{PID:'$logicVariable.panelId'}},{type:'text',value:getMessage('Is')},{type:'select',fieldName:'Operator',value:'$expressionFunction.getOperatorList(Numeric)'},{type:'combobox',fieldName:'RightOperand',action:'GetEmbeddedFieldValues',prompt:'Value',params:{PID:'$logicVariable.panelId',Field:'$field.LeftOperand'},depends:{$ifAny:['$field.Operator == "GreaterThan"','$field.Operator == "GreaterThanOrEqual"','$field.Operator == "LessThan"','$field.Operator == "LessThanOrEqual"','$field.Operator == "EqualTo"','$field.Operator == "NotEqualTo"','$field.Operator == "Contains"','$field.Operator == "DoesNotContain"','$field.Operator == "MatchesRegex"']}}]},Quota:{id:'Quota',description:getMessage('Piping','Quota'),fields:[{type:'select',fieldName:'QuotaID',labelKey:'Name',truncate:30,value:{$ajax:{action:'GetQuotaList'}}},{type:'select',fieldName:'Operator',value:'$expressionFunction.getOperatorList(Quota)'},{type:'textbox',fieldName:'RightOperand',depends:{$ifAll:['$field.Operator != "QuotaMet"','$field.Operator != "QuotaNotMet"']}},{type:'hidden',fieldName:'LeftOperand',value:'$function.Q_GlobalLogic.getLocatorFromData($field.QuotaID, $field.LogicType, $field.Operator)'},{type:'hidden',fieldName:'QuotaName',value:'$logicEditorFunction.getQuotaNameById($field.QuotaID)'}]},Date:{id:'Date',description:getMessage('SiteWide','Date')},RecipientHistory:{id:'RecipientHistory',description:getMessage('Piping','RecipientHistory'),fields:[{type:'select',fieldName:'LeftOperand',value:{'m://LastSurveyResponse/Date':getMessage('Piping','LastSurveyResponse'),'m://LastSurveyInvitation/Date':getMessage('Piping','LastEmailInvitation')}},{type:'text',value:'was'},{type:'select',fieldName:'Operator',value:'$expressionFunction.getOperatorList(Date)'},{type:'date',fieldName:'RightOperand'}]},RecipientMembership:{id:'RecipientMembership',description:getMessage('Piping','RecipientMembership'),fields:[{type:'select',fieldName:'Operator',value:{'NotArrayContains':getMessage('Piping','NotAMember'),'ArrayContains':getMessage('Piping','Member')}},{type:'text',value:'of sample'},{type:'select',fieldName:'LeftOperand',prompt:'Select Sample...',persistent:true,value:{$ajax:{action:'GetSampleLocators',params:{PID:'$logicVariable.panelId'}}}},{type:'hidden',fieldName:'RightOperand',value:'m://RecipientID'}]},Panel:{id:'Panel',description:getMessage('SiteWide','Panel'),fields:[{type:'select',fieldName:'LibraryID',prompt:'Select Library...',value:{$ajax:{action:'GetLibraries'}}},{type:'select',fieldName:'PanelID',prompt:'Select Panel...',depends:'$field.LibraryID',value:{$ajax:{action:'GetPanels',params:{LID:'$field.LibraryID'}}}}]}}
window.Q_LogicEditor=Class.create();Q_LogicEditor.registry={};Q_LogicEditor.getInstance=function(id)
{if(!id)
{for(id in Q_LogicEditor.registry)
{return Q_LogicEditor.registry[id];}}
return Q_LogicEditor.registry[id];}
Q_LogicEditor.getExpressionById=function(id)
{var foundExp=null;for(logicEditorId in Q_LogicEditor.registry)
{foundExp=Q_LogicEditor.registry[logicEditorId].getExpressionById(id);}
return foundExp;}
Q_LogicEditor.prototype={id:null,logicId:null,name:null,element:null,criteria:null,questionList:null,refreshControlsCallback:null,valid:false,parentObj:null,attention:null,saved:null,editMode:true,alwaysShowExpressionSetHeader:true,allowConjunctions:true,minExpressions:null,maxExpressions:null,availableTypes:{Question:true,EmbeddedField:true,Quota:false,Date:false},initialize:function(parentObj,refreshControlsCallback,opt_booleanExpression,options)
{this.initialRender=true;if(!options)options={};if(options.editLink===undefined)
{options.editLink=true;}
this.options=options;this.parentObj=parentObj;this.id=QualtricsCPTools.createNewId('LE');this.refreshControlsCallback=refreshControlsCallback;Q_LogicEditor.registry[this.id]=this;if(options.schema)
{this.schema=options.schema;}
else
{this.schema=new Q_LogicEditorSchema();this.schema.addElement(Qualtrics.schemaElementLibrary.Question);this.schema.addElement(Qualtrics.schemaElementLibrary.EmbeddedField);}
this.criteria=new Q_BooleanExpression(this);if(opt_booleanExpression)
{if(typeof opt_booleanExpression=='string')
{opt_booleanExpression=opt_booleanExpression.evalJSON();}
this.generate(opt_booleanExpression);}},generate:function(json)
{if(json)
{var booleanExpressionData=null;if(json['type']&&json['type']=='BooleanExpression')
{this.criteria=json;this.criteria.parentObj=this;this.saved=true;return;}
else if(json['Type']&&json['Type']=='BooleanExpression')
{booleanExpressionData=json;}
else
{for(i in json)
{if(json[i]&&typeof json[i]=='object')
{if(json[i]['Type']&&json[i]['Type']=='BooleanExpression')
{booleanExpressionData=json[i];}}}
if(json['Name'])
{this.name=json['Name'];}
if(json['ID'])
{this.logicId=json['ID'];}}
if(booleanExpressionData)
{this.saved=true;this.criteria.generate(booleanExpressionData);}}},getLogicEditor:function()
{return this;},getExpressionCount:function()
{return this.getAllExpressions().length;},build:function()
{this.element=QBuilder('div',{id:'LogicEditor',className:'LogicEditor'},[this.criteria.buildEditor()]);return this.element;},getDescription:function()
{var desc=QBuilder('div');var expressions=this.getAllExpressions();for(var i=0,len=expressions.length;i<len;++i)
{desc.appendChild(QBuilder('div',null,[expressions[i].buildDescription(this.options.editLink)]));}
return desc;},getData:function()
{var data={};var criteria=[];for(var i=0,len=this.criteria.elements.length;i<len;++i)
{var setObj=this.criteria.elements[i];var setData={};setData['Type']=setObj.type;for(var seti=0,setLen=this.criteria.elements[i].elements.length;seti<setLen;seti++)
{var expObj=this.criteria.elements[i].elements[seti];setData[seti]=expObj.getData();}
criteria.push(setData);}
if(criteria.length)
{for(var i=0,len=criteria.length;i<len;++i)
{data[i]=criteria[i];}}
data['Type']='BooleanExpression';if(this.name)
{data['Name']=this.name;}
if(this.logicId)
{data['LogicID']=this.logicId;}
return data;},edit:function()
{this.editMode=true;this.refresh();},triggerRefresh:function()
{if(this.refreshTimer)
{clearTimeout(this.refreshTimer);}
this.refreshTimer=this.refresh.bind(this).delay();},refresh:function()
{var expressions=this.getAllExpressions()
for(var i=0,len=expressions.length;i<len;++i)
{expressions[i].cleanup();}
if(this.element)
{deleteChildren(this.element);}
if(this.element&&this.criteria)
{$(this.element).appendChild(this.criteria.buildEditor());this.attentionHighlighter();}
this.validate();this.refreshControls();},refreshControls:function()
{if(this.refreshControlsCallback&&this.parentObj[this.refreshControlsCallback])
{this.parentObj[this.refreshControlsCallback](this);}},getAdvancedMenuButton:function()
{return QMenu.buildMenuButton(getMessage('EditSection','AddAdvancedLogic'),'Q_LogicEditor.getInstance("'+this.id+'").buildAdvancedMenu()');},buildAdvancedMenu:function()
{return QBuilder('ul',{},[QBuilder('li',null,[QBuilder('a',{href:'javascript:void(0)',clickcallback:'Q_LogicEditor.addExpressionSet',p1:'AndIf',instanceid:this.id},[QBuilder('span',{className:'icon'}),getMessage('EditSection','AddANDIFGroup')])]),QBuilder('li',null,[QBuilder('a',{href:'javascript:void(0)',clickcallback:'Q_LogicEditor.addExpressionSet',p1:'ElseIf',instanceid:this.id},[QBuilder('span',{className:'icon'}),getMessage('EditSection','AddORIFGroup')])])]);},updateValues:function()
{var expressions=this.getAllExpressions();for(var i=0,len=expressions.length;i<len;++i)
{expressions[i].updateValues();}},validate:function()
{var valid=true;var uniqueFields={};if(this.criteria&&this.criteria.elements.length)
{for(var i=0,len=this.criteria.elements.length;i<len;++i)
{var expressionSet=this.criteria.elements[i];if(expressionSet.elements.length)
{for(var seti=0,setLen=expressionSet.elements.length;seti<setLen;seti++)
{var expression=expressionSet.elements[seti];if(seti==0)
{if(expression.data['Conjunction'])
{delete(expression.data['Conjunction']);}}
if(!expression.validate())
{this.invalidReason=expression.invalidReason;valid=false;}
if(expression.cachedSchema&&expression.cachedSchema.fields)
{for(var i=0,len=expression.cachedSchema.fields.length;i<len;++i)
{var f=expression.cachedSchema.fields[i];if(f.validation)
{if(f.validation.unique)
{var fieldVal=expression.data[f.fieldName];if(!uniqueFields[f.fieldName])
{uniqueFields[f.fieldName]={};}
if(uniqueFields[f.fieldName][fieldVal])
{expression.invalidReason=f.fieldName;this.invalidReason=expression.invalidReason;expression.valid=false;valid=false;}
uniqueFields[f.fieldName][fieldVal]=1;}}}}
if(expression.node){var wasValid=false;if(expression.node.valid)
{wasValid=true;}
if(wasValid!=expression.valid)
{if(expression.valid)
{$(expression.node).addClassName('Valid');expression.node.valid=true;}
else
{$(expression.node).removeClassName('Valid');expression.node.valid=false}}}}}
else
{valid=false;}}}
else
{valid=false;}
this.valid=valid;this.attentionHighlighter(false);this.autoAddExpression();return valid;},autoAddExpression:function()
{if(this.autoAddExpressions&&this.valid)
{this.addExpression();}},getAllExpressions:function()
{var expressions=[];if(this.criteria&&this.criteria.elements)
{for(var i=0,len=this.criteria.elements.length;i<len;++i)
{for(var seti=0,setLen=this.criteria.elements[i].elements.length;seti<setLen;seti++)
{expressions.push(this.criteria.elements[i].elements[seti]);}}}
return expressions;},attentionHighlighter:function(autoFocus)
{var expressions=this.getAllExpressions();for(var i=0,len=expressions.length;i<len;++i)
{var foundAttention=expressions[i].attentionHighlighter(autoFocus);if(foundAttention)
break;}},removeExpression:function(expressionId)
{var expressionObj=this.getExpressionById(expressionId);var len=this.getAllExpressions().length;if(this.minExpressions&&len<=this.minExpressions)
{return;}
expressionObj.destroy();len--;this.validate();this.saved=false;this.refresh();if(this.onExpressionRemove)
this.onExpressionRemove();if(this.onChange)
this.onChange();if(len==0&&this.onEmpty)
this.onEmpty();},addExpressionSet:function(type)
{if(type)
{var newSet=new Q_ExpressionSet(type,this.criteria);this.criteria.elements.push(newSet);this.saved=false;this.refresh();return newSet;}},addExpression:function(opt_aboveId,opt_expressionObj,opt_event)
{var len=this.getAllExpressions().length;if(this.maxExpressions&&len>=this.maxExpressions)
{return;}
if(opt_event&&(opt_event.shiftKey||opt_event.metaKey))
{this.addExpressionSet('AndIf');return}
this.saved=false;var expressionSetObj;var siblingExpressionObj;if(opt_aboveId&&typeof opt_aboveId=='string'){siblingExpressionObj=this.getExpressionById(opt_aboveId);expressionSetObj=siblingExpressionObj.parentObj;}
else
{var expressionSetObj=this.criteria.elements.last();}
if(!expressionSetObj)
{this.addExpressionSet('If');}
else
{if(opt_expressionObj)
{var newExpression=opt_expressionObj;newExpression.parentObj=expressionSetObj;}
else
{var newExpression=new Q_Expression(expressionSetObj);}
if(!siblingExpressionObj||siblingExpressionObj.getPosition()==expressionSetObj.elements.length-1)
{expressionSetObj.elements.push(newExpression)}
else
{expressionSetObj.elements.splice(siblingExpressionObj.getPosition()+1,0,newExpression);}}
this.refresh();if(this.onExpressionAdd)
this.onExpressionAdd();if(this.onChange)
this.onChange();},getQuestionList:function()
{return this.getAjaxData('GetQuestionList');},getQuotaList:function()
{var quota=this.getAjaxData('GetQuotaList');return quota;},getQuotaNameById:function(quotaId)
{var quotaList=this.getQuotaList();if(quotaList&&quotaList[quotaId])
{return quotaList[quotaId]['Name'];}},setLogicVariable:function(name,val)
{this[name]=val;},getAjaxData:function(action,opt_parameters,ajaxDef)
{ajaxDef=ajaxDef||{};if(!this.ajaxDataCache)
{this.ajaxDataCache={};}
var uniqueId=action;if(opt_parameters)
{uniqueId=uniqueId+'_'+$H(opt_parameters).keys().join('|')+'_'+$H(opt_parameters).values().join('|');}
if(!this.ajaxDataCount)
{this.ajaxDataCount=0;}
if(!this.ajaxDataCache[uniqueId])
{var that=this;if(Qualtrics.AjaxUpdateQueue.isWaitingOn(uniqueId))
{Qualtrics.AjaxUpdateQueue.push({id:uniqueId,onComplete:function()
{if(that.tryOnloadEvent)
that.tryOnLoadEvent();},onSuccess:function(transport)
{if(!transport.responseText)
{that.ajaxDataCache[uniqueId]={};that.triggerRefresh();return;}
try{that.ajaxDataCache[uniqueId]=transport.responseText.evalJSON();}catch(e)
{console.error(e)}
that.refresh();if(ajaxDef.onSuccess)
ajaxDef.onSuccess()},onFailure:function(transport)
{that.ajaxDataCache[uniqueId]='#failed#';}});return false;}
else
{Qualtrics.AjaxUpdateQueue.waitOn(uniqueId);}
this.ajaxDataCount++;this.ajaxDataCache[uniqueId]='#loading#'
new Ajax.CachedRequest('Ajax.php?action='+action,{parameters:opt_parameters,onComplete:function()
{try
{that.ajaxDataCount--;if(that.tryOnloadEvent)
that.tryOnLoadEvent();Qualtrics.AjaxUpdateQueue.complete(uniqueId,'onComplete');}
catch(e)
{console.error(e);}},onSuccess:function(transport){if(!transport.responseText)
{that.ajaxDataCache[uniqueId]={};that.triggerRefresh();Qualtrics.AjaxUpdateQueue.complete(uniqueId,'onSuccess',transport);return;}
try{that.ajaxDataCache[uniqueId]=transport.responseText.evalJSON();}catch(e)
{console.error(e)}
that.refresh();if(ajaxDef.onSuccess)
ajaxDef.onSuccess()
Qualtrics.AjaxUpdateQueue.complete(uniqueId,'onSuccess',transport);},onFailure:function(transport)
{console.error('ajax fail');that.ajaxDataCache[uniqueId]='#failed#';Qualtrics.AjaxUpdateQueue.complete(uniqueId,'onFailure',transport);}});return false;}
if(this.ajaxDataCache[uniqueId]=='#loading#')
{return false;}
if(this.tryOnloadEvent)
this.tryOnLoadEvent();return this.ajaxDataCache[uniqueId];},getExpressionById:function(id)
{return this.criteria.getExpressionById(id);},tryOnLoadEvent:function()
{if(this.onLoadTimer)
{window.clearTimeout(this.onLoadTimer)}
this.onLoadTimer=this.tryOnLoadEventAction.bind(this).delay(1.1);},tryOnLoadEventAction:function()
{if(this.ajaxDataCount<1)
{if(this.onLoad)
{this.onLoad();}}}}
Qualtrics.AjaxUpdateQueue={waitingOn:{},queue:{},waitOn:function(id)
{this.waitingOn[id]=true;},isWaitingOn:function(id)
{return this.waitingOn[id];},push:function(job)
{if(!this.queue[job.id])
{this.queue[job.id]={onComplete:[],onSuccess:[],onFailure:[]};}
if(job.onComplete)
this.queue[job.id].onComplete.push(job.onComplete);if(job.onSuccess)
this.queue[job.id].onSuccess.push(job.onSuccess);if(job.onFailure)
this.queue[job.id].onFailure.push(job.onFailure);},complete:function(id,type,opt_transport)
{try
{this.waitingOn[id]=false;if(this.queue[id])
{var jobs=this.queue[id][type];var job;while(job=jobs.pop())
{job(opt_transport);}}}
catch(e)
{console.error('Error completing ajax queue: '+e)}}};window.Q_BooleanExpression=Class.create();Q_BooleanExpression.prototype={type:'BooleanExpression',elements:null,parentObj:null,initialize:function(parentObj,opt_expressionSets)
{this.parentObj=parentObj;if(opt_expressionSets&&opt_expressionSets.length)
{this.elements=opt_expressionSets;}
else
{this.elements=[new Q_ExpressionSet(getMessage('If'),this)];}
for(var i=0,len=this.elements.length;i<len;++i)
{this.elements[i].parentObj=this;}},generate:function(json)
{this.elements=[];for(i in json)
{if(!isNaN(i))
{if(json[i]===null){continue;}
var type=json[i]['Type'];var expressionSetObj=new Q_ExpressionSet(type,this);expressionSetObj.generate(json[i]);this.elements.push(expressionSetObj);}}},buildEditor:function()
{this.parentObj.rendering=true;var div=QBuilder('div',{className:'BooleanExpression EditMode_'+this.parentObj.editMode});for(var i=0,len=this.elements.length;i<len;++i)
{div.appendChild(this.elements[i].buildEditor());}
this.parentObj.rendering=false;return div;},getExpressionById:function(id)
{for(var i=0,len=this.elements.length;i<len;++i)
{var foundExpressionObj=this.elements[i].getExpressionById(id);if(foundExpressionObj)
{return foundExpressionObj;}}}}
window.Q_ExpressionSet=Class.create();Q_ExpressionSet.prototype={id:null,type:'If',elements:null,parentObj:null,initialize:function(type,parentObj,opt_expressions)
{this.type=type;this.parentObj=parentObj;if(opt_expressions&&opt_expressions.length)
{this.elements=opt_expressions;}
else
{this.elements=[new Q_Expression(this)];}
this.id=this.id=QualtricsCPTools.createNewId('QEXS');for(var i=0,len=this.elements.length;i<len;++i)
{this.elements[i].parentObj=this;}},generate:function(json)
{this.type=json['Type'];this.elements.length=0;for(i in json)
{if(!isNaN(i))
{var expressionObj=new Q_Expression(this);expressionObj.generate(json[i]);this.elements.push(expressionObj);}}},buildEditor:function()
{var div=QBuilder('div',{className:'ExpressionSet'});var expressionSetCount=this.parentObj.elements.length;if(this.parentObj.parentObj.allowConjunctions&&(expressionSetCount>1||this.parentObj.parentObj.alwaysShowExpressionSetHeader))
{div.appendChild(QBuilder('h3',{className:'type_'+this.type},getMessage(this.type)));}
for(var i=0,len=this.elements.length;i<len;++i)
{div.appendChild(this.elements[i].build());}
return div;},getExpressionById:function(id)
{for(var i=0,len=this.elements.length;i<len;++i)
{if(this.elements[i].id==id)
{return this.elements[i];}}},getPosition:function()
{if(this.parentObj)
{for(var i=0,len=this.parentObj.elements.length;i<len;++i)
{if(this.parentObj.elements[i].id==this.id)
{return i;}}}},destroy:function()
{this.parentObj.elements.splice(this.getPosition(),1);this.parentObj=null;}}
window.Q_Expression=Class.create();Q_Expression.getInstance=function(id)
{return Q_LogicEditor.getExpressionById(id);}
Q_Expression.registry={};Q_Expression.getInstance=QualtricsCPTools.getInstanceHelper(Q_Expression.registry,'id');Q_Expression.prototype={id:null,parentObj:null,type:'Expression',conjunction:null,choiceLocator:null,description:null,LogicType:null,RightOperand:null,attention:null,ajaxError:null,data:null,initialize:function(parentObj,opt_schema)
{if(opt_schema)
this.schema=opt_schema;this.data={};this.parentObj=parentObj;this.data['LogicType']='Question';var logicEditor=this.getLogicEditor();if(logicEditor&&logicEditor.schema)
{var schemaElements=logicEditor.schema.elements;var nextSchemaIndex=0;if(logicEditor.getAllExpressions)
{var expressionCount=logicEditor.getAllExpressions().length;if(logicEditor.cycle)
{nextSchemaIndex=expressionCount%schemaElements.length;}}
this.data['LogicType']=schemaElements[nextSchemaIndex].id;}
this.id=QualtricsCPTools.createNewId('QEX');Q_Expression.registry[this.id]=this;},generate:function(json)
{var reMap={Question:'QuestionID',Conjuction:'Conjunction'}
for(key in json)
{if(reMap[key])
{this.data[reMap[key]]=json[key];}
else
{this.data[key]=json[key];}}},getCurrentFields:function()
{var expData={};var schema=this.getSchemaElement();for(var i=0,len=schema.fields.length;i<len;++i)
{if(schema.fields[i].depends&&!this.resolveDependency(schema.fields[i].depends))
{continue;}
var fieldName=schema.fields[i].fieldName;if(fieldName)
{expData[fieldName]=this.data[fieldName];}}
return expData},getData:function()
{var expData={};expData['Type']='Expression';expData['LogicType']=this.data['LogicType'];expData['Description']=this.getDescription();if(this.parentObj)
{var firstExpression=this.parentObj.elements[0];if(firstExpression===this&&this.data['Conjunction'])
{delete(this.data['Conjunction']);}}
for(fieldName in this.getCurrentFields())
{expData[fieldName]=this.data[fieldName];}
if(this.data.Conjunction)
{expData['Conjuction']=this.data.Conjunction;}
return expData;},setSchema:function(schema)
{this.schema=schema;},getLogicEditor:function()
{if(this.parentObj)
return this.parentObj.parentObj.parentObj;else
{var genericLEObject={schema:this.schema,editMode:true,getAjaxData:Q_LogicEditor.prototype.getAjaxData.bind(this),validate:this.validate.bind(this),refreshControls:Q_LogicEditor.prototype.refreshControls.bind(this),attentionHighlighter:this.attentionHighlighter.bind(this),getExpressionCount:function(){return 1;}};return genericLEObject;}},getPosition:Q_ExpressionSet.prototype.getPosition,ajaxData:Q_LogicEditor.prototype.ajaxData,triggerRefresh:function()
{if(this.refreshTimer)
{clearTimeout(this.refreshTimer);}
this.refreshTimer=this.refresh.bind(this).delay(0.1);},refresh:function()
{var logicEditor=this.getLogicEditor();if(logicEditor.rendering){return;}
try{this.cleanup();deleteChildren(this.node);this.node.appendChild(this.buildEditor());logicEditor.attentionHighlighter(true);}
catch(e)
{console.error(e);}
if(this.onRefresh)
{this.onRefresh();}},build:function()
{var classes='ExpressionContainer';var pos=this.getPosition();if(pos==0)
{classes+=' First';}
if(this.parentObj&&this.parentObj.elements&&pos==this.parentObj.elements.length-1)
{classes+=' Last';}
this.node=QBuilder('div',{className:classes});this.node.appendChild(this.buildEditor());return this.node;},attentionHighlighterAction:function(autoFocus)
{if(autoFocus==undefined)autoFocus=true;var newAttention=null;if(!this.valid)
{var r=this.invalidReason;var id=this.id;if($(r+'_'+id))
{newAttention=$(r+'_'+id);}}
if(newAttention)
{if(this.initialRender&&newAttention.nodeName=='INPUT')
{return;}
if(newAttention.hasAttribute('comboboxinput'))
{var tmp=$(newAttention.getAttribute('comboboxinput'))
if(tmp)
{newAttention=tmp;}}
this.attention=newAttention;$(this.attention).addClassName('Attention');if(this.attention.nodeName=='INPUT')
{if(autoFocus)
{if(this.attention.getAttribute('autoclear')&&this.attention.getAttribute('autoclear')==this.attention.value)
{}
$(this.attention).focus();}}}},attentionHighlighter:function(autoFocus)
{if(this.attention)
{$(this.attention).removeClassName('Attention');this.attention=null;}
if(!this.valid)
{var r=this.invalidReason;var id=this.id;if(r)
{if($(r+'_'+id))
{this.attentionHighlighterAction(autoFocus);}
else
{this.attentionHighlighterAction.bind(this,autoFocus).defer();}
return true;}}
return false;},buildEditor:function()
{var logicEditor=this.getLogicEditor();if(logicEditor.editMode)
{var conjunctionSelect='';if(logicEditor.allowConjunctions)
{conjunctionSelect=this.buildConjunction();}
var logicTypeSelect='';if(this.getSchemaElement().description)
{logicTypeSelect=QBuilder('select',{className:'SelectBox',exid:this.id,leid:logicEditor.id,name:'LogicType'});var schemaElements=logicEditor.schema.elements;for(var i=0,len=schemaElements.length;i<len;++i)
{logicTypeSelect.appendChild(QBuilder('option',{value:schemaElements[i].id},schemaElements[i].description));}
if(schemaElements.length==1)
{$(logicTypeSelect).hide();}
logicTypeSelect.onchange=this.valueChangeHandler;if(!this.data['LogicType'])
{this.data['LogicType']='Question';}
logicTypeSelect.value=this.data['LogicType'];}
var expressionDiv=QBuilder('span');var expressionOuterDiv=QBuilder('div',{className:'Selectors'},[conjunctionSelect,logicTypeSelect,expressionDiv]);expressionDiv.appendChild(this.buildExpressionFromSchema(this.data['LogicType']));expressionDiv.appendChild(QBuilder('div',{className:'clear'}));var buttonClass='';var expCount=logicEditor.getExpressionCount();var removeClass='RemoveExpression';var addClass='AddExpression';if(logicEditor.minExpressions!=undefined)
{if(logicEditor.minExpressions==expCount)
{buttonClass+=' first';removeClass+=' Disabled';}}
if(logicEditor.maxExpressions!=undefined)
{if(logicEditor.maxExpressions==expCount)
{buttonClass+=' last';addClass+=' Disabled';}}
var expressionContainer=QBuilder('div',{className:'Expression '+this.data['LogicType']},[expressionOuterDiv,QBuilder('div',{className:'Buttons'+buttonClass},[QBuilder('div',{className:removeClass,clickcallback:'Q_LogicEditor.removeExpression',p1:this.id,p2:'',p3:'$evt',instanceid:logicEditor.id}),QBuilder('div',{className:addClass,clickcallback:'Q_LogicEditor.addExpression',p1:this.id,p2:'',p3:'$evt',instanceid:logicEditor.id})])]);logicEditor.validate();logicEditor.refreshControls();return expressionContainer;}
else
{var orClass='';if(this.data['Conjunction']=='Or'){orClass=' OrIfExpression';}
var desc=QBuilder('div',{className:'Description'+orClass},[this.buildDescription(logicEditor.options.editLink)]);return desc;}},buildConjunction:function()
{var firstMsg=getMessage('If');var andMsg=getMessage('EditSection','AndIf');var orMsg=getMessage('EditSection','OrIf');if(this.getSchemaElement().conjunction)
{firstMsg=this.getSchemaElement().conjunction.first||fistMsg;andMsg=this.getSchemaElement().conjunction.and||andMsg;orMsg=this.getSchemaElement().conjunction.or||orMsg;}
var conjunctionSelect=QBuilder('span',null,[firstMsg]);if(this.getPosition()>0)
{conjunctionSelect=QBuilder('select',{className:'SelectBox',exid:this.id,leid:this.getLogicEditor().id,name:'Conjunction'},[QBuilder('option',{value:getMessage('Piping','And')},[andMsg]),QBuilder('option',{value:getMessage('Piping','Or')},[orMsg])]);if(this.data['Conjunction'])
{conjunctionSelect.value=this.data['Conjunction'];}
else
{this.data['Conjunction']=getMessage('Piping','And');}
conjunctionSelect.onchange=this.valueChangeHandler;}
return conjunctionSelect;},buildCustomConjunction:function()
{},buildExpressionFromSchema:function(logicType)
{var fields=this.getSchemaElement().fields;if(fields)
{var expressionDiv=document.createDocumentFragment();for(var i=0,len=fields.length;i<len;++i)
{var fieldNode=this.buildField(fields[i]);if(fieldNode&&fieldNode.nodeType)
{expressionDiv.appendChild(fieldNode);}
else
{if(fieldNode=='#loading#')
{expressionDiv.appendChild(this.buildLoading());break;}}}
return expressionDiv;}},updateValues:function()
{var fields=this.getSchemaElement().fields;if(fields)
{for(var i=0,len=fields.length;i<len;++i)
{var fieldDef=fields[i];if(fieldDef['type']=='hidden'&&typeof fieldDef.value!='undefined')
{this.data[fieldDef.fieldName]=this.evalSchemaExpressionString(fieldDef.value);}}}},evalSchemaExpression:function(obj,opt_forcedParams)
{for(key in obj)
{var val=obj[key];if(key=='$logicEditorFunction')
{val=this.preparseFunctionParameters(val);return QualtricsCPTools.executeDotSyntax(val,null,this.getLogicEditor(),opt_forcedParams);}
else if(key=='$logicVariable')
{return this.getLogicEditor()[val];}
else if(key=='$expressionFunction')
{val=this.preparseFunctionParameters(val);return QualtricsCPTools.executeDotSyntax(val,null,this,opt_forcedParams);}
else if(key=='$function')
{val=this.preparseFunctionParameters(val);return QualtricsCPTools.executeDotSyntax(val,null,null,opt_forcedParams);}
else if(key=='$field')
{return this.data[val];}
else if(key=='$ajax')
{return this.processAjaxExpression(val);}
else if(key=='$if'||key=='$ifAll')
{return this.processIf(val,false);}
else if(key=='$ifAny')
{return this.processIf(val,true);}}
return obj;},evalSchemaExpressionString:function(str,opt_wrapWithQuotes,opt_forcedParams)
{if(typeof str=='object')
{return this.evalSchemaExpression(str,opt_forcedParams);}
if(str.charAt(0)=='$')
{var firstDot=str.indexOf('.');var key=str.substr(0,firstDot);var val=str.substr(firstDot+1);var expressionPkg={};expressionPkg[key]=val;var evaled=this.evalSchemaExpression(expressionPkg,opt_forcedParams);if(evaled===expressionPkg)
{return str;}
if(opt_wrapWithQuotes)
return'"'+evaled+'"';return evaled;}
return str;},processAjaxExpression:function(pkg)
{var params={};for(key in pkg.params)
{params[key]=this.evalSchemaExpressionString(pkg.params[key]);}
return this.getLogicEditor().getAjaxData(pkg.action,params,pkg);},processIf:function(ifArray,returnTrueIfAny)
{var allAreTrue=true;for(var i=0,len=ifArray.length;i<len;++i)
{var exp=ifArray[i];if(exp)
{var processedExp=this.evalInternalStringExpressions(exp,' ',true);if(eval(processedExp))
{if(returnTrueIfAny)
{return true;}}
else
{allAreTrue=false;}}}
return allAreTrue;},preparseFunctionParameters:function(str)
{if(str.lastIndexOf(')')===str.length-1)
{var openIndex=str.lastIndexOf('(');if(openIndex!=-1)
{var paramsString=str.substring(openIndex+1,str.lastIndexOf(')'));paramsString=this.evalInternalStringExpressions(paramsString,',');str=str.substring(0,openIndex);str+='('+paramsString+')';}}
return str;},evalInternalStringExpressions:function(str,opt_delimiter,opt_wrapWithQuotes)
{var tokens=str.split(opt_delimiter||' ');for(var i=0,len=tokens.length;i<len;++i)
{tokens[i]=tokens[i].strip();tokens[i]=this.evalSchemaExpressionString(tokens[i],opt_wrapWithQuotes);}
return tokens.join(opt_delimiter||' ');},buildField:function(fieldDef)
{var node=null;if(fieldDef.depends&&!this.resolveDependency(fieldDef.depends))
{return false}
else
{if(fieldDef['type']=='select')
{node=this.buildSelectField(fieldDef);}
else if(fieldDef['type']=='suggest')
{node=this.buildSuggestField(fieldDef);}
else if(fieldDef['type']=='text')
{node=QBuilder('span',null,this.evalSchemaExpressionString(fieldDef.value));}
else if(fieldDef['type']=='textbox')
{var valueInput=QBuilder('input',{className:'TextBox',keyentercallback:'Event.stop($evt)',autocomplete:'off',id:fieldDef.fieldName+'_'+this.id,name:fieldDef.fieldName,exid:this.id,leid:this.getLogicEditor().id});if(fieldDef.prompt&&!this.data[fieldDef.fieldName])
{valueInput.setAttribute('autoclear',fieldDef.prompt);$(valueInput).addClassName('AutoClearMessage');valueInput.value=fieldDef.prompt;}
if(fieldDef.size)
{valueInput.setAttribute('size',fieldDef.size);$(valueInput).setStyle({width:fieldDef.size+'em'});}
if(this.data[fieldDef.fieldName]===undefined&&fieldDef.defaultValue)
{this.data[fieldDef.fieldName]=this.evalSchemaExpressionString(fieldDef.defaultValue);}
if(this.data[fieldDef.fieldName])
{valueInput.value=this.data[fieldDef.fieldName];}
this.addObserver(valueInput);node=valueInput;}
else if(fieldDef['type']=='combobox')
{node=this.buildComboBoxField(fieldDef);}
else if(fieldDef['type']=='checkbox')
{node=this.buildCheckBoxField(fieldDef);}
else if(fieldDef['type']=='hidden'&&typeof fieldDef.value!='undefined')
{this.data[fieldDef.fieldName]=this.evalSchemaExpressionString(fieldDef.value);}
else if(fieldDef['type']=='date')
{node=this.buildDateInput(fieldDef);}}
return node;},buildLoading:function()
{return QBuilder('span',{className:'Loading'},getMessage('SiteWide','Loading'));},buildDateInput:function(fieldDef)
{var frag=document.createDocumentFragment();var now=new Date();var nowString=now.getFullYear()+'-'+String(now.getMonth()+1).leftPad(2)+'-'+String(now.getDate()).leftPad(2);if(!this.data[fieldDef.fieldName])
this.data[fieldDef.fieldName]=nowString;var valueValue=this.data[fieldDef.fieldName];var valueInput=QBuilder('input',{className:'TextBox',id:fieldDef.fieldName+'_'+this.id,name:fieldDef.fieldName,value:valueValue,size:'10',maxlength:'10',autocomplete:'off',exid:this.id,leid:this.getLogicEditor().id});this.addObserver(valueInput);frag.appendChild(valueInput);frag.appendChild(QBuilder('img',{id:'buttonValueID_'+this.id,clickcallback:'qualtricsPopupCalendar',p1:'buttonValueID_'+this.id,p2:fieldDef.fieldName+'_'+this.id,p3:'-120',p4:'-100',src:'../WRQualtricsControlPanel/CPGraphics/Calendar.png'}));return frag;},buildComboBoxField:function(fieldDef)
{var action=fieldDef.action;var fieldName=fieldDef.fieldName;var prompt;if(fieldDef.prompt)
{prompt=fieldDef.prompt;}
var paramFunc=function(){var params={};for(key in fieldDef.params)
{params[key]=this.evalSchemaExpressionString(fieldDef.params[key]);}
return params;};var value=this.data[fieldDef.fieldName]||'';var that=this;var cb=new Qualtrics.ComboBox({autoComplete:true,className:'InlineComboBox',list:{type:'ajax',ajaxAction:action,ajaxParameters:paramFunc.bind(this)},hiddenInputId:fieldName+'_'+this.id,hiddenInputName:fieldName,defaultValue:value,prompt:prompt,onHiddenInputChange:function(el)
{that.valueChangeHandler(el,el.value)}});var comboBoxNode=cb.build();cb.input.setAttribute('exid',this.id);cb.input.setAttribute('leid',this.getLogicEditor().id);cb.hiddenInput.setAttribute('exid',this.id);cb.hiddenInput.setAttribute('leid',this.getLogicEditor().id);this.addObserver(cb.input);return comboBoxNode;},buildCheckBoxField:function(fieldDef)
{var fieldName=fieldDef.fieldName;var prompt=fieldDef.prompt;var value=(this.data[fieldDef.fieldName]?1:0);var checkbox=QBuilder('input',{type:'checkbox',id:fieldName+'_'+this.id,name:fieldName,leid:this.getLogicEditor().id,exid:this.id})
if(value)
{checkbox.checked=true;checkbox.defaultChecked=true;}
this.addObserver(checkbox);var label=QBuilder('label',{htmlFor:fieldName+'_'+this.id},prompt)
return QBuilder('div',{className:'InlineCheckBox'},[checkbox,label]);},modifyChoiceOption:function(val,desc)
{var locatorData=Q_GlobalLogic.getDataFromLocator(val);if(locatorData.type=='ChoiceTextEntryValue')
{desc+=' '+getMessage('EditSection','TextEntryP');}
return desc;},buildSelectField:function(fieldDef)
{var node=QBuilder('select',{id:fieldDef.fieldName+'_'+this.id,className:'SelectBox',name:fieldDef.fieldName,exid:this.id,leid:this.getLogicEditor().id});if(fieldDef.prompt)
{node.appendChild(QBuilder('option',{value:''},[fieldDef.prompt]));}
if(fieldDef.value)
{var list=this.evalSchemaExpressionString(fieldDef.value);if(list===false)
{return'#loading#';}
for(key in list)
{if(typeof list[key]=='function')
{continue;}
var optionValue=key;var desc=list[key];if(fieldDef.labelKey)
{desc=list[key][fieldDef.labelKey];}
if(fieldDef.valueKey)
{if(list[key][fieldDef.valueKey])
optionValue=list[key][fieldDef.valueKey];else
QError('Cannot find valueKey: '+fieldDef.valueKey);}
desc=String(desc);if(fieldDef.optionModifier)
{desc=this.evalSchemaExpressionString(fieldDef.optionModifier,false,[optionValue,desc]);}
node.appendChild(QBuilder('option',{value:optionValue},[desc]));}
if(this.data[fieldDef.fieldName]!==undefined)
{node.value=this.data[fieldDef.fieldName];}
else
{if(node.value)
{this.performValueChange(fieldDef.fieldName,node.value);}}
if(fieldDef.truncate)
{if(Qualtrics.Browser.IE)
{QualtricsCPTools.smartTruncateSelectBox(node,fieldDef.truncate);}
else
{$(node).setStyle({maxWidth:(fieldDef.truncate*7)+'px'});}}
node.onchange=this.valueChangeHandler;}
return node;},buildSuggestField:function(fieldDef)
{QModules.loadModule('QSuggest.js');var options={id:fieldDef.fieldName+'_'+this.id,ajaxAction:'webservice',ajaxParams:fieldDef.params,onChange:this.refreshSuggestHandlerOnType.bind(this,fieldDef),onSelect:this.refreshSuggestHandlerOnSelect.bind(this,fieldDef),onHiddenInputChange:this.refreshSuggestHandlerOnHiddenInputChange.bind(this,fieldDef),allowCustomValues:fieldDef.allowCustomValues};if(fieldDef.prompt)
{options.prompt=fieldDef.prompt;}
if(this.data[fieldDef.fieldName]!==undefined)
{options.hiddenInputValue=this.data[fieldDef.fieldName];}
if(this.data[fieldDef.fieldName+"_searchtext"]!==undefined)
{options.inputValue=this.data[fieldDef.fieldName+"_searchtext"];}
var suggest=new QSuggest(options);var node=suggest.build();return node;},refreshSuggestHandlerOnType:function(fieldDef,key,val)
{this.data[fieldDef.fieldName+"_searchtext"]=val;delete this.data[fieldDef.fieldName];this.getLogicEditor().refreshControls();},refreshSuggestHandlerOnSelect:function(fieldDef,key,val)
{this.data[fieldDef.fieldName+"_searchtext"]=val;this.data[fieldDef.fieldName]=key;this.getLogicEditor().refreshControls();this.getLogicEditor().validate();},refreshSuggestHandlerOnHiddenInputChange:function(fieldDef,key,val)
{this.getLogicEditor().validate();},normalizeList:function(list,fieldDef)
{var returnList={};for(key in list)
{if(typeof list[key]=='function')
{continue;}
var optionValue=key;var desc=list[key];if(fieldDef.labelKey)
{desc=list[key][fieldDef.labelKey];}
if(fieldDef.valueKey)
{if(list[key][fieldDef.valueKey])
optionValue=list[key][fieldDef.valueKey];else
QError('Cannot find valueKey: '+fieldDef.valueKey);}
desc=String(desc);if(fieldDef.optionModifier)
{desc=this.evalSchemaExpressionString(fieldDef.optionModifier,false,[optionValue,desc]);}
returnList[optionValue]=desc;}
return returnList;},resolveDependency:function(dependsDef)
{return this.evalSchemaExpressionString(dependsDef);},getDescription:function(opt_editLink)
{var d=this.buildDescription(opt_editLink);if(typeof d=='object'&&d.innerHTML)
{return d.innerHTML;}
else
{return'';}},buildDescription:function(opt_editLink)
{var logicId=this.getLogicEditor().id;var desc='';if(this.validate())
{var conjString=this.data['Conjunction'];if(!conjString)conjString=getMessage('If');var conjSpan=QBuilder('span',{className:'ConjDesc'},conjString);var questionDescription=this.data.QuestionID
var leftOpDesc=this.data['LeftOperand'];if(window.BaseQuestion)
{var questionObj=BaseQuestion.getQuestionByQuestionId(this.data.QuestionID);if(questionObj)
{questionDescription=questionObj['description'];if(leftOpDesc)
{var choiceLocatorData=Q_GlobalLogic.getDataFromLocator(this.data['ChoiceLocator']);if(choiceLocatorData.choiceId||choiceLocatorData.answerId)
{leftOpDesc='';if(choiceLocatorData.choiceId)
{if(questionObj.getChoiceByChoiceId)
{var choiceObj=questionObj.getChoiceByChoiceId(choiceLocatorData.choiceId);if(choiceObj)
{leftOpDesc+=choiceObj.text;}}}
if(choiceLocatorData.answerId)
{if(questionObj.getAnswerByAnswerId)
{var answerObj=questionObj.getAnswerByAnswerId(choiceLocatorData.answerId);if(answerObj)
{leftOpDesc+=' - '+answerObj.text;}}}
if(choiceLocatorData.answerIndex)
{if(questionObj.answers[choiceLocatorData.answerIndex])
{var answerObj=questionObj.answers[choiceLocatorData.answerIndex];if(answerObj)
{leftOpDesc+=' - '+answerObj.text;}}}}
else if(choiceLocatorData.type=='ChoiceTextEntryValue')
{leftOpDesc='Text Response';}
else if(choiceLocatorData.type=='ChoiceDisplayed')
{leftOpDesc='';}
else if(choiceLocatorData.type=='DisplayableQuestion')
{leftOpDesc='';}}}}
var rightOperand=null;if(this.data['RightOperand'])
{var rightOperand=QBuilder('span',{className:'RightOpDesc'},' '+this.data['RightOperand']+' ');}
var isString=getMessage('Is')+' ';if(this.data['LogicType']=='Quota')
{var choiceLocatorData=Q_GlobalLogic.getDataFromLocator(this.data['ChoiceLocator']);var quotaId=choiceLocatorData.quotaId;questionDescription='Quota';if(this.data['Operator']=='QuotaMet')
{isString='';}
leftOpDesc=quotaId;if(this.data['QuotaName'])
{leftOpDesc=this.data['QuotaName'];}
if(this.quotaName)
{leftOpDesc=this.quotaName;}
else
{this.quotaName=this.getLogicEditor().getQuotaNameById(quotaId);leftOpDesc=this.quotaName;}}
if(!Q_GlobalLogic.needsValueBox(this.data['Operator']))
{rightOperand=null;}
var operatorString=getMessage(this.data['Operator']);var operator=QBuilder('span',{className:'OpDesc'},operatorString);var leftOperand=QBuilder('span',{className:'LeftOpDesc'},leftOpDesc);var questionSpan=QBuilder('span',{className:'QuestionDesc'},questionDescription);desc=QBuilder('span',{className:'InnerDescription',href:'javascript:void(0)'},[conjSpan,' ',questionSpan,' ',leftOperand,' ',isString,operator,' ']);if(rightOperand)
{desc.appendChild(rightOperand);}
if(opt_editLink&&typeof opt_editLink=='object')
{desc.appendChild(opt_editLink.cloneNode(true));}
else if(opt_editLink)
{desc.appendChild(QBuilder('a',{className:'a',clickcallback:'Q_LogicEditor.edit',instanceid:logicId},getMessage('EditSection','EditCondition')));}}
else
{var link=QBuilder('a',{href:'javascript:void(0)',clickcallback:'Q_LogicEditor.edit',instanceid:logicId},getMessage('EditSection','ClickHereToEditLogic'));if(opt_editLink&&typeof opt_editLink=='object')
{var link=opt_editLink.cloneNode(true)}
desc=QBuilder('div',{className:'LogicMsg'},[QBuilder('span',{className:'Error'},getMessage('EditSection','InvalidLogic')),' ',link]);}
return desc;},addObserver:function(input)
{if(!this.observers)
{this.observers=[];}
this.observers.push(new Form.Element.Observer(input,0.5,this.valueChangeHandler));},cleanup:function()
{if(this.rightOperandObserver)
{this.rightOperandObserver.stop();this.rightOperandObserver=null;}
if(this.leftOperandObserver)
{this.leftOperandObserver.stop();this.leftOperandObserver=null;}
if(this.observers)
{for(var i=0,len=this.observers.length;i<len;++i)
{this.observers[i].stop();this.observers[i]=null;}
this.observers=null;}},destroy:function()
{if(this.parentObj.getPosition()==0&&this.parentObj.parentObj.elements.length>1)
{if(this.parentObj.elements.length==1)
{return;}}
this.cleanup();var expressionSet=this.parentObj;expressionSet.elements.splice(this.getPosition(),1);if(expressionSet.elements.length==0)
{expressionSet.destroy();}
this.parentObj=null;expressionSet=null;},valueChangeHandler:function(evt,opt_value)
{if(evt&&evt.nodeType)
{var el=evt;}
else
{if(!evt)evt=window.event;var el=Event.element(evt);}
var leid=el.getAttribute('leid');var exid=el.getAttribute('exid');var type=el.getAttribute('name');var expressionObj=Q_Expression.getInstance(exid);var logicEditor=expressionObj.getLogicEditor();if(!logicEditor)
logicEditor=expressionObj;if(el.type=='checkbox')
{opt_value=undefined;}
if(opt_value!==undefined)
{var val=opt_value;if(expressionObj)
{expressionObj.data[type]=val;logicEditor.saved=false;expressionObj.updateValues();logicEditor.validate();logicEditor.attentionHighlighter(false);logicEditor.refreshControls();}}
else
{logicEditor.initialRender=false;var value=el.value;if(el.type=='checkbox')
{value=el.checked?1:0;}
if(expressionObj)
{if(type=='LogicType')
{var oldConj=expressionObj.data['Conjunction'];expressionObj.resetSubsequentFields(type);expressionObj.data={};expressionObj.data['Conjunction']=oldConj;expressionObj.cachedSchema=null;}
expressionObj.performValueChange(type,value);if(type!='Conjunction')
{expressionObj.resetSubsequentFields(type,true);}}}
if(logicEditor.onValueChange)
logicEditor.onValueChange();if(logicEditor.onChange)
logicEditor.onChange();if(expressionObj.onChange)
expressionObj.onChange();},performValueChange:function(fieldName,value)
{this.data[fieldName]=value;var fieldDef=this.getFieldDef(fieldName);if(fieldDef)
{}
var logicEditor=this.getLogicEditor();logicEditor.saved=false;this.triggerRefresh();},resetSubsequentFields:function(fieldName,persistApplicableValues)
{var fieldPos=this.getSchemaFieldPosition(fieldName);if(!fieldPos)
{fieldPos=0;}
var schema=this.getSchemaElement();if(schema&&schema.fields)
{for(var i=fieldPos+1,len=schema.fields.length;i<len;++i)
{var field=schema.fields[i];if(field.persistent)
{continue;}
if(field.fieldName)
{if(field.type=='textbox'||field.type=='combobox'||field.type=='hidden')
{if(field.value)
{this.data[field.fieldName]=this.evalSchemaExpressionString(field.value);}}
else
this.data[field.fieldName]=undefined;}}}},getSchemaElement:function()
{if(!this.cachedSchema)
{this.cachedSchema=this.getLogicEditor().schema.getElementById(this.data['LogicType']);}
return this.cachedSchema;},getSchemaFieldPosition:function(fieldName)
{var schema=this.getSchemaElement();if(schema&&schema.fields)
{for(var i=0,len=schema.fields.length;i<len;++i)
{if(schema.fields[i].fieldName==fieldName)
return i;}}},getFieldDef:function(fieldName)
{var fieldPos=this.getSchemaFieldPosition(fieldName);if(fieldPos!==undefined)
{var schema=this.getSchemaElement();if(schema.fields)
return this.getSchemaElement().fields[fieldPos];}},validate:function()
{this.valid=true;this.invalidReason=null;var schema=this.getSchemaElement();if(schema&&schema.fields)
{for(var i=0,len=schema.fields.length;i<len;++i)
{if(schema.fields[i].depends&&!this.resolveDependency(schema.fields[i].depends))
{continue;}
if(schema.fields[i].type=='checkbox')
{continue;}
if(schema.fields[i].fieldName&&!this.data[schema.fields[i].fieldName]&&!schema.fields[i].optional)
{this.invalidReason=schema.fields[i].fieldName;this.valid=false;return this.valid;}}}
if(schema&&schema.validation)
{if(!this.evalSchemaExpressionString(schema.validation))
{this.valid=false;}}
return this.valid;},validateOld:function()
{var logicEditor=this.parentObj.parentObj.parentObj;var valid=false;this.invalidReason=null;if(this.data['LogicType']=='Question'||this.data['LogicType']=='EmbeddedField'||this.data['LogicType']=='Quota')
{if(this.data.QuestionID||this.data['QuotaID']||this.data['LogicType']=='EmbeddedField')
{if(!this.data['LeftOperand']&&this.choiceLocator&&this.data['LogicType']=='Question')
{this.data['LeftOperand']=this.choiceLocator;}
if(this.data['LeftOperand'])
{if(this.data['Operator'])
{if(Q_GlobalLogic.needsValueBox(this.data['Operator']))
{if(this.data['RightOperand']!=null&&this.data['RightOperand']!="")
{valid=true;}
else
{valid=false;this.invalidReason='RightOperand';}}
else
{valid=true;}}
else
{this.invalidReason='operator';}}
else
{this.invalidReason='LeftOperand';}}
else
{this.invalidReason='QuestionID';}}
else if(this.data)
{return true;}
return valid;},getOperatorListTypeFromChoiceLocator:function()
{var locatorData=Q_GlobalLogic.getDataFromLocator(this.data['ChoiceLocator']);var locatorType=locatorData.type;var listType;if(locatorType=='DisplayableQuestion')
{listType='Displayed';}
else if(locatorType=='SelectableAnswer'||locatorType=='SelectableChoice'||locatorType=='DisplayableChoice')
{if(this.getLogicEditor().hideDisplayed)
{listType='Selected';}
else
{listType='SelectedWithDisplayed';}}
else if(locatorType=='ChoiceNumericEntryValue'||locatorType=='ChoiceTextEntryValue'||locatorType=='AnswerNumericEntryValue'||locatorType=='AnswerTextEntryValue'||locatorType=='SelectedAnswerCount'||locatorType=='SelectedChoicesCount')
{if(this.getLogicEditor().hideDisplayed)
{listType='Numeric';}
else
{listType='NumericWithDisplayed';}}
else if(locatorType=='Region')
{listType='Region';}
return this.getOperatorList(listType);},getGUID:function()
{return QualtricsCPTools.createNewId('QID');},getOperatorList:function(type)
{if(type=='Selected')
{return{Selected:getMessage('Selected'),NotSelected:getMessage('NotSelected')}}
else if(type=='Displayed')
{return{Displayed:getMessage('Displayed'),NotDisplayed:getMessage('NotDisplayed')}}
else if(type=='SelectedWithDisplayed')
{return{Selected:getMessage('Selected'),NotSelected:getMessage('NotSelected'),Displayed:getMessage('Displayed'),NotDisplayed:getMessage('NotDisplayed')}}
else if(type=='Numeric')
{return{EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto'),GreaterThan:getMessage('GreaterThan'),GreaterThanOrEqual:getMessage('GreaterThanorEqual'),LessThan:getMessage('LessThan'),LessThanOrEqual:getMessage('LessThanorEqual'),Empty:getMessage('Empty'),NotEmpty:getMessage('NotEmpty'),Contains:getMessage('Contains'),DoesNotContain:getMessage('DoesNotContain'),MatchesRegex:getMessage('MatchesRegex')}}
else if(type=='NumericSimple')
{return{EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto'),GreaterThan:getMessage('GreaterThan'),LessThan:getMessage('LessThan')}}
else if(type=='String')
{return{Contains:getMessage('Contains'),Is:getMessage('Is'),StartsWith:getMessage('StartsWith'),EndsWith:getMessage('EndsWith')}}
else if(type=='NumericWithDisplayed')
{return{EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto'),GreaterThan:getMessage('GreaterThan'),GreaterThanOrEqual:getMessage('GreaterThanorEqual'),LessThan:getMessage('LessThan'),LessThanOrEqual:getMessage('LessThanorEqual'),Empty:getMessage('Empty'),NotEmpty:getMessage('NotEmpty'),Contains:getMessage('Contains'),DoesNotContain:getMessage('DoesNotContain'),MatchesRegex:getMessage('MatchesRegex'),Displayed:getMessage('Displayed'),NotDisplayed:getMessage('NotDisplayed')}}
else if(type=='Quota')
{return{QuotaMet:getMessage('QuotaMet'),QuotaNotMet:getMessage('QuotaNotMet'),GreaterThan:getMessage('GreaterThan'),GreaterThanOrEqual:getMessage('GreaterThanorEqual'),LessThan:getMessage('LessThan'),LessThanOrEqual:getMessage('LessThanorEqual'),EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto')}}
else if(type=='Date')
{return{LessThan:getMessage('Piping','Before'),GreaterThan:getMessage('Piping','After'),EqualTo:getMessage('Piping','Exactly'),NotEqualTo:getMessage('Piping','NotOn')}}
else if(type=='Region')
{return{ClickedIn:getMessage('ClickedIn'),NotClickedIn:getMessage('NotClickedIn')}}},getOperatorSelect:function(locatorType,opt_operatorName)
{if(locatorType=='DisplayableQuestion')
{var list={Selected:'Selected',NotSelected:'Not Selected',Displayed:'Displayed',NotDisplayed:'Not Displayed'}
if(!list[this.data['Operator']])
{this.data['Operator']='Displayed';}}
else if(locatorType=='SelectableAnswer'||locatorType=='SelectableChoice'||locatorType=='DisplayableChoice')
{var list={Selected:'Selected',NotSelected:'Not Selected',Displayed:'Displayed',NotDisplayed:'Not Displayed'}
if(this.getLogicEditor().hideDisplayed)
{var list={Selected:'Selected',NotSelected:'Not Selected'}}
if(!list[this.data['Operator']])
{this.data['Operator']='Selected';}}
else if(locatorType=='ChoiceNumericEntryValue'||locatorType=='ChoiceTextEntryValue'||locatorType=='AnswerNumericEntryValue'||locatorType=='AnswerTextEntryValue')
{var list={GreaterThan:getMessage('GreaterThan'),GreaterThanOrEqual:getMessage('GreaterThanorEqual'),LessThan:getMessage('LessThan'),LessThanOrEqual:getMessage('LessThanorEqual'),EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto'),Empty:getMessage('Empty'),NotEmpty:getMessage('NotEmpty'),Displayed:getMessage('Displayed'),NotDisplayed:getMessage('NotDisplayed')}
if(!list[this.data['Operator']])
{this.data['Operator']='NotEmpty';}}
else if(locatorType=='SelectedAnswerCount'||locatorType=='SelectedChoicesCount')
{var list={GreaterThan:getMessage('GreaterThan'),GreaterThanOrEqual:getMessage('GreaterThanorEqual'),LessThan:getMessage('LessThan'),LessThanOrEqual:getMessage('LessThanorEqual'),EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto')}
if(!list[this.data['Operator']])
{this.data['Operator']='EqualTo';}}
else if(locatorType=='EmbeddedField')
{var list={GreaterThan:getMessage('GreaterThan'),GreaterThanOrEqual:getMessage('GreaterThanorEqual'),LessThan:getMessage('LessThan'),LessThanOrEqual:getMessage('LessThanorEqual'),EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto'),Empty:getMessage('Empty'),NotEmpty:getMessage('NotEmpty')}
if(!list[this.data['Operator']])
{this.data['Operator']='EqualTo';}}
else if(locatorType=='Quota')
{var list={QuotaMet:getMessage('QuotaMet'),GreaterThan:getMessage('GreaterThan'),GreaterThanOrEqual:getMessage('GreaterThanorEqual'),LessThan:getMessage('LessThan'),LessThanOrEqual:getMessage('LessThanorEqual'),EqualTo:getMessage('EqualTo'),NotEqualTo:getMessage('NotEqualto')}
if(!list[this.data['Operator']])
{this.data['Operator']='QuotaMet';var newLocator=Q_GlobalLogic.getLocatorFromData(this.data['QuotaID'],locatorType,this.data['Operator']);this.data['LeftOperand']=newLocator;}}
else if(locatorType=='_date')
{var list={LessThan:getMessage('Piping','Before'),GreaterThan:getMessage('Piping','After'),EqualTo:getMessage('Piping','Exactly'),NotEqualTo:getMessage('Piping','NotOn')}}
else if(locatorType=='_MemberShip')
{var list={NotArrayContains:getMessage('Piping','NotAMember'),ArrayContains:getMessage('Piping','Member')}}
else if(locatorType=='Region')
{var list={ClickedIn:'Clicked In',NotClickedIn:'Not Clicked In'}}
var opt_operatorName=opt_operatorName||'Operator';var select=QBuilder('select',{className:'SelectBox',name:opt_operatorName,exid:this.id,leid:this.getLogicEditor().id});for(name in list)
{select.appendChild(QBuilder('option',{value:name},list[name]))}
return select;},tryFields:function()
{var fields=this.getCurrentFields();var fieldName='';for(var i=0,ilen=arguments.length;i<ilen;i++)
{fieldName=arguments[i];if(fields[fieldName])
return fields[fieldName];}
return'';}}