// JavaScript needed by the form_edit template(s)

if(typeof(window.Ln_ClassMaker) === 'object') {
	MMI.Util.ns('MMI.Form.Edit');
	MMI.Form.Edit = {
        _questionInit: function(formItemId) {
            // @mmi-log MMI.log('MMI.Form.Edit._questionInit()');
            MMI.Form.Edit._questionMakeSortableLists();
            MMI.Form.Edit._questionUpdateOptionButtons('form_' + formItemId);
            MMI.Form.Edit._questionInitTypeListener();
            MMI.Form.Edit._questionInitOptionsDialog();
        }
        /* Question Option Source Editor */
		,_questionInitOptionsDialog: function() {
            // @mmi-log MMI.log('MMI.Form.Edit._questionInitOptionsDialog()');
			var jelDialog = jQuery('#mmiQuestionOptionsDialog');
            // @mmi-log MMI.log('Dialog selected: ');
            // @mmi-log MMI.log(jelDialog);
            if(!jelDialog.size()) {
                jQuery('body').append('<div id="mmiQuestionOptionsDialog" style="display: none;"></div>');
                jelDialog = jQuery('#mmiQuestionOptionsDialog');
            }
            jelDialog.dialog({
				autoOpen: false
                , 'modal': true
				, width: 500
				, height: 425
                , 'close': function() {
                    jQuery(this).html('');
                }
			});
		}
        // Loop over all the question type fields and register them to listen for
        ,_questionInitTypeListener: function() {
            var fields = jQuery('.modelQuestionOptionField');
            fields.unbind('change.mmi_questionTypeListener'); //.mmi_questionTypeListener
            fields.bind('change.mmi_questionTypeListener', MMI.Form.Edit._questionUpdateOptionButtons);
        }
        ,_questionInitDependencies: function(formItemId) {
            var jelQuestionContainers = jQuery('.mmi_question', '#item_form_' + formItemId);
            jelQuestionContainers.each(function() {
                var jel = jQuery(this);
                var questionId = MMI.Form.Edit._questionGetId(jel);
                var jelDepRules = jQuery('.questionDependencyRules input', jel);
                if(jelDepRules.size() > 0) {
                    var jelParentQuestion = MMI.Form.Edit.questionDependencyGetPreviousQuestionContainer(questionId);
                    var jelParentQuestionDeps = jQuery('.questionDependents:first', jelParentQuestion);
                    jel.detach().appendTo(jelParentQuestionDeps);
                }
            });

            jelQuestionContainers.each(function() {
                var jel = jQuery(this);
                var questionId = MMI.Form.Edit._questionGetId(jel);
                if(MMI.Form.Edit.questionHasDependents(questionId)) {
                    MMI.Form.Edit._questionDisableFieldType(jel);
                }
            });


            MMI.Form.Edit._questionUpdateDependencyButtons(formItemId);
            MMI.Form.Edit._questionUpdateDeleteButtons(formItemId);
        }
        ,_questionUpdateDependencyButtons: function(formItemId) {
            var jelQuestionContainers = jQuery('.mmi_question', '#item_form_' + formItemId);
            jelQuestionContainers.each(function() {
                var jel = jQuery(this);
                var questionId = MMI.Form.Edit._questionGetId(jel);
                // button[1381][207][dependency][create]
                var depBtn = jQuery('#button_dependency_create_' + questionId);
                if(MMI.Form.Edit.questionCanBeDependent(questionId) || MMI.Form.Edit.questionIsDependent(questionId)) {
                    depBtn.removeClass('disabled');
                } else {
                    depBtn.addClass('disabled');
                }
            });
        }
        ,_questionUpdateDeleteButtons: function(formItemId) {
            var jelQuestionContainers = jQuery('.mmi_question', '#item_form_' + formItemId);
            jelQuestionContainers.each(function() {
                var jel = jQuery(this);
                var questionId = MMI.Form.Edit._questionGetId(jel);
                // button[1381][207][dependency][create]
                var depBtn = jQuery('#button_dependency_delete_' + questionId);
                if(MMI.Form.Edit.questionHasDependents(questionId)) {
                    depBtn.addClass('disabled');
                } else {
                    depBtn.removeClass('disabled');
                }
            });
        }
        ,_questionHandleSortableListUpdate: function() {
            var sel = jQuery('.mmi-admin_questionList > .mmi_question');
            //var sortList = [];
            var formItemId = 0;
            var sortCount = 0;
            sel.each(function() {
                var jelQuestionRow = jQuery(this);
                var questionItemId = MMI.Form.Edit._questionGetId(jelQuestionRow);//jelQuestionRow.attr('id').split('_')[1];
                var jelForm = jelQuestionRow.parents('form:first');
                formItemId = jelForm.attr('id').split('_')[2];
                var jelSortField = jQuery.genome('#formfield['+formItemId+']['+questionItemId+'][sort_order]');
                if(!formItemId) {
                    formItemId = MMI.Form.Edit._questionGetFormId(jelQuestionRow);
                }
                jelSortField.val(sortCount);
                sortCount++;

                // Select and set sort count on dependent questions
                var subSel = jQuery('.questionDependents .mmi_question', jelQuestionRow);
                subSel.each(function() {
                    var jelQuestionRow = jQuery(this);
                    var questionItemId = jelQuestionRow.attr('id').split('_')[1];
                    var jelForm = jelQuestionRow.parents('form:first');
                    var formItemId = jelForm.attr('id').split('_')[2];
                    var jelSortField = jQuery.genome('#formfield['+formItemId+']['+questionItemId+'][sort_order]');
                    jelSortField.val(sortCount);
                    jelSortField.change(); //force event
                    sortCount++;
                });
            });

            MMI.Form.Edit._questionUpdateDependencyButtons(formItemId);
            MMI.Form.Edit._questionUpdateDeleteButtons(formItemId);

        }
		,_questionMakeSortableLists: function() {
            var sel = jQuery('.mmi-admin_questionList, .questionDependents');
            sel.each(function() {
                var jel = jQuery(this);
                jel.sortable('destroy');
                jel.sortable(
                    {
                        'handle': '.sortableHandle'
                        ,'forcePlaceholderSize': false
                        ,'items': '> .sortable'
                        ,'tolerance': 'intersect'
                        ,'update': MMI.Form.Edit._questionHandleSortableListUpdate
                    }
                );
            });
            MMI.Form.Edit._questionHandleSortableListUpdate();
		}
        ,_questionUpdateOptionButtons: function(e) {
        	//// @mmi-log MMI.log(e);
            var fields = jQuery.genome('.modelQuestionOptionField');
            //// @mmi-log MMI.log(fields);
            fields.each(function() {
                var field = jQuery(this);
                var fieldId = field.attr('id');
                var optButtonId = fieldId.replace('formfield[', 'button[').replace('[edittype]', '[optionsource]');
                //// @mmi-log MMI.log(optButtonId);
                var jelOptButton = jQuery.genome('#' + optButtonId);
                //// @mmi-log MMI.log(jelOptButton);
                //// @mmi-log MMI.log(field);
                //// @mmi-log MMI.log(field.val());
                switch(field.val()) {
                    case 'checkboxgroup':
                    case 'option':
                    case 'radio':
                    case 'filerefdynamic' :
                    case 'assoc' : 
                        // Enable
                        jelOptButton.removeClass('disabled');
                        break;
                    default:
                        // Disable
                        jelOptButton.addClass('disabled');
                        break;
                }
            });
        }
        ,_questionUpdateOptionButton: function() {
            throw 'MMI.Form.Edit._questionUpdateOptionButton is deprecated. You must call MMI.Form.Edit._questionUpdateOptionButtons instead.';
            MMI.Form.Edit._questionUpdateOptionButtons();
        }
        ,questionParseOptions: function(fieldId){
        	//Get the initial value/text and determine type
        	var dataElement = jQuery(fieldId);
        	fieldId = dataElement.attr('id');
        	var items = new Object();
        	//bad name, get rid of it
        	if(dataElement == undefined){
        		return items;
        	}
        	var fieldValue = dataElement.val();
        	//check type
        	
        	if(fieldValue.substring(0,5) == 'list:'){
        		//linear list
        		var list = fieldValue.substring(5).split(',');
        		if(list.length <= 0){
        			return items;
        		}
        		//make the key the value 
        		for(i=0;i<list.length;i++){
        			var n = decodeURIComponent(list[i].replace(/\+/g,  " "));
        			items[n] = n;
        		}
        	}else if(fieldValue.substring(0,6) == 'assoc:'){
        		//property list
        		var list = fieldValue.substring(6).split(':::');
        		if(list.length <= 0){
        			return items;
        		}
        		for(i=0;i<list.length;i++){
        			var parts = list[i].split(',');
        			var iKey = parts[0].replace(/%2c/g,  ",");
        			var iValue = parts[1].replace(/%2c/g,  ",");
        			items[iKey] = iValue;
        		}
        	}
        	return items;
        }
        ,questionOptionsDialog: function(title, fieldId, typeFieldId) {
            //var jel = jQuery(fieldId);

            var typeField = jQuery(typeFieldId);
            var fieldType = typeField.val();
            if (fieldType != 'checkboxgroup' && fieldType != 'option' && fieldType != 'radio' && fieldType != 'filerefdynamic' && fieldType != 'assoc') {
                MMI.Util.alert("Only the following field types support options:<br /><br /><ul><li>Check Box Group</li><li>Option/Select</li><li>Radio Button List</li></ul>", 'Question Options');
                return false;
            }

            var dialog = jQuery('#mmiQuestionOptionsDialog');
            dialog.html('');
            var tmp = jQuery(jQuery("#mmiQuestionOptionsDialogTemplate").html());
            var tmpHead = jQuery('#mmiQuestionDialogOptionsEditorHeaderTemplate tr.mmiQuestionDialogOptionsEditorHeaderRow').clone(false);
            
            //var tmpTbl = jQuery('table.mmiQuestionOptionsSortGroup', tmp);
            // tmpTbl is empty here
            //console.log(tmpTbl);
            //tmpHead.appendTo(tmpTbl);
            
            dialog.html(tmp);
            
            var tmpTbl = jQuery('table.mmiQuestionOptionsSortGroup', dialog);
            tmpHead.appendTo(tmpTbl);

            var base = this.questionParseOptions(fieldId);

            // Clear the table of all template rows. We're going to build all rows from the optionsource data.
            //console.log(jQuery('tr.sortable', dialog));
            jQuery('tr.sortable', dialog).remove();
            //dialog.children('table').html('');
            var rowHtml = jQuery('#mmiQuestionOptionsDialogTemplate table.mmiQuestionOptionsSortGroup').html(); 
            var counter = 0;
            var newRowHtml = '';
            for (key in base) {
            	counter ++;
            	var numName = (counter).toString();
            	var iValue = base[key];
                newRowHtml = rowHtml.toString().replace(/{%num}/gi, numName);
                newRowHtml = newRowHtml.replace(/{%value}/gi, iValue);
                newRowHtml = newRowHtml.replace(/{%key}/gi, key);
                dialog.children('table.mmiQuestionOptionsSortGroup').append(newRowHtml);
                var deleteEl = jQuery('#mmiQuestionOptionsDialog .mmiTmpOptionFieldDelete:last');
                deleteEl.click(function(event) {
                    // @mmi-log MMI.log('Deleting option (A.1)...');
                    // @mmi-log MMI.log(jQuery(this));
                    jQuery(this).parent().parent().remove(); // Remove the <tr> row tag and its contents.
                });
            }

            var updateSourceField = function(event) {
                // Select all fields in their DOM order.
                var tmpSourceField = jQuery("#mmiTmpOptionFieldSource");
                tmpSourceField.val(''); // Reset the tmp value.
                jQuery('#mmiQuestionOptionsDialog .mmiQuestionOptionsEditorRowTemplate').each(function() {
                    // The scope here is NOT the same as outside this anonymous function.
                    // This means we have to select the tmpSourceField inside here every time this function runs.
                   //
                	var iValue = jQuery('.mmiTmpOptionValueField:first', this).val();
                	var iKey = jQuery('.mmiTmpOptionKeyField:first', this).val();
                	//if no key, duplicate
                	if(iKey == '' || iKey == undefined){
                		iKey = iValue;
                	}
                	iKey = iKey.replace(/,/g, '%2c');
                	iValue = iValue.replace(/,/g, '%2c');
                    var tmpSourceField = jQuery('#mmiTmpOptionFieldSource');
                    
                    if (!tmpSourceField.val()) {
                        tmpSourceField.val('assoc:' + iKey + ',' + iValue);
                    } else {
                        tmpSourceField.val(tmpSourceField.val() + ':::' + iKey + ',' + iValue);
                    }
                });
                //alert(tmpSourceField.val());
                // @mmi-log MMI.log('Updating source field to value: ' + tmpSourceField.val());
                jQuery(fieldId).val(tmpSourceField.val());
                MMI.log('force change event');
                jQuery(fieldId).change();
            };

            dialog.children('.mmiQuestionOptionsSortGroup').sortable({
                items: 'tr.sortable'
            	, handle: '.mmiTmpOptionFieldDragHandle'
                , stop: updateSourceField
            });
            jQuery('.mmiQuestionOptionsButtonAdd').click(function() {
                var rowHtml = jQuery('#mmiQuestionOptionsDialogTemplate table.mmiQuestionOptionsSortGroup').html();
                rowHtml = rowHtml.replace(/{%num}/gi, 'X.').replace(/{%value}/gi, '').replace(/{%key}/gi, '');
                var el = jQuery(this).parent();
                el.children('table.mmiQuestionOptionsSortGroup').append(rowHtml);
                jQuery('#' + el.attr('id') + ' .mmiTmpOptionField:last').focus();
                var deleteEl = jQuery('#mmiQuestionOptionsDialog .mmiTmpOptionFieldDelete:last');
                deleteEl.click(function(event) {
                    // @mmi-log MMI.log('Deleting option (A2) ...');
                    // @mmi-log MMI.log(jQuery(this));
                    jQuery(this).parent().parent().remove(); // Remove the <tr> row tag and its contents.
                });
            });

            dialog.dialog('option', 'title', title);
            dialog.dialog(
                'option'
                , 'beforeclose'
                , updateSourceField
            );
            dialog.dialog('open');
        }
        ,questionNotesDialog: function(title, fieldId) {
            var el = jQuery(fieldId);
            var dialog = jQuery('<div />');
            var field = jQuery('<textarea id="mmiNotesDialogTmpField" style="width: 315px; height: 155px;">' + el.val() + '</textarea>');
            field.data({
                sourceField: el
            });
            dialog.html(field).dialog({
                title: title
                , resizable : false
                , width: 352
                , height: 212
                , beforeclose: function(event) {
                    var el = jQuery(this).children('#mmiNotesDialogTmpField');
                    var sourceEl = el.data('sourceField');
                    sourceEl.val(el.val());
                    sourceEl.change();
                }
                , close: function(event) {
                    var jel = jQuery(this);
                    jel.dialog('destroy');
                    jel.remove();
                }
            });
        }
		,questionAdd: function(itemId, type, layout) {
            var jelTpl = jQuery('#questionRow____mmi_tmp_question_id___');
            var htmlTpl = jelTpl.parent().html();
            //var newQuestionId = 'item[' + itemId + '][question_' + MMI.Util.getRandomString(10) + ']';
            var newQuestionId = MMI.Util.getRandomString(10);
            htmlTpl = htmlTpl.replace(/___mmi_tmp_question_id___/g, newQuestionId);
            var jelNewQuestion = jQuery(htmlTpl);//.attr('id', '');
            var jelQuestions = jQuery('#mmi-admin_questionList_' + itemId);
            jelQuestions.append(jelNewQuestion);

            MMI.Form.Edit._questionInit(itemId);
		}
		,questionDelete: function(formId, questionId, fieldName, isNew) {
	        var del = jQuery(this);
            if(MMI.Form.Edit.questionHasDependents(questionId)) {
                MMI.Util.alert('This question has dependent questions attached to it and cannot be deleted.<br /><br />Remove the dependency connections or delete the dependent questions to enable deletion of this question.', 'Delete Question');
                return;
            }
            MMI.Util.confirm(
                    'Are you sure you want to delete this question?',
                    'Confirm: Delete User',
                    {
                        'label': 'Confirm Delete',
                        'function': function() {
                            var jel = jQuery(this);
                            MMI.Form.Edit._questionHandleDelete(jel.dialog('option', 'mmiQuestionDeleteData'));
                            jel.dialog('destroy');
                            jel.remove();
                        }
                    }, null, {'mmiQuestionDeleteData': {
                        'questionId': questionId
                        ,'fieldName': fieldName
                        ,'formId': formId
                        ,'isNew': isNew
                    }
                }
            );
	    }
        ,_questionHandleDelete: function(questionDeleteData) {
            MMI.Util.log('MMI.Form.Edit._questionHandleDelete('+questionDeleteData.formId+', '+questionDeleteData.questionId+', '+questionDeleteData.fieldName+', '+questionDeleteData.isNew+')');
            var jel = jQuery('#questionRow_'+questionDeleteData.questionId);
            jel.remove();
	        if (questionDeleteData.isNew != '1') {
	            var formEl = jQuery('#item_form_' + questionDeleteData.formId + '_hidden_fields');
	            formEl.append('<input type="hidden" name="deletefield['+questionDeleteData.formId+']['+questionDeleteData.fieldName+']" value="1" />');
	        }
        }
		,questionShowOptions: function(itemId, qid) {
			if(!qid) {
				//alert('This field type does not allow for predefined options. Use a select or checkbox group.');
				MMI.Util.alert('No question ID - cannot create options.', 'Question Options Error');
			} else {
				//var id = '#formfield_' + itemId + '-' + qid + '_options';
				jQuery('#formfield_' + itemId + '-' + qid + '_options').dialog('open');
			}
		}

        // --------------------------- DEPENDENCIES ---------------------------
        ,questionDependencyDialog: function(questionId) {
        	// If not a dependent question this does not apply
        	if(!MMI.Form.Edit.questionIsDependent(questionId)) {
        		return false;
        	}

            // find question container based on item id
        	var jelParentQuestion = MMI.Form.Edit.questionDependentGetParentContainer(questionId);
            var jelQuestion = jQuery('#questionRow_' + questionId);

            // Check the parent container type
        	jelTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jelParentQuestion, 'edittype');
        	var formFieldType = jelTypeField.val();
            var templateName = '';
            switch(formFieldType){
            	case 'checkbox':
            		templateName = 'mmiDependentDialogTemplate_truefalse';
            		break;
            	case 'checkboxgroup' :
            	case 'option' : 
            	case 'radio' :
            		templateName = 'mmiDependentDialogTemplate_option';
            		break;
            	case 'text' :
            	case 'textarea' :
            	case 'html' : 
            		templateName = 'mmiDependentDialogTemplate_hasvalue';
            		break;
            	case 'number' : 
            		templateName = 'mmiDependentDialogTemplate_number';
            		break;            	
            	default:
            		//not allowed date, datetime, label, assoc, color
            		return false;
            }
            if(templateName != ''){
            	//Select it
            	var jelTemplate = jQuery('#' + templateName);
            	//swap the ids
            	var templateHTML = '<div>'+jelTemplate.html()+'</div>';
            	templateHTML = templateHTML.replace(/{%id}/gi, questionId);
            
            	//populate the options if applicable
            	var jelDialogInnerContainer = jQuery(templateHTML);
            	jelDialogInnerContainer.dialog({ 
            			'autoOpen' : true, 
            			'modal' : true,
                        'width': 580,
                        'height': 380,
            			'buttons': {
            				'Save Dependency': MMI.Util.bind(function(questionId){
                                var jel = jQuery(this);

                                var jelParentQuestion = MMI.Form.Edit.questionDependentGetParentContainer(questionId);
                                var jelQuestion = jQuery('#questionRow_' + questionId);
                                var jelParentQuestionNameField = MMI.Form.Edit._questionGetFieldFromContainer(jelParentQuestion, 'field');
                                var jelParentQuestionTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jelParentQuestion, 'edittype');


                                //                                                                       Multi/Option             |   True/False |   Text  |  Number
                                // formfielddependencies[$form_id][$questionName][0][condition_answer]=  stringCheckedOptions     |   true/false |   N/A   |  value (#) in field
                                // formfielddependencies[$form_id][$questionName][0][condition_modifier]=in                       |   =          |   N/A   |  >,<,>=,<=,=
                                // formfielddependencies[$form_id][$questionName][0][condition_field]=   $questionParentFieldName
                                // formfielddependencies[$form_id][$questionName][0][condition_isset]=   N/A                      |   N/A        |   true  | N/A

                                jQuery('#questionDependencyRules_' + questionId).html('');
                                var formItemId = MMI.Form.Edit._questionGetFormId(jelQuestion);
                                MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'field', jelParentQuestionNameField.val());
                                

                                var formFieldType = jelParentQuestionTypeField.val();
                                //var templateName = '';
                                switch(formFieldType){
                                    case 'checkbox':
                                        //templateName = 'mmiDependentDialogTemplate_truefalse';
                                        var stringCheckedOption = jQuery('.answer_options_' + questionId + ' input:checked', jel).val();
                                        MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'answer', stringCheckedOption);
                                        MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'modifier', '=');
                                        break;
                                    case 'checkboxgroup' :
                                    case 'option' :
                                    case 'radio' :
                                        //templateName = 'mmiDependentDialogTemplate_option';
                                        var checkedOptions = jQuery('.answer_options_' + questionId + ' input:checked', jel);
                                        var stringCheckedOptions = '';
                                        checkedOptions.each(function() {
                                            var jelOption = jQuery(this);
                                            stringCheckedOptions += ':::' + jelOption.val();
                                        });
                                        stringCheckedOptions += ':::';
                                        if(stringCheckedOptions == ':::') {
                                            stringCheckedOptions += ':::';
                                        }
                                        MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'answer', stringCheckedOptions);
                                        MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'modifier', 'in');
                                        break;
                                    case 'text' :
                                    case 'textarea' :
                                    case 'html' :
                                        //templateName = 'mmiDependentDialogTemplate_hasvalue';
                                        MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'isset', '1');
                                        break;
                                    case 'number' :
                                        //templateName = 'mmiDependentDialogTemplate_number';

                                        MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'answer', jQuery('#answer_' + questionId).val());
                                        MMI.Form.Edit._questionDependencyInsertOptionField(formItemId, questionId, 'modifier', jQuery('#modifier_' + questionId).val());
                                        break;
                                    default:
                                        //not allowed date, datetime, label, assoc, color
                                        return false;
                                }

                                jel.dialog('destroy').remove();
                                //foce the name to update so that it will trigger autosave
                                jelParentQuestionNameField.change();
                            }, jelDialogInnerContainer,[questionId]),
            				'Remove Dependency': MMI.Util.bind(
            						function(questionId) {
            							MMI.Form.Edit.questionDependencyRemove(questionId);
            							jQuery(this).dialog('destroy').remove();
            						}
            						, jelDialogInnerContainer
            						, [questionId])
            			}
            		}
            	);

            	//add controls based on template
            	var jelOptionsField = MMI.Form.Edit._questionGetFieldFromContainer(jelParentQuestion, 'optionsource')              
            	var options = MMI.Form.Edit.questionParseOptions(jelOptionsField);
                var formItemId = MMI.Form.Edit._questionGetFormId(jelQuestion);
            	switch(templateName){
            	    case 'mmiDependentDialogTemplate_option' :
                        var jelDependencyOptionsContainer = jQuery('.answer_options_' + questionId);

                        // formfielddependencies[1381][question_4c10e5fa5158c][0][condition_answer]

                        var jelQuestionTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jQuery('#questionRow_'+questionId), 'field');

                        var jelCurrentOptions = jQuery.genome('#formfielddependencies['+formItemId+']['+jelQuestionTypeField.val()+'][0][condition_answer]');
                        var currentOptions = [];
                        if(jelCurrentOptions.size()) {
                            currentOptions = jelCurrentOptions.val().split(':::');
                        }

            		    for(var key in options) {
                            var value = options[key];
                            var checked = '';
                            if(MMI.Util.inArray(key, currentOptions)) {
                                checked = ' checked="checked"';
                            }
                            jelDependencyOptionsContainer.append(jQuery('<div><input type="checkbox" name="answer_' + questionId + '" value="'+key+'"'+checked+' /> '+value+'</div>'));
                        }
            		    break;
                    case 'mmiDependentDialogTemplate_truefalse':
                        var jelDependencyOptionsContainer = jQuery('.answer_options_' + questionId);

                        // formfielddependencies[1381][question_4c10e5fa5158c][0][condition_answer]

                        var jelQuestionTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jQuery('#questionRow_'+questionId), 'field');

                        var jelCurrentValue = jQuery.genome('#formfielddependencies['+formItemId+']['+jelQuestionTypeField.val()+'][0][condition_answer]');
                        var currentValue = '1';
                        if(jelCurrentValue.size()) {
                            currentValue = jelCurrentValue.val();
                        }

                        options = {
                            '1': 'Checked'
                            ,'0': 'Not Checked'
                        };

            		    for(var key in options) {
                            var value = options[key];
                            var checked = '';
                            if(key == currentValue) {
                                checked = ' checked="checked"';
                            }
                            jelDependencyOptionsContainer.append(jQuery('<div><input type="radio" name="answer_' + questionId + '" value="'+key+'"'+checked+' /> '+value+'</div>'));
                        }
                        break;
            		case 'mmiDependentDialogTemplate_number':
                        //var jelDependencyOptionsContainer = jQuery('.answer_options_' + questionId);

                        var jelQuestionTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jQuery('#questionRow_'+questionId), 'field');

                        var currentAnswer = jQuery.genome('#formfielddependencies['+formItemId+']['+jelQuestionTypeField.val()+'][0][condition_answer]').val();
                        if(typeof(currentAnswer) == 'undefined') {
                            currentAnswer = '';
                        }
                        var currentModifier = jQuery.genome('#formfielddependencies['+formItemId+']['+jelQuestionTypeField.val()+'][0][condition_modifier]').val();
                        if(typeof(currentModifier) == 'undefined') {
                            currentModifier = '';
                        }

                        jQuery('#modifier_'+questionId).val(currentModifier);
                        var jelAnswerField = jQuery('#answer_'+questionId);
                        jelAnswerField.val(currentAnswer);
                        //jelAnswerField.bind('keypress', MMI.Util.Form.Field.FilterInput.number).bind('change', MMI.Util.Form.Field.SanitizeInput.number);
                        break;
            	}
            	
            	//populate with the current values
            	
            }
           //open a dialog with the form and load in the current values
            
        }
        ,_questionDependencyInsertOptionField: function(formItemId, questionId, subFieldName, fieldValue) {
            //                                                                       Multi/Option             |   True/False |   Text  |  Number
            // formfielddependencies[$form_id][$questionName][0][condition_answer]=  stringCheckedOptions     |   true/false |   N/A   |  value (#) in field
            // formfielddependencies[$form_id][$questionName][0][condition_modifier]=in                       |   =          |   N/A   |  >,<,>=,<=,=
            // formfielddependencies[$form_id][$questionName][0][condition_field]=   $questionParentFieldName
            // formfielddependencies[$form_id][$questionName][0][condition_isset]=   N/A                      |   N/A        |   true  | N/A

            var jelQuestionTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jQuery('#questionRow_'+questionId), 'field');
            var questionName = jelQuestionTypeField.val();
            var newFieldName = 'formfielddependencies['+formItemId+']['+questionName+'][0][condition_'+subFieldName+']';
            // questionDependencyRules_

            jQuery('<input type="hidden" id="'+newFieldName+'" name="'+newFieldName+'" value="'+fieldValue+'" />').appendTo('#questionDependencyRules_'+questionId);
           
        }
        ,_questionGetFormId: function(jelQuestionContainer){
        	//var questionItemId = jelQuestionContainer.attr('id').split('_')[1];
            var jelForm = jelQuestionContainer.parents('form:first');
            return jelForm.attr('id').split('_')[2];
        }
        ,_questionGetId: function(jelQuestionContainer) {
            return jelQuestionContainer.attr('id').split('_')[1];
        }
        ,_questionGetFieldFromContainer: function(jelContainer, subFieldName){
            if(typeof(jelContainer) != 'object') {
                return false;
            }
            var containerId = jelContainer.attr('id');
            if(typeof(containerId) == 'string') {
        	    var questionItemId = containerId.split('_')[1];
                var jelForm = jelContainer.parents('form:first');
                var formItemId = jelForm.attr('id').split('_')[2];
                return jQuery.genome('#formfield['+formItemId+']['+questionItemId+']['+subFieldName+']');
            }
            return false;
        }
        
        //Disable the type selector for a field when made a parent
        ,_questionDisableFieldType : function(jelQuestionContainer){
            // formfield[1381][66][edittype]
            var questionTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jelQuestionContainer, 'edittype');
            var questionTypeFieldParent = questionTypeField.parent();
            var newQuestionTypeField = jQuery('<input type="hidden" id="'+questionTypeField.attr('id')+'" name="'+questionTypeField.attr('id')+'" value="'+questionTypeField.val()+'" />');
            questionTypeField.each(function() {
                var jel = jQuery(this);
                if(this.tagName.toLowerCase() == 'input') {
                    jel.remove();
                } else {
                    jel.attr("disabled", 'disabled');
                }
            });
            newQuestionTypeField.appendTo(questionTypeFieldParent);
        }
		,_questionEnableFieldType : function(jelQuestionContainer){
            var questionTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jelQuestionContainer, 'edittype');
            //var questionTypeFieldParent = questionTypeField.parent();
            //var newQuestionTypeField = jQuery('<input type="hidden" name="'+questionTypeField.attr('id')+'" value="'+questionTypeField.val()+'" />');
            questionTypeField.each(function() {
                var jel = jQuery(this);
                if(this.tagName.toLowerCase() == 'input') {
                    jel.remove();
                } else {
                    jel.removeAttr("disabled", 'disabled');
                }
            });
		}
        ,questionDependencyAdd: function(questionId) {
            var jelQuestion = jQuery('#questionRow_' + questionId);
            if(!MMI.Form.Edit.questionCanBeDependent(questionId)) {
                // Attempt to open the dialog for editing the current dependency (only opens if it is dependent)
                if(!MMI.Form.Edit.questionIsDependent(questionId)) {
                    MMI.Util.alert('This question has dependent questions under it and cannot be made dependent on another question.', 'Add Dependency');
                } else {
                    MMI.Form.Edit.questionDependencyDialog(questionId);
                }
                return false;
            }
           
            var jelPreviousQuestion = MMI.Form.Edit.questionDependencyGetPreviousQuestionContainer(questionId);
            var deps = jQuery('.questionDependents:first', jelPreviousQuestion);
            jelQuestion.detach().appendTo(deps);
            
            // Disable options on the parent
            MMI.Form.Edit._questionDisableFieldType(jelPreviousQuestion);
            MMI.Form.Edit._questionMakeSortableLists();
            
            MMI.Form.Edit.questionDependencyDialog(questionId);
        }
        ,questionDependencyRemove: function(questionId) {
            // If this question is not dependent then do not try to remove it
            if(!MMI.Form.Edit.questionIsDependent(questionId)) {
                return false;
            }

            var jelQuestion = jQuery('#questionRow_' + questionId);
            var jelParentQuestion = MMI.Form.Edit.questionDependentGetParentContainer(questionId);

            // Move the question out of the dependents list and into the main/root list of questions below the question that it was dependent on.
            jelQuestion.detach().insertAfter(jelParentQuestion);

            // 
            var parentQuestionItemId = jelParentQuestion.attr('id').split('_')[1];
            if(!MMI.Form.Edit.questionHasDependents(parentQuestionItemId)){
                MMI.Form.Edit._questionEnableFieldType(jelParentQuestion);
            }
            // Reset sortables and recalculate sort order.
            MMI.Form.Edit._questionMakeSortableLists();
            
            //force update
            var questionItemId = MMI.Form.Edit._questionGetId(jelQuestion);
            var jelForm = jelQuestion.closest('form');
            var formItemId = jelForm.attr('id').split('_')[2];
            var jelNameField = jQuery.genome('#formfield['+formItemId+']['+questionItemId+'][name]');
            jelNameField.change();
        }
        ,questionDependencyGetPreviousQuestionContainer: function(questionId) {
            var jelQuestion = jQuery('#questionRow_' + questionId);
            var jelQuestionParent = jelQuestion.parent();
            var questions = jQuery('#' + jelQuestionParent.attr('id') + ' > .mmi_question');
            var previousQuestion = false;
            questions.each(function() {
                var jel = jQuery(this);
                if(jelQuestion.attr('id') == jel.attr('id')) {
                    return false;
                }
                previousQuestion = jel;
            });
            return previousQuestion;
        }
        ,questionIsDependent: function(questionId) {
            var val = false;
            var jelQuestion = jQuery('#questionRow_' + questionId);
            if(jelQuestion.parent().hasClass('questionDependents')) {
                val = true;
            }
            return val;
        }
        ,questionHasDependents: function(questionId) {
            var jelQuestionDeps = jQuery('#questionDependents_' + questionId + ' .mmi_question');
            var val = (jelQuestionDeps.size() > 0);
            return val;
        }
        ,questionCanBeDependent: function(questionId) {
        	var jelPreviousQuestion = MMI.Form.Edit.questionDependencyGetPreviousQuestionContainer(questionId);
            if(!jelPreviousQuestion) {
                return false;
            }
        	var jelTypeField = MMI.Form.Edit._questionGetFieldFromContainer(jelPreviousQuestion, 'edittype');
        	var formFieldType = jelTypeField.val();
        	switch(formFieldType){
            	case 'date' :
            	case 'datetime' :
            	case 'label' :
        	    case 'assoc' :
        	    case 'color' :
        		    return false;
        		    break;
        	    default :
        		    break;
        	}
            //var jelQuestion = jQuery('#questionRow_' + questionId);
            if(!MMI.Form.Edit.questionIsDependent(questionId) && !MMI.Form.Edit.questionHasDependents(questionId) && MMI.Form.Edit.questionDependencyGetPreviousQuestionContainer(questionId) !== false) {
                return true;
            }
            return false;
        }
        // Get and return the primary container for the parent question
        ,questionDependentGetParentContainer : function(questionId){
        	var jelQuestion = jQuery('#questionRow_' + questionId);
        	var jelParentQuestion = jelQuestion.parents('.mmi_question:first');
        	return jelParentQuestion;
        }
	};
} else {
	throw(MMI.Exception('Ln_ClassMaker JavaScript class is not available.', 0));
}
