var init = false; //var saveDraft = false; var validate = true; var formChanged = false; var changeSection = false; var formSaved = false; var autosaveFlag = 'n'; var targetMenu; var saveButton = false; var firstSave = false; var loock var cancelUnlock = false; function initList() { $('.saved').each(function(){ var list = this; $(list).parent().find('a[id*=list]').click(function(){ if ($(list).css('display') == 'none'){ $(this).parent().addClass('active'); $(list).slideDown(); } else { $(this).parent().removeClass('active'); $(list).slideUp(); } }); }); var id_hash = window.location.hash; if (id_hash){ $('a#list_'+id_hash.split('#').join('')).click(); } $('.percent').each(function(){ var value = $(this).text(); $(this).progressBar(value, { width: 120, barImage: { 1: 'images/progress/progressbg_red.gif', 30: 'images/progress/progressbg_yellow.gif', 70: 'images/progress/progressbg_green.gif' }, boxImage: 'images/progress/progressbar.gif' }); }) } /*function setSaveDraft() { saveDraft = true; }*/ /*function redirectFrame() { //alert('redirect'); window.parent.location.href=window.location.href; }*/ /** * Fix change event for radio and checkbox in ie */ function ieEventFix() { if ($.browser.msie){ $("input[type=radio], input[type=checkbox]").click(function(){ this.blur(); this.focus(); }) } } function unloadEvent() { Qs_Form.onUnlockQuestionnaire($('form'), function(){ self.close(); }); } function initIndex(initForm) { ieEventFix(); window.onbeforeunload = function(e) { showQuestionnaireStatus(); e = e || window.event; var message = "Please make sure to use \"Back\" link or \"Finish\" button to finish \n" + "editing current questionnaire correctly and leave this page, otherwise \n" + "questionnaire will be locked for a short amount of time to avoid mid-air collisions"; // For IE and Firefox if (formChanged && e) { e.returnValue = message; return message; } if (!cancelUnlock){ unloadEvent(); } } $('#coda-slider-1').codaSlider({ dynamicArrows: false }); $('#coda-nav-1').prepend('
Progress
'); targetMenu = jQuery('a.xtrig', jQuery('#navigation')); var targetNav = jQuery('a.xtrig', jQuery('.panel_inside_nav')); var targetCodaNav = jQuery('a', jQuery('#coda-nav-1')); var id_hash = window.location.hash; targetCodaNav.attr('href', '#'); targetNav.each( function(){ $(this).attr({id: 'nav' + $(this).attr('href').split('#').join('_')}); $(this).attr('href', '#') }) targetNav.click(function() { var id_menu = $(this).attr('id').substring(4, $(this).attr('id').length); if (validate){ Qs_Form.validateSection(parseInt($('#navigation').find('.active').attr('id').replace('menu_', ''))-1, '#menu_' + id_menu, targetMenu); } return false; }); targetMenu.click(function() { if (validate){ Qs_Form.validateSection(parseInt($('#navigation').find('.active').attr('id').replace('menu_', ''))-1, this, targetMenu); } return false; }); targetCodaNav.click(function() { var id_menu = $(this).parent('li').attr('class').substring(3, $(this).parent('li').attr('class').length); if (validate){ Qs_Form.validateSection(parseInt($('#navigation').find('.active').attr('id').replace('menu_', ''))-1, '#menu_' + id_menu, targetMenu); } return false; }); $('#menu_' + id_hash.split('#').join('')).toggleClass('active'); if (id_hash == '') { $('#menu_1').toggleClass('active'); } $('.nav_finish').unbind('click').click( function (){ Qs_Form.onSubmit(document.index_form); return false; } ); jQuery.extend(Qs_Form, FormExtend); if (initForm){ Qs_Form.init('index-form', Qs_Form.options); } $('input, textarea, select').change(function(){ if (formChanged != true && !init){ formChanged = true; changeSection = true; showQuestionnaireStatus(); } }); showQuestionnaireStatus(); initLableClick(); fixPhoneElement(); } function fixPhoneElement() { Qs_Form_Element_PhoneFix.parenFormatReal = Qs_Form_Element_Phone.formatReal; $.extend(Qs_Form_Element_Phone, Qs_Form_Element_PhoneFix); } /** * Fix change event for phone element */ var Qs_Form_Element_PhoneFix = { parenFormatReal: null, formatReal: function () { if (this.parenFormatReal) { this.parenFormatReal(); $(this.element).change(); } } } function onBlurElements() { $('input, textarea, select').blur(); } function initLableClick() { $("div[id*='-element']").children('.optional, .required').css('cursor', 'pointer').click(function(){ $(this).parent().find("[name*='field_']:first").putCursorAtEnd(); }); } function setFormSaved() { formSaved = true; } function lockQuestionnaire() { if ($('#action').val() == 'update'){ lockQuestionnaireRequest(true); setInterval(function(){ lockQuestionnaireRequest(); }, 300000); } } function lockQuestionnaireRequest(firstLock) { var options = { url: $('#index-form').attr('action'), type: 'POST', dataType: 'json', data: { action: 'lockQuestionnaire', id: $('#id').val(), firstLock: (firstLock?firstLock:false) }, success: function (data) { if (!data.success){ cancelUnlock = true; //window.parent.location.href = BASE_URL; } } } $.ajax(options); } function verifyQuestionnairesLock(questionnairesId) { verifyQuestionnairesRequest(questionnairesId); setInterval(function(){ verifyQuestionnairesRequest(questionnairesId); }, 100000); } function verifyQuestionnairesRequest(questionnairesId) { var options = { url: $('#index_form').attr('action'), type: 'POST', dataType: 'json', data: { action: 'verifyQuestionnairesLock', 'questionnaires[]': questionnairesId }, success: function (data) { if (data){ for (var key in data){ var link = $('#' + key + '_percent').parent().children('a:first'); var delLink = $('#' + key + '_percent').parent().children('a:last'); var printLink = $('#' + key + '_print'); if (data[key] == true){ link.click(function(){ return false; }); if (!link.next('.locked').size()){ link.after(' This questionnaire is locked, because it\'s editing by another user now.'); } delLink.hide(); printLink.hide(); } else { link.unbind('click').next('.locked').remove(); delLink.show(); printLink.show(); } } } } } $.ajax(options); } function showQuestionnaireStatus() { var status = ''; if (autosaveFlag == false && formChanged && !formSaved){ status = ' Questionnaire is not yet saved'; } else if (!formSaved){ status = ' Questionnaire is not complete'; } else if (formSaved && formChanged){ status = ' Questionnaire has been modified' } else if (!formChanged && formSaved && !firstSave){ status = ''; } else if (formSaved){ status = ' Questionnaire has been saved'; $('.nav_finish').css('display', ''); } else { status = ' N/A'; } $('.questionnaire_status').remove(); if (status == ''){ return false; } var activeSection = parseInt($('#navigation').find('a.active').attr('id').replace('menu_', '')) - 1; var statusHtml = '
' + status; var currentSection = $('.quest_page.panel:eq(' + activeSection + ')'); var lastSection = $('.quest_page.panel:last'); if ((autosaveFlag == false && formChanged && currentSection.attr('id') != lastSection.attr('id')) || (formSaved && formChanged && (currentSection.attr('id') != lastSection.attr('id')))){ statusHtml += '
Save Questionnaire'; } statusHtml += '
'; $('#coda-nav-1').append(statusHtml); $('#status_save_link').click(function(){ saveButton = true; Qs_Form.validateSection(parseInt($('#navigation').find('.active').attr('id').replace('menu_', ''))-1, '#' + $('#navigation').find('.active').attr('id'), targetMenu); }); window.scroll(0,0); return true; } /*function navClick(data) { }*/ var FormExtend = { saveCallback: null, /*onSubmitDraft: function (form) { var submit = false; var formValue = $(form).serializeArray(); for (var key in formValue){ if (formValue[key]['name'] == 'action'){ formValue[key]['value'] = 'saveDraft'; } else if (formValue[key]['name'] != 'idShema' && $("select[name='"+formValue[key]['name']+"']").size() == 0) { if (formValue[key]['value']){ submit = true; } } } var activeMenu = new Object(); activeMenu.name = 'activeMenu'; activeMenu.value = $('a.active').attr('id').split('_')[1]; formValue.push(activeMenu); var options = { url: $(form).attr('action'), type: 'POST', dataType: 'json', data: formValue, success: function (data) { //vdie(data); if (data.id){ $(form).append(''); } $.unblockUI(); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Error saving questionnaire. Please reload page.') } } if (submit){ $.blockUI({css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff' }}); $.ajax(options); } },*/ onSubmitSuccess: function (response, form) { var id = $(form).attr('id'); Qs_Form.setFormOption(id, 'response', response) if (response.isValid) { if (form) { var onSuccessCallback = Qs_Form.getFormOption($(form).attr('id'), 'onSuccessCallback'); if (typeof onSuccessCallback == 'undefined') { Qs_Form.onUnlockQuestionnaire(form, function(){ formChanged = false; form.submit(); }); //form.submit(); /*var options = { url: $(form).attr('action'), type: 'POST', dataType: 'json', data: Qs_Form.toObject(form), success: function (data) { //alert($data); } }; $.ajax(options);*/ } else { Qs_Form.callExternal(onSuccessCallback); } } } else { var onErrorCallback = Qs_Form.getFormOption($(form).attr('id'), 'onErrorCallback'); if (typeof onErrorCallback != 'undefined') { Qs_Form.callExternal(onErrorCallback); return true; } Qs_Form.displayErrors(id); } return response; }, onUnlockQuestionnaire: function(form, callback, confirmBeforeUnlock) { if (confirmBeforeUnlock == true && formChanged){ this.showUnlockConfirm(form, callback); return true; } if (typeof($('#id').val()) != 'undefined'){ var options = { url: $(form).attr('action'), type: 'POST', dataType: 'json', data: { action: 'unlockQuestionnaire', id: $('#id').val() }, success: function (data) { if (callback){ callback(); } } } $.ajax(options); } else { callback(); } return true }, showUnlockConfirm: function(form, callback) { var html = $('
'); html.append('

Questionnaire was modified, do you want to save changes ?

'); html.append(' '); html.append(' '); html.append(' '); $.blockUI({message: html, css: {width: '450px'}}); $('#cancel').click(function(){ $.unblockUI(); }); $('#no_save').click(function(){ $.unblockUI({onUnblock: function(){ formChanged = false; Qs_Form.onUnlockQuestionnaire(form, callback); } }); }); $('#save').click(function(){ $.unblockUI({onUnblock: function(){ Qs_Form.saveCallback = function(){ Qs_Form.onUnlockQuestionnaire(form, callback); } saveButton = true; autosaveFlag = 'y'; Qs_Form.validateSection(parseInt($('#navigation').find('.active').attr('id').replace('menu_', ''))-1, '#' + $('#navigation').find('.active').attr('id'), targetMenu); } }); }); }, onSectionSubmitSuccess: function (response, form) { var id = $(form).attr('id'); Qs_Form.setFormOption(id, 'response', response) if (response.isValid) { if (form) { var onSuccessCallback = Qs_Form.getFormOption($(form).attr('id'), 'onSuccessCallback'); if (typeof onSuccessCallback != 'undefined') { Qs_Form.callExternal(onSectionSuccessCallback); } } } else { var onErrorCallback = Qs_Form.getFormOption($(form).attr('id'), 'onErrorCallback'); if (typeof onErrorCallback != 'undefined') { Qs_Form.callExternal(onErrorCallback); return true; } Qs_Form.displaySectionErrors(id); } return response; }, validateSection: function (section, element, elementGroups) { var form = $('form'); var idForm = $(form).attr('id'); var formValues = new Array(); formValues = $('.quest_page.panel:eq(' + section + ') *').serializeArray(); var newKey = formValues.length; formValues[newKey] = new Object(); formValues[newKey]['name'] = 'action'; formValues[newKey]['value'] = 'validateSection'; newKey = formValues.length; formValues[newKey] = new Object(); formValues[newKey]['name'] = 'idShema'; formValues[newKey]['value'] = $('#idShema').val(); //vdie(Qs_Form.toObject(document.index_form)); var formAllValues = form.serializeArray(); var formAllNewValues = new Array(); for (var key in formAllValues){ var formNewValues = new Object(); formNewValues['name'] = 'formValues[' + formAllValues[key]['name'] + ']'; formNewValues['value'] = formAllValues[key]['value']; formValues.push(formNewValues); } Qs_Form.removeElementsErrors(form); Qs_Form.formOptions[idForm]['processRequest'] = true; var options = { url: $(form).attr('action'), type: 'POST', dataType: 'json', //data: $('.quest_page.panel:eq(' + section + ') *').serialize() + '&action=validateSection&idShema=' + $('#idShema').val(), data: formValues, success: function (data) { if (changeSection){ $('#menu_' + (section+1)).html($('#menu_' + (section+1)).text() + ''); changeSection = false; } var response = Qs_Form.onSectionSubmitSuccess(data, form); if (response.isValid){ Qs_Form.saveData(document.index_form, element, elementGroups, response.validForm); } }, error: Qs_Form.onSubmitError, complete: function (XMLHttpRequest, textStatus) { Qs_Form.onSubmitComplete(XMLHttpRequest, textStatus, form) } }; $.ajax(options); }, saveData: function (form, element, elementGroups, saveFlag) { if (saveFlag && formChanged){ if (autosaveFlag == 'n'){ var question = $('
'); if (saveButton){ question.append('

Do you want to save changes automatically?

'); } else { question.append('

Questionnaire has been changed and not saved yet.
Do you want to save changes automatically?

'); } question.append(' '); question.append(' '); $.blockUI({message: question, css: {width: '400px'}}); $('#yes').click(function() { autosaveFlag = true; Qs_Form.saveAction(form, element, elementGroups); }); $('#no').click(function() { autosaveFlag = false; $.unblockUI({onUnblock: function(){ Qs_Form.chanageSectionAction(element, elementGroups); if (saveButton){ Qs_Form.saveAction(form, element, elementGroups); } } }); return false; }); } else if (saveButton == true || autosaveFlag == true){ Qs_Form.saveAction(form, element, elementGroups); saveButton = false; } else { Qs_Form.chanageSectionAction(element, elementGroups); } } else { Qs_Form.chanageSectionAction(element, elementGroups); } }, saveAction: function(form, element, elementGroups) { $('.section_changed').remove(); $.blockUI({message: '

Please wait, data saving is in progress...

'}); var formValue = $(form).serializeArray(); for (var key in formValue){ if (formValue[key]['name'] == 'action'){ var newKey = formValue.length; formValue[newKey] = new Object(); formValue[newKey]['name'] = 'formAction'; formValue[newKey]['value'] = formValue[key]['value']; formValue[key]['value'] = 'saveData'; } } var options = { url: $(form).attr('action'), type: 'POST', dataType: 'json', data: formValue, success: function (data) { if (parseInt(data.id) > 0){ $(form).append(''); $('#action').val('update'); $('.disabled_element').find('input,textarea,select').attr('disabled', 'disabled'); $('.disabled_element').find('label').removeClass('required'); } $.unblockUI({ onUnblock: function(){ //$.growlUI('INFORMATION', 'Questionnaire has been saved!'); if (!formSaved){ lockQuestionnaire(); } setFormSaved(); firstSave = true; formChanged = false; Qs_Form.chanageSectionAction(element, elementGroups); if (Qs_Form.saveCallback){ Qs_Form.saveCallback(); Qs_Form.saveCallback = null; } } }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Error saving questionnaire. Please reload page.') } } $.ajax(options); }, chanageSectionAction: function(element, elementGroups) { elementGroups.attr('class', 'xtrig'); $(element).toggleClass('active'); validate = false; $(element).attr('href', '#' + $('#navigation').find('.active').attr('id').replace('menu_', '')) .click() .attr('href', '#'); validate = true; showQuestionnaireStatus(); }, displaySectionErrors: function (id) { var response = Qs_Form.getFormOption(id, 'response'); var form = document.getElementById(id); var displayMethod = Qs_Form.getErrorDisplayMethod(id); switch (displayMethod) { case 'ALERT': var message = Qs_Form.message.get('invalidInformationEntered') + '\n'; message += Qs_Form.prepareErrorsAlert(response.errors, response.elements); message += '\n\n' + Qs_Form.message.get('pleaseCorrectTheseFields'); var name = array_key(response.errors); if (form[name] && form[name].focus) { form[name].focus(); } else if (form[name + '[input]'] && form[name + '[input]'].focus) { // встановлення фокуса для каптчі form[name + '[input]'].focus(); } $.scrollTo('#' + name + '-label'); alert(message); break; case 'HTML': Qs_Form.displayErrorsHtml(form, response.errors); var name = array_key(response.errors); var focusKey = null; if (form[name] && form[name].focus) { focusKey = name; } else if (form[name + '[input]'] && form[name + '[input]'].focus) { // встановлення фокуса для каптчі focusKey = name + '[input]'; } if (focusKey != null) { if ($('[name="' + focusKey + '"]:visible', form).size()) { form[focusKey].focus(); } } var formPrependId = Qs_Form.getFormOption(id, 'prependId'); if (formPrependId) { name = id + '-' + name; } break; default: alert('Qs_Form. Unknown errorDisplayMethod "' + displayMethod + '"'); } if (typeof response.captcha == 'object' && response.captcha != null) { for (var name in response.captcha) { var captcha = $('#' + name + '-element'); if ($(captcha).size() != 0) { $('img:first', captcha).attr('src', response.captcha[name].src); $('#' + name + '-id', captcha).attr('value', response.captcha[name].id); $('#' + name + '-input', captcha).attr('value', ''); if (typeof response.captcha[name].href != 'undefined') { $('a.captcha_refresh', captcha).attr('href', response.captcha[name].href); } } } } }, displayErrors: function (id) { var response = Qs_Form.getFormOption(id, 'response'); var form = document.getElementById(id); var displayMethod = Qs_Form.getErrorDisplayMethod(id); switch (displayMethod) { case 'ALERT': var message = Qs_Form.message.get('invalidInformationEntered') + '\n'; message += Qs_Form.prepareErrorsAlert(response.errors, response.elements); message += '\n\n' + Qs_Form.message.get('pleaseCorrectTheseFields'); var name = array_key(response.errors); if (form[name] && form[name].focus) { form[name].focus(); } else if (form[name + '[input]'] && form[name + '[input]'].focus) { // встановлення фокуса для каптчі form[name + '[input]'].focus(); } $.scrollTo('#' + name + '-label'); alert(message); break; case 'HTML': Qs_Form.displayErrorsHtml(form, response.errors); var name = array_key(response.errors); var focusKey = null; if (form[name] && form[name].focus) { focusKey = name; } else if (form[name + '[input]'] && form[name + '[input]'].focus) { // встановлення фокуса для каптчі focusKey = name + '[input]'; } if (focusKey != null) { if ($('[name="' + focusKey + '"]:visible', form).size()) { form[focusKey].focus(); } } var formPrependId = Qs_Form.getFormOption(id, 'prependId'); if (formPrependId) { name = id + '-' + name; } var section = 1; var exit = false; $(".quest_page").each(function(){ if ($(this).find('ul.errors').size() > 0){ $('#menu_'+section).click(); exit = true; return false; } if (exit){ return false; } section++; }); /*$.scrollTo('#' + name + '-label'); alert( Qs_Form.message.get('invalidInformationEntered') + '\n' + Qs_Form.message.get('pleaseCorrectTheseFields') );*/ break; default: alert('Qs_Form. Unknown errorDisplayMethod "' + displayMethod + '"'); } if (typeof response.captcha == 'object' && response.captcha != null) { for (var name in response.captcha) { var captcha = $('#' + name + '-element'); if ($(captcha).size() != 0) { $('img:first', captcha).attr('src', response.captcha[name].src); $('#' + name + '-id', captcha).attr('value', response.captcha[name].id); $('#' + name + '-input', captcha).attr('value', ''); if (typeof response.captcha[name].href != 'undefined') { $('a.captcha_refresh', captcha).attr('href', response.captcha[name].href); } } } } } } function changeRule(fieldsArray, element) { var fields = new Object(fieldsArray); if (!init && $(element).attr('type') != 'checkbox'){ hideAllField(fields); } else if(!init && $(element).attr('type') == 'checkbox'){ changeCheckboxRule(fields, element); } else { initValueRecursive(fields); } if (fields[element.value] && $(element).attr('checked')){ for (var key in fields[element.value]){ $('#field_' + fields[element.value][key] + '-element,#field_' + fields[element.value][key] + '-label, #field_' + fields[element.value][key]).show(250).removeAttr('disabled'); $('input[id*=field_'+ fields[element.value][key]+']').removeAttr('disabled'); } } } function changeCheckboxRule(fields, element) { var id = $(element).attr('id').split('-'); for (var key in fields){ for(var subKey in fields[key]){ if (!$('#' + id[0] + '-' + key).attr('checked')){ $('#field_'+fields[key][subKey]).attr('disabled', 'disabled'); $('input[id*=field_'+ fields[key][subKey]+']').attr('disabled', 'disabled').removeAttr('checked').change(); $('#field_'+fields[key][subKey] + '-element,#field_'+fields[key][subKey] + '-label,p#field_' + fields[key][subKey]).css('display', 'none'); } } } } function initValueRecursive(fields) { for (var key in fields){ for(var subKey in fields[key]){ $('input[name=field_'+fields[key][subKey]+']').change(); } } } function hideAllField(fields) { for (var key in fields){ for(var subKey in fields[key]){ $('input[name=field_'+fields[key][subKey]+'], input[name="field_'+fields[key][subKey]+'[]"]').removeAttr("checked").change(); $('input[id*=field_'+ fields[key][subKey]+']').attr('disabled', 'disabled'); $('#field_' + fields[key][subKey]).attr('disabled', 'disabled'); $('#field_' + fields[key][subKey] + '-element, #field_' + fields[key][subKey] + '-label').hide(); } } } function initHiddenElements(params) { init = true; for (var key in params){ $('#' + params[key]).attr('disabled', 'disabled'); $('#' + params[key] + '-element, #' + params[key] + '-label, p#' + params[key]).hide(); $('#' + params[key] + '-element').parent().find('input:checked').change(); } init = false; formChanged = false; changeSection = false; }