(function(){var ft="ui-icon-pencil",ut="ui-icon-search",ot="ui-icon-add",et="ui-icon-minusthick",rt="ui-icon-link",nt="ui-icon-trash",g="ui-icon-save",it="ui-icon-circle-minus",tt="ui-icon-wrench",st="ui-icon-triangle-1-s",pt="ui-icon-triangle-1-n",yt="ui-icon-triangle-2-n-s",bt="ui-icon-arrowthickstop-1-s",wt="ui-icon-arrowthickstop-1-n",vt="ui-icon-check",ct="ui-icon-print",ht="ui-icon-circle-triangle-w",at="ui-icon-circle-triangle-e",lt="ui-icon-circle-triangle-n",h="ui-icon-alert",s="ui-icon-help",l="ui-icon-note",c="ui-icon-folder-open",f="ui-icon-clock",u="ui-icon-copy",o="ui-icon-newwin",e="ui-icon-cart",b="ui-icon-refresh",w="ui-icon-calculator",d="ui-icon-lightbulb",k="ui-icon-pin-s",v="ui-icon-mail-closed",a="ui-icon-locked",p="ui-icon-unlocked",y="ui-icon-arrowreturnthick-1-w",t=null,r=0,n=null,dt=0,kt=!1;($(function(){var e,o,r,i,n;const f=function(n){var i=n.hasMissingAnswers,t=n.inspection;return i?(alert("There are missing required questions on this inspection, cannot complete."),$.unblockUI()):(t.completed=moment(new Date).format(),t.isInProgress=!1,t.isComplete=!0,t.isDirty=!0,app.persist.putInspection(t,function(){app.persist.syncChanges(function(){window.location=app.vroot()+"Inspection/"})})),Promise.resolve()},u=function(n){var i=n.hasMissingAnswers,t=n.inspection;return i?(alert("There are missing required questions on this inspection, cannot complete."),$.unblockUI()):(t.completed=moment(new Date).format(),t.isInProgress=!1,t.isComplete=!0,t.isDirty=!0,app.persist.putInspection(t,function(){app.persist.syncChanges(function(){window.location=app.vroot()+"Inspection/ReviewList/"})})),Promise.resolve()};$("#CompleteInspection").button();$("#CompleteInspection").on("click",function(){if(confirm("Mark Inspection as complete?")){$.blockUI({message:"<h1>Please Wait...<\/h1>"});var n=Wndsr.getUrlParam("inspectionId"),t=Wndsr.getUrlParam("review");t==="true"?app.persist.getInspection(n,function(n){if(console.log(n),n.isConflict){alert("This inspection has a conflict, you must resolve the conflict and synchronize before completing the inspection");return}var t=null;app.persist.getSites(function(i){t=i?i:[];var r=t.find(function(t){return t.id===n.siteId});if($("#RequireSiteKeyForCompleteInspeciton").val()==="True"&&(r===undefined||r.siteKey===null||r.siteKey===undefined||r.siteKey==="")){alert($("#SiteKeyLabel").val()+" is required to complete an inspection"),$.unblockUI();return}appPersistInspectionHasMissingAnswers(n).then(u)})},function(){alert("Failed getting inspection to complete"),$.unblockUI()}):app.persist.getInspections(function(t){var r=t.find(function(t){return t.id===n}),i;if(r){if(r.isConflict){alert("This inspection has a conflict, you must resolve the conflict and synchronize before completing the inspection");return}i=null,app.persist.getSites(function(n){i=n?n:[];var t=i.find(function(n){return n.id===r.siteId});if($("#RequireSiteKeyForCompleteInspeciton").val()==="True"&&(t===undefined||t.siteKey===null||t.siteKey===undefined||t.siteKey==="")){alert($("#SiteKeyLabel").val()+" is required to complete an inspection"),$.unblockUI();return}appPersistInspectionHasMissingAnswers(r).then(f)})}else app.persist.getInspection(n,function(n){if(console.log(n),n.isConflict){alert("This inspection has a conflict, you must resolve the conflict and synchronize before completing the inspection");return}var t=null;app.persist.getSites(function(i){t=i?i:[];var r=t.find(function(t){return t.id===n.siteId});if($("#RequireSiteKeyForCompleteInspeciton").val()==="True"&&(r===undefined||r.siteKey===null||r.siteKey===undefined||r.siteKey==="")){alert($("#SiteKeyLabel").val()+" is required to complete an inspection"),$.unblockUI();return}appPersistInspectionHasMissingAnswers(n).then(u)})},function(){alert("Failed getting inspection to complete"),$.unblockUI()})})}else $.unblockUI()});$("html").on("syncStart",function(){$(".transferStatus-heading").html("Preparing Synchronization"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep),$("#SyncDialog").dialog("open")});$("html").on("beginRequestSync",function(){$(".transferStatus-heading").html("Requesting Sync from the server"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("prepareSyncStart",function(){$(".transferStatus-heading").html("Preparing Upload"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadInspections",function(){$(".transferStatus-heading").html("Uploading Inspections"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadInspectionCmeValues",function(){$(".transferStatus-heading").html("Uploading Inspection Cme Values"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadInspectionForms",function(){$(".transferStatus-heading").html("Uploading Inspection Forms"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadInspectionFormSections",function(){$(".transferStatus-heading").html("Uploading Inspection Form Sections"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadInspectionFormRepeatingSections",function(){$(".transferStatus-heading").html("Uploading Inspection Form Repeating Sections"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadInspectionFormAnswers",function(){$(".transferStatus-heading").html("Uploading Inspection Form Answers"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadInspectionFormMedias",function(){$(".transferStatus-heading").html("Uploading Inspection Form Medias"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadSites",function(){$(".transferStatus-heading").html("Uploading Sites"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadSiteAddresses",function(){$(".transferStatus-heading").html("Uploading Site Addresses"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadProjects",function(){$(".transferStatus-heading").html("Uploading Projects"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startProcessUpload",function(){$(".transferStatus-heading").html("Processing Upload"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspections",function(){$(".transferStatus-heading").html("Downloading Inspections"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspectionCmeValues",function(){$(".transferStatus-heading").html("Downloading Inspection Cne Values"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspectionForms",function(){$(".transferStatus-heading").html("Downloading Inspection Forms"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspectionFormSections",function(){$(".transferStatus-heading").html("Downloading Inspection Form Sections"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspectionFormRepeatingSections",function(){$(".transferStatus-heading").html("Downloading Inspection Form Repeating Sections"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspectionFormAnswers",function(){$(".transferStatus-heading").html("Downloading Inspection Form Answers"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspectionFormMedias",function(){$(".transferStatus-heading").html("Downloading Inspection Form Medias"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadImage",function(){$(".transferStatus-heading").html("Downloading Image "+app.synchronize.currentImage+" of "+app.synchronize.totalImages),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startUploadImage",function(){$(".transferStatus-heading").html("Uploading Image "+app.synchronize.currentUploadImage+" of "+app.synchronize.totalUploadImages),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadSites",function(){$(".transferStatus-heading").html("Downloading Sites"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadSiteAddresses",function(){$(".transferStatus-heading").html("Downloading Site Addresses"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadPrincipals",function(){$(".transferStatus-heading").html("Downloading Principals"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadProjects",function(){$(".transferStatus-heading").html("Downloading Projects"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadAutoAssignForms",function(){$(".transferStatus-heading").html("Downloading Auto Assign Forms"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadGroups",function(){$(".transferStatus-heading").html("Downloading Groups"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadRoles",function(){$(".transferStatus-heading").html("Downloading Roles"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadGroupRoles",function(){$(".transferStatus-heading").html("Downloading Group Roles"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadOrganizations",function(){$(".transferStatus-heading").html("Downloading Organizations"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadOrgGroups",function(){$(".transferStatus-heading").html("Downloading Organization Groups"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadInspectionTypes",function(){$(".transferStatus-heading").html("Downloading Inspection Types"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadOrgInspectionTypes",function(){$(".transferStatus-heading").html("Downloading Organization Inspection Types"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadForms",function(){$(".transferStatus-heading").html("Downloading Forms"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadFormVersions",function(){$(".transferStatus-heading").html("Downloading Form Versions"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadFormSections",function(){$(".transferStatus-heading").html("Downloading Sections"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startDownloadFormControls",function(){$(".transferStatus-heading").html("Downloading Form Controls"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("startFinishSync",function(){$(".transferStatus-heading").html("Finishing Synchronization"),$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep)});$("html").on("synchronizeComplete",function(){$("#uploadProgress").attr("max",app.synchronize.totalSteps),$("#uploadProgress").val(app.synchronize.currentStep),$("#SyncDialog").dialog("close")});$("html").on("prepareSyncSuccess",function(){var n=app.synchronize.dirtyInspectionCount+app.synchronize.dirtyInspectionFormCount+app.synchronize.dirtyInspectionFormMediaCount;n===0?($("#uploadProgress").attr("max",1),$("#uploadProgress").val(1)):($("#uploadProgress").attr("max",n),$("#uploadProgress").val(0)),$(".transferStatus-heading").html("Uploading Data (0 of "+n+")")});$("html").on("uploadDataSuccess",function(){$(".transferStatus-heading").html("Preparing to download data"),$("#uploadProgress").attr("max",1),$("#uploadProgress").val(1)});$("html").on("prepareDownloadSuccess",function(){var n=app.synchronize.totalTirdty;n===0?($("#uploadProgress").attr("max",1),$("#uploadProgress").val(1)):($("#uploadProgress").attr("max",n),$("#uploadProgress").val(0)),$(".transferStatus-heading").html("Downloading Data (0 of "+n+")")});$("html").on("downloadItemComplete",function(){var n=$("#uploadProgress").val()+1,t=app.synchronize.totalTirdty;$("#uploadProgress").val(n),$(".transferStatus-heading").html("Downloading Data ("+n+" of "+t+")")});$("html").on("uploadDataItemSuccess",function(){var t=$("#uploadProgress").val()+1,n=app.synchronize.dirtyInspectionCount+app.synchronize.dirtyInspectionFormCount+app.synchronize.dirtyInspectionFormMediaCount;n===0?($("#uploadProgress").attr("max",1),$("#uploadProgress").val(1)):($("#uploadProgress").attr("max",n),$("#uploadProgress").val(t)),$(".transferStatus-heading").html("Uploading Data ("+t+" of "+n+")")});if(e=function(){alert("Failed getting inspection to complete"),$.unblockUI(),Wndsr.error("GetInspection Failed - complete")},o=function(n){if(!n){showMapFailed();return}Wndsr.info("Request inspection Success - complete"),app.validateInspection(n,function(t){t?(n.completed=moment(new Date).format(),n.isInProgress=!1,n.isComplete=!0,app.updateInspection(n,function(){window.location=app.vroot()+"Inspection/"},function(){alert("Failed Completing inspection"),$.unblockUI()})):(alert("You must answer all required questions before you can mark an inspection complete."),$.unblockUI())})},$("#Support .toggler").click(function(){$.trim($(this).text())==="Close"?($("#Support .content").hide(),$(this).text("Open")):($("#Support .content").show(),$(this).text("Close"))}),$("button").live("click",function(){var n=$(this);n.addClass("ui-active"),setTimeout(function(){n.removeClass("ui-active")},500)}),r=function(){$("form[method='DELETE'], form[method='PUT']").each(function(){var n=$(this),t=n.attr("method");n.attr("method","post").prepend('<input type="hidden" name="_method" value="'+t+'" />')})},app.principal=Wndsr.getLocalStorage("principal"),window.location.href.toUpperCase().indexOf("STATUSPAGE")<0&&window.location.href.toUpperCase().indexOf("DUMPDATA")<0&&window.location.href.toUpperCase().indexOf("LOADDATA")<0&&window.location.href.toUpperCase().indexOf("LOADDEBUGDATA")<0&&window.location.href.toUpperCase().indexOf("PREPIPAD")<0&&(app.principal===null?($("#InspectorName").text(""),$("#LoggedInUser").text(""),$("#LogoutLink").removeClass("ui-icon-logout"),$("#LogoutLink").addClass("ui-icon-login"),$("#LogoutLink").attr("title","Logon"),window.location.href.indexOf(app.vroot()+"Inspection/")<0&&window.location.href.indexOf(app.vroot()+"Logon/")<0?window.location=app.vroot()+"Inspection/":(i=$("#LoginUrl").val(),i!==""?app.getPrincipal(function(n){n.successful?n.isExpired?($("#LogonForm").dialog("close"),alert("Your password has expired, you must change it before logging in"),app.openChangePasswordDialog()):(app.principal=n.user,Wndsr.setLocalStorage("principal",app.principal),$("#InspectorName").text(app.principal.displayName),$("#LoggedInUser").text(app.principal.displayName),$("#LogoutLink").removeClass("ui-icon-login"),$("#LogoutLink").addClass("ui-icon-logout"),$("#LogoutLink").attr("title","Logout"),window.location.reload()):n.isInactive?logonMessage("User account is inactive"):n.errorCode===1?logonMessage("There was an error processing the login request"):logonMessage("Credentials are invalid")},function(){alert("Failed getting logged in user.")},!1):app.authenticate())):($("#InspectorName").text(app.principal.displayName),$("#LoggedInUser").text(app.principal.displayName),$("#LogoutLink").removeClass("ui-icon-login"),$("#LogoutLink").addClass("ui-icon-logout"),$("#LogoutLink").attr("title","Logout"),app.principal.isAdmin&&$("#AdminButton").show(),app.principal.isSensitiveEdit&&($("#ReviewButton").show(),$("#ProjectTrackingButton").show()))),window.location.href.toUpperCase().indexOf("STATUSPAGE")>=0){n=null;$("#RefreshGPS").on("click",function(){var t=!0,u=0,r=0,i;t=$("#rdoTrue").is(":checked")?!0:!1,u=parseInt($("#txtMaximumAge").val()),r=parseInt($("#txtTimeout").val()),i={enableHighAccuracy:t,maximumAge:u,timeout:r},navigator.geolocation.getCurrentPosition(function(t){$("#gpsCoordinates").val(t.coords.latitude+", "+t.coords.longitude),$("#gpsAccuracy").val(t.coords.accuracy),$("#gpsAge").val(0),n=+new Date},function(n){$("#gpsError").val(n.code+" - "+n.message)},i)});setInterval(function(){var t=+new Date;n!==null&&n!==undefined&&$("#gpsAge").val(Math.floor(t-n))},1e3)}$("html").on("logonComplete",function(){app.principal.isSensitiveEdit&&($("#ReviewButton").show(),$("#ProjectTrackingButton").show()),app.principal.isAdmin&&$("#AdminButton").show()});$("#LogoutLink").click(function(){var t=app.vroot()+"Support/LogJavaScriptError",n;if(app.principal===null)return app.authenticate(),!1;if(n=app.principal.login,app.isMobile())confirm("All inspection data will be removed from this tablet. Are you sure you want to logout?")&&(app.canLogOut=!0,app.persist.getInspections(function(i){for(var r=0;r<i.length;r++)if(i[r].isDirty)return app.canLogOut=!1,alert("You must synchronize before you can log out"),!1;app.principal=null,Wndsr.clearLocalStorage(),app.persist.clear(),$.ajax({url:t,data:{message:"User "+n+" logged out"},type:"POST",error:function(){},global:!1,success:function(){window.location=app.vroot()+"Inspection/"}})}));else return app.principal=null,Wndsr.clearLocalStorage(),$.ajax({url:t,data:{message:"User "+n+" logged out"},type:"POST",error:function(){},global:!1,success:function(){window.location=app.vroot()+"Inspection/"}}),!1;return!1});$("html").on("applicationOnline",function(){$("#SyncState").removeClass("ui-icon-online-status-offline"),$("#SyncState").addClass("ui-icon-online-status-online"),$("#LogoutLink").show(),$("#AddUnassignedInspection").show()});$("html").on("applicationOffline",function(){$("#SyncState").removeClass("ui-icon-online-status-online"),$("#SyncState").addClass("ui-icon-online-status-offline"),$("#LogoutLink").hide(),$("#AddUnassignedInspection").hide()});$("#HomeButton").on("click",function(){setTimeout(function(){window.location=app.vroot()+"Inspection/"},300)});$("#AdminButton").on("click",function(){app.isOnline?setTimeout(function(){window.location=app.vroot()+"Form/"},300):alert("Sorry, you must be on-line to access Administration functions.")});$("#ReviewButton").on("click",function(){app.isOnline?setTimeout(function(){window.location=app.vroot()+"Inspection/ReviewList/"},300):alert("You must be online to review inspections")});$("#ProjectTrackingButton").on("click",function(){app.isOnline?setTimeout(function(){window.location=app.vroot()+"Project/"},300):alert("You must be online to track projects")});$("#SlideUpSitesButton").on("click",function(){app.isOnline?setTimeout(function(){window.location.href=app.vroot()+"Site?mode=2"},300):alert("You must be online to use site history")});$.blockUI.defaults.message="<h1>Please wait...<\/h1>",$("#LogoutLink").hide(),app.isMobile()?($("#ReviewButton").hide(),$("#MobileIndicator").show(),$("#DesktopIndicator").hide(),setInterval(app.pingServer,6e4),app.pingServer()):(app.isOnline=!0,$("#MobileIndicator").hide(),$("#DesktopIndicator").show(),Wndsr.info("Application Online"),$("html").trigger("applicationOnline")),$("#LogonLink").unbind().click(function(n){n.preventDefault(),app.openLogonDialog()}),window.location.href.search(/ReturnUrl=/)>-1&&app.openLogonDialog(),t=Handlebars.compile($("#template-row").html());$("#SearchAdditionalForms").on("keyup",function(){var n=$(this).val().toUpperCase();$("h3","#AdditionalForms").each(function(){n==""||$(this).children("a").text().toUpperCase().indexOf(n.trim())>=0?$(this).show():$(this).hide().next().hide()})});$("#CurrentForms, #AdditionalForms").on("click","h3",function(){return $("#CurrentForms h3, #AdditionalForms h3").not(this).each(function(){$(this).children("span").removeClass("ui-expanded-accordion").addClass("ui-collapsed-accordion"),$(this).children("a").removeClass("ui-accordion-title-text-expanded").addClass("ui-accordion-title-text-collapsed"),$(this).removeClass("ui-accordion-title-expanded").addClass("ui-accordion-title-collapsed"),$(this).next().hide()}),$(this).next().is(":visible")?($(this).children("span").removeClass("ui-expanded-accordion").addClass("ui-collapsed-accordion"),$(this).children("a").removeClass("ui-accordion-title-text-expanded").addClass("ui-accordion-title-text-collapsed"),$(this).removeClass("ui-accordion-title-expanded").addClass("ui-accordion-title-collapsed"),$(this).next().hide()):($(this).children("span").removeClass("ui-collapsed-accordion").addClass("ui-expanded-accordion"),$(this).children("a").removeClass("ui-accordion-title-text-collapsed").addClass("ui-accordion-title-text-expanded"),$(this).removeClass("ui-accordion-title-collapsed").addClass("ui-accordion-title-expanded"),$(this).next().show()),$("#CurrentForms").resize(),$("#AdditionalForms").resize(),$(window).resize(),!1});$("#AdditionalForms").on("click","li",function(){$.blockUI();var t=$(this).data("formversion-id"),i=$(this).data("formsection-id"),n=$(this).data("inspection-id");Inspection.Load(n,function(r){var u=new InspectionForm;u.New(n,t),r.inspectionForms.push(u),r.isDirty=!0,u.Initialize(function(){r.Save(function(){window.location=app.vroot()+"InspectionForm?inspectionId="+n+"&formVersionId="+t+"&formSectionId="+i},app.getDataFailed)},app.getDataFailed)},app.getDataFailed)});app.setupEditors(),app.configureDefaultValidations(),r(),$("#SyncState").click(app.synchronize.synchronize)}),typeof app=="undefined")&&(app={},app.principal=null,app.vroot=function(){return $("body").data("vroot")},app.currentUrl=function(){return $("body").data("currentUrl")},app.supportUrl=function(){return app.vroot()+"support/LogJavaScriptError"},app.isOnline=!1,app.canLogOut=!0,app.isMobile=function(){var n=Wndsr.getLocalStorage("mobileOverride");return n!==null?n===1?!0:!1:Modernizr.touch},app.handleTimeoutStopBackOrClick=function(){Wndsr.error("A timeout, stop, back, or click to another page.  Arghh!"),app.isOnline&&(app.isOnline=!1,Wndsr.info("Application Offline"),$("html").trigger("applicationOffline"))},app.handle403Errors=function(){Wndsr.error("A 403 error was caught. Go back to login."),app.authenticate()},app.authenticate=function(){Wndsr.warn("Authentication is required.  Presenting login to user"),app.openLogonDialog()},app.pingServer=function(){Wndsr.info("Ping Start"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/Heartbeat/0",contentType:"application/json; charset=utf-8",success:app.pingSuccess,error:app.pingFailed})},app.pingSuccess=function(){Wndsr.info("Ping Success")},app.pingFailed=function(){Wndsr.info("Ping Failed")},app.openChangePasswordDialog=function(){var n=$("#ChangePasswordForm"),i=function(n){$("#ChangePasswordForm fieldset span.error").remove(),$("#ChangePasswordForm fieldset legend").after("<span class='error'>"+n+"<\/span>")},t=function(){n.dialog({autoOpen:!1,height:500,minHeight:500,width:500,minWidth:500,modal:!0,resizable:!1,dialogClass:"logon-form-dialog",buttons:{OK:function(){var t=$(this),n=$("form",t);if(app.formIsValid(n)){if($("#PasswordChange").val()!==$("#PasswordConfirm").val())return alert("The passwords do not match"),!1;$.blockUI({message:"<h1>Please Wait<\/h1>"}),$.post(n.attr("action"),n.serialize(),function(n){if($.unblockUI(),n.successful)location.reload();else return alert(n.message),!1})}},Cancel:function(){$(this).dialog("close")}},open:function(){$(".ui-dialog-buttonpane button:contains('Cancel')").addClass("ui-priority-secondary")}}),n.bind("dialogclose",function(){var n=$("#ChangePasswordForm form");n[0].reset(),$(".input-validation-error",n).removeClass("input-validation-error"),$("#ChangePasswordForm form .error").html("")}),$("input[required=required]",n).before("<span class='requiredIndicator'><\/span>")};n.data("isDialogSetup")||(t(),n.data("isDialogSetup",!0)),n.dialog("open")},app.openResetPasswordDialog=function(){var n=$("#ResetPasswordForm"),i=function(n){$("#ResetPasswordForm fieldset span.error").remove(),$("#ResetPasswordForm fieldset legend").after("<span class='error'>"+n+"<\/span>")},t=function(){n.dialog({autoOpen:!1,height:300,minHeight:300,width:500,minWidth:500,modal:!0,resizable:!1,dialogClass:"logon-form-dialog",buttons:{OK:function(){var t=$(this),n=$("form",t);return app.formIsValid(n)&&($.blockUI({message:"<h1>Please Wait<\/h1>"}),$.post(n.attr("action"),n.serialize(),function(n){if($.unblockUI(),n.successful)location.reload();else return alert(n.message),!1})),!1},Cancel:function(){$(this).dialog("close")}},open:function(){$(".ui-dialog-buttonpane button:contains('Cancel')").addClass("ui-priority-secondary")}}),n.bind("dialogclose",function(){var n=$("#ResetPasswordForm form")}),$("input[required=required]",n).before("<span class='requiredIndicator'><\/span>")};n.data("isDialogSetup")||(t(),n.data("isDialogSetup",!0)),n.dialog("open")},app.openLogonDialog=function(){var i=$("#LoginUrl").val();if(i!=="")window.location.replace(i+"?returnUrl="+window.location.href);else{var n=$("#LogonForm"),t=function(n){$("#LogonForm fieldset span.error").remove(),$("#LogonForm fieldset legend").after("<span class='error'>"+n+"<\/span>")},r=function(){n.dialog({autoOpen:!1,height:545,minHeight:545,width:550,minWidth:550,modal:!0,resizable:!1,dialogClass:"logon-form-dialog",position:{my:"top",at:"top"},buttons:{OK:function(){var r=$(this),i=$("form",r),n;if(!Modernizr.localstorage)return n=$("#ApplicationName").val(),alert("This browser is not capable of supporting "+n+" (no local storage)."),!1;if(navigator.userAgent.indexOf("MSIE 9.0")>=0)return n=$("#ApplicationName").val(),alert("Internet Explorer version 9.0 is not capable of supporting "+n+"."),!1;if(navigator.userAgent.indexOf("MSIE 8.0")>=0)return n=$("#ApplicationName").val(),alert("Internet Explorer version 8.0 is not capable of supporting "+n+"."),!1;if(navigator.userAgent.indexOf("MSIE 7.0")>=0)return n=$("#ApplicationName").val(),alert("Internet Explorer version 7.0 is not capable of supporting "+n+"."),!1;if(navigator.userAgent.indexOf("Mozilla/5.0")>-1&&navigator.userAgent.indexOf("Android ")>-1&&navigator.userAgent.indexOf("AppleWebKit")>-1&&!(navigator.userAgent.indexOf("Chrome")>-1))return n=$("#ApplicationName").val(),alert("The native android browser is not capable of supporting "+n+"."),!1;$("#IsMobile").is(":checked")?(Wndsr.setLocalStorage("mobileOverride",1),$("#MobileIndicator").show(),$("#DesktopIndicator").hide()):(Wndsr.setLocalStorage("mobileOverride",0),$("#MobileIndicator").hide(),$("#DesktopIndicator").show()),app.formIsValid(i)&&($.blockUI({message:"<h1>Please Wait<\/h1>"}),$.post(i.attr("action"),i.serialize(),function(n){$.unblockUI();var u=window.location.href.search(/ReturnDomain=/),i="",r=window.location.href.search(/ReturnUrl=/);n.successful?n.isExpired?($("#LogonForm").dialog("close"),alert("Your password has expired, you must change it before logging in"),app.openChangePasswordDialog()):(app.principal=n.user,Wndsr.setLocalStorage("principal",app.principal),$("#InspectorName").text(app.principal.displayName),$("#LoggedInUser").text(app.principal.displayName),$("#LogoutLink").removeClass("ui-icon-login"),$("#LogoutLink").addClass("ui-icon-logout"),$("#LogoutLink").attr("title","Logout"),u>-1&&(i=unescape(Wndsr.getUrlParam("ReturnDomain"))),r>-1?window.location=i.length>0?i+unescape(window.location.href.substr(r+10)):window.location.protocol+"//"+window.location.host+unescape(window.location.href.substr(r+10)):($("#LogonForm").dialog("close"),$("html").trigger("logonComplete")),(window.location.href.indexOf("InspectionForm?")>0||window.location.href.indexOf("FormVersion?")>0)&&window.location.reload()):n.isInactive?t("User account is inactive"):n.errorCode===1?t("There was an error processing the login request"):t("Credentials are invalid")}).fail(function(){$.unblockUI(),t("Cannot access the server")}))},"Change Password":function(){$(this).dialog("close"),app.openChangePasswordDialog()},"Reset Password":function(){$(this).dialog("close"),app.openResetPasswordDialog()},Cancel:function(){$(this).dialog("close")}},close:function(){$("#LogoutLink").focus()},open:function(){$(".ui-dialog-buttonpane button:contains('Cancel')").addClass("ui-priority-secondary"),$("input").keypress(function(n){n.which===13&&$(".ui-dialog-buttonpane button:contains(OK)",".logon-form-dialog").trigger("click")}),window.location.href.search(/ReturnUrl=/)>-1&&t("Please sign in")}}),n.bind("dialogclose",function(){var n=$("#LogonForm form");n[0].reset(),$(".input-validation-error",n).removeClass("input-validation-error"),$("#LogonForm form .error").html("")}),$("input[required=required]",n).before("<span class='requiredIndicator'><\/span>")};n.data("isDialogSetup")||(r(),n.data("isDialogSetup",!0)),app.isMobile()?($("#IsMobile").prop("checked",!0),$("#IsConnected").prop("checked",!1)):($("#IsMobile").prop("checked",!1),$("#IsConnected").prop("checked",!0)),n.dialog("open"),$.unblockUI()}},app.configureDefaultValidations=function(n){var t;$.fn.valid&&(t=$(n).is("form")?$(n):$("form",n),t.validate({ignore:".ignoreValidation"}),$("input[required]",n).each(function(){$(this).rules("remove","required"),$(this).rules("add","required")}))},app.clearError=function(){$("div.error").hide(),app.isOnline||(app.isOnline=!0,Wndsr.info("Application Online"),$("html").trigger("applicationOnline"))},app.showMessage=function(n,t){var i,r=$(".ui-dialog:visible");r.length>0?(i=$("div.error",r),i.length===0&&($(".ui-dialog-titlebar",r).next().prepend("<div class='error autogen'><\/div>"),i=$("div.error",r)),i.html(n).show()):(i=$("div.error",t).not(".ui-dialog"),i.length===0&&(t?$(t).prepend("<div class='error autogen'><\/div>"):$("body").prepend("<!-- This is likely not where you want this div.  Make your own div with class error somewhere in the body and this one will go away. --><div class='error autogen'><\/div>"),i=$("div.error",t).not(".ui-dialog")),i.html(n).show())},app.ajaxErrorIsHandled=!1,app.setError=function(n,t){var u,f=!1;if(app.ajaxErrorIsHandled){app.ajaxErrorIsHandled=!1;return}switch(t.status){case 422:u=$.parseJSON(t.responseText),app.showMessage(u[0].ErrorMessage);break;case 400:Wndsr.error("Bad request from server: "),Wndsr.error($.parseJSON(t.responseText)),Wndsr.error($.parseJSON(t.responseText).Message),Wndsr.error($.parseJSON(t.responseText).StackTrace),app.showMessage(n);break;default:app.showMessage(n)}},app.post=function(n,t,i,r){$.ajax({type:"post",url:n,dataType:"json",contentType:"application/json; charset=utf-8",data:JSON.stringify(t),headers:{"cache-control":"no-cache"},success:i,cache:!1,error:r})},app.deleteItem=function(n,t,i,r){var u=$("#dialog-confirm"),f=r?r:t;u.length===0&&($("body").append('<div id="dialog-confirm" title="'+t+'"><p>'+t+"<\/p><\/div>"),u=$("#dialog-confirm")),$(".error",u).remove(),$("#dialog-confirm").dialog({resizable:!1,height:160,modal:!0,buttons:{Cancel:function(){$(this).dialog("close")},OK:function(){var t=$(this);if($(".error",u).remove(),i){i(n,function(n){typeof n=="undefined"||n===!0?t.dialog("close"):u.prepend("<div class='error'>"+n+"<\/div>")});return}$(this).dialog("close")}}})},app.formIsValid=function(n){var r,i,t=$("div.error",n),u,f=function(n){var t=0;return $(".richEdit.required",n).removeClass("input-validation-error").each(function(){var n=$(this).data("default");n||(n=""),$(this).html()===n&&($(this).addClass("input-validation-error"),t++)}),t};return $(n).valid(),r=$(n).validate({errorClass:"input-validation-error"}),r.hideErrors(),i=r.numberOfInvalids()+f($(n)),i?(t.length===0&&($(n).prepend("<div class='error autogen'><\/div>"),t=$("div.error",n)),u=i==1?"Please correct the highlighted field":"Please correct the highlighted fields",t.html(u),t.show()):t.hide(),!i},app.wmdHtml=function(n){var t=$("#wmd-preview",n);return t.length===0&&(t=n),t.html()},app.serialize=function(n){var r=$(n),t=r.serialize(),i=t.length>0;return $(".richEdit[id]",n).each(function(){var r=$(this),f=r.attr("id"),n=$("#wmd-preview",r),u;n.length===0&&(n=r),u=n.html(),i?t+="&":i=!0,t+=f+"="+encodeURI(u)}),t},app.move=function(n,t,i,r){i.length!==0&&(n.detach(),t==="before"?n.insertBefore(i):n.insertAfter(i),r())},app.logToElmah=function(n){$.post("Support/LogJavaScriptError",{message:n})},app.applyTheme=function(n){var t;return $(".js-move-up-down",n).each(function(){var t=$(this);t.prev().is(".js-button-move-up-down-no-text",n)||t.before("<div class='js-button-move-up-down-no-text' title='Move'><div class='js-move-up-target' title='Move up'><\/div><div class='js-move-down-target' title='Move down'><\/div><\/div>")}),$(".js-button-add",n).button({icons:{primary:ot}}).show(),$(".js-button-remove",n).button({icons:{primary:et}}).show(),$(".js-button-view",n).button({icons:{primary:ut}}).show(),$(".js-button-edit",n).button({icons:{primary:ft}}).show(),$(".js-button-delete",n).button({icons:{primary:nt}}).show(),$(".js-button-save",n).button({icons:{primary:g}}).show(),$(".js-button-cancel",n).button({icons:{primary:it}}).show(),$(".js-button-wrench",n).button({icons:{primary:tt}}).show(),$(".js-button-download",n).button({icons:{primary:bt}}).show(),$(".js-button-upload",n).button({icons:{primary:wt}}).show(),$(".js-button-move-down",n).button({icons:{primary:st}}).show(),$(".js-button-move-up",n).button({icons:{primary:pt}}).show(),$(".js-button-move-up-down",n).button({icons:{primary:yt}}).show(),$(".js-button-validate",n).button({icons:{primary:vt}}).show(),$(".js-button-print",n).button({icons:{primary:ct}}).show(),$(".js-button-back",n).button({icons:{primary:ht}}).show(),$(".js-button-next",n).button({icons:{primary:at}}).show(),$(".js-button-up",n).button({icons:{primary:lt}}).show(),$(".js-button-alert",n).button({icons:{primary:h}}).show(),$(".js-button-question",n).button({icons:{primary:s}}).show(),$(".js-button-note",n).button({icons:{primary:l}}).show(),$(".js-button-history",n).button({icons:{primary:c}}).show(),$(".js-button-version",n).button({icons:{primary:f}}).show(),$(".js-button-copy",n).button({icons:{primary:u}}).show(),$(".js-button-new-window",n).button({icons:{primary:o}}).show(),$(".js-button-pay",n).button({icons:{primary:e}}).show(),$(".js-button-refresh",n).button({icons:{primary:b}}).show(),$(".js-button-control",n).button({icons:{primary:w}}).show(),$(".js-button-pin",n).button({icons:{primary:k}}).show(),$(".js-button-mail",n).button({icons:{primary:v}}).show(),$(".js-button-locked",n).button({icons:{primary:a}}).show(),$(".js-button-unlocked",n).button({icons:{primary:p}}).show(),$(".js-button-link",n).button({icons:{primary:rt}}).show(),$(".js-button-return",n).button({icons:{primary:y}}).show(),$(".js-button-hot",n).button({icons:{primary:d}}).show(),$(".js-button-add-no-text",n).button({icons:{primary:ot},text:!1}).show(),$(".js-button-remove-no-text",n).button({icons:{primary:et},text:!1}).show(),$(".js-button-view-no-text",n).button({icons:{primary:ut},text:!1}).show(),$(".js-button-edit-no-text",n).button({icons:{primary:ft},text:!1}).show(),$(".js-button-delete-no-text",n).button({icons:{primary:nt},text:!1}).show(),$(".js-button-save-no-text",n).button({icons:{primary:g},text:!1}).show(),$(".js-button-cancel-no-text",n).button({icons:{primary:it},text:!1}).show(),$(".js-button-wrench-no-text",n).button({icons:{primary:tt},text:!1}).show(),$(".js-button-download-no-text",n).button({icons:{primary:bt},text:!1}).show(),$(".js-button-upload-no-text",n).button({icons:{primary:wt},text:!1}).show(),$(".js-button-move-down-no-text",n).button({icons:{primary:st},text:!1}).show(),$(".js-button-move-up-no-text",n).button({icons:{primary:pt},text:!1}).show(),$(".js-button-move-up-down-no-text",n).button({icons:{primary:yt},text:!1}).show(),$(".js-button-validate-no-text",n).button({icons:{primary:vt},text:!1}).show(),$(".js-button-print-no-text",n).button({icons:{primary:ct},text:!1}).show(),$(".js-button-back-no-text",n).button({icons:{primary:ht},text:!1}).show(),$(".js-button-next-no-text",n).button({icons:{primary:at},text:!1}).show(),$(".js-button-up-no-text",n).button({icons:{primary:lt},text:!1}).show(),$(".js-button-alert-no-text",n).button({icons:{primary:h},text:!1}).show(),$(".js-button-question-no-text",n).button({icons:{primary:s},text:!1}).show(),$(".js-button-note-no-text",n).button({icons:{primary:l},text:!1}).show(),$(".js-button-history-no-text",n).button({icons:{primary:c},text:!1}).show(),$(".js-button-version-no-text",n).button({icons:{primary:f},text:!1}).show(),$(".js-button-copy-no-text",n).button({icons:{primary:u},text:!1}).show(),$(".js-button-new-window-no-text",n).button({icons:{primary:o},text:!1}).show(),$(".js-button-pay-no-text",n).button({icons:{primary:e},text:!1}).show(),$(".js-button-refresh-no-text",n).button({icons:{primary:b},text:!1}).show(),$(".js-button-control-no-text",n).button({icons:{primary:w},text:!1}).show(),$(".js-button-pin-no-text",n).button({icons:{primary:k},text:!1}).show(),$(".js-button-mail-no-text",n).button({icons:{primary:v},text:!1}).show(),$(".js-button-locked-no-text",n).button({icons:{primary:a},text:!1}).show(),$(".js-button-unlocked-no-text",n).button({icons:{primary:p},text:!1}).show(),$(".js-button-link-no-text",n).button({icons:{primary:rt},text:!1}).show(),$(".js-button-return-no-text",n).button({icons:{primary:y},text:!1}).show(),$(".js-button-hot-no-text",n).button({icons:{primary:d},text:!1}).show(),$("input[type='date']").datepicker({showOn:"focus",changeMonth:!0,changeYear:!0}),$(".js-date-picker").datepicker({dateFormat:"yy-mm-dd",changeMonth:!0,changeYear:!0,showButtonPanel:!0,showOn:"both",buttonImage:"css/img/cal-sm.png",buttonImageOnly:!0,showAnim:"slideDown",firstDay:1,autoSize:!0}),$(".js-date-time-picker").datepicker({dateFormat:"yy-mm-dd",changeMonth:!0,changeYear:!0,showButtonPanel:!0,showOn:"both",buttonImage:"css/img/cal-sm.png",buttonImageOnly:!0,showAnim:"slideDown",firstDay:1,time24h:!0,showTime:!0}),$("div[role='navigation'] a span.ui-icon").length===0&&($("div[role='navigation'] a.logon").append("<span class='ui-icon ui-icon-key'><\/span>"),$("div[role='navigation'] a.whatsnew").append("<span class='ui-icon ui-icon-lightbulb'><\/span>"),$("div[role='navigation'] a.users").append("<span class='ui-icon ui-icon-person'><\/span>"),$("div[role='navigation'] a.logout").append("<span class='ui-icon ui-icon-power'><\/span>").unbind().click(function(n){n.preventDefault(),$.post($(this).attr("href"),null,function(n){n&&(location=app.vroot()+"adminlogon")})}),$("div[role='navigation'] a.return").append("<span class='ui-icon ui-icon-arrowreturnthick-1-w'><\/span>").unbind().click(function(n){history.go(-1),n.preventDefault()})),$("#InfoArea .ui-icon-alert").length+$("#InfoArea .ui-icon-info").length===0&&(t=$("#InfoArea div.error").addClass("ui-state-error ui-corner-all").prepend('<span class="ui-icon ui-icon-alert" style="float: left;"><\/span>'),t.length===0&&(t=$("#InfoArea div.warning").addClass("ui-state-highlight ui-corner-all").prepend('<span class="ui-icon ui-icon-info" style="float: left;"><\/span>'))),$(".js-move-up-target, .js-move-down-target").hover(function(){$(this).addClass("ui-state-highlight")},function(){$(this).removeClass("ui-state-highlight")}),n},app.htmlToMarkDown=function(n){return n.replace(/ id=[\'\"].*[\'\"]/g,"").replace(/<\/p><p( id=[\'\"].*[\'\"])*>/gm,"<br><br>").replace(/<p>/g,"").replace(/<p id=[\'\"].*[\"\']>/g,"").replace(/<\/p>\n\n/g,"\n").replace(/<\/p>/g,"").replace(/<br>/g,"\n").replace(/ +<li>/g,"<li>").replace(/<li>/g,"    <li>").replace(/<\/li>\n/g,"<\/li>").replace(/<\/li>/g,"<\/li>\n").replace(/<ul>/g,"\n<ul>\n").replace(/<\/ul>/g,"<\/ul>\n").replace(/<ol>/g,"\n<ol>\n").replace(/<\/ol>/g,"<\/ol>\n").replace(/<strong>/g,"**").replace(/<\/strong>/g,"**").replace(/<em>/g,"*").replace(/<\/em>/g,"*")},app.currentEditor=undefined,app.setJqGridGlobals=function(){$.jgrid.defaults=$.extend($.jgrid.defaults,{jsonReader:{repeatitems:!1,page:"Page",total:"Total",records:"Records",root:"Items",id:"0"}})},app.convertToAutoSize=function(n){n.supertextarea({maxh:500,maxw:500,minh:100,tabr:{use:!1},maxl:2e3,dsrm:{use:!1}})},app.setupEditors=function(n){var t,f,i,r,u=$(".richEdit",n);u.length!==0&&(n||$("body").append("<div id='wmd'><div id='wmd-preview'><\/div><div id='wmd-button-bar'><\/div><textarea id='wmd-input'><\/textarea><button class='js-button-save'>Close<\/button><\/div>"),r=$("#wmd"),t=$("#wmd-preview"),f=$("#wmd-button-bar"),i=$("#wmd-input"),u.click(function(){var n=$(this).prevAll(".hideOnEdit").add($(this).nextAll(".hideOnEdit"));$("#wmd-input",this).length>0||(Wndsr.debug("setting up markdown ed"),app.currentEditor&&app.currentEditor[0]!==$(this)[0]&&$(".js-button-save",app.currentEditor).click(),app.currentEditor=$(this).removeClass("input-validation-error"),app.currentEditor.html()===app.currentEditor.data("default")&&app.currentEditor.html(""),$(this).data("html",$(this).html()).html(""),t.html($(this).data("html")),app.currentEditor.hasClass("new")&&app.currentEditor.removeClass("new").data("hadNewClass",!0),$(r).detach().appendTo($(this)),n.hide(),i.html($(this).data("html")).trigger("keypress").val(app.htmlToMarkDown($(this).data("html"))))}).parent().addClass("clearfix"),n||$(".js-button-save").click(function(n){var f=app.wmdHtml(),e=$(this).parentsUntil(".wmd").parent().prev(),u=$(".hideOnEdit");Wndsr.debug("tearing down markdown ed"),$(r).detach().appendTo("body"),t.html().toString().length>0?app.currentEditor.html(f):t.html()===""&&app.currentEditor.data("default")&&(app.currentEditor.html(app.currentEditor.data("default")),app.currentEditor.data("hadNewClass")===!0&&app.currentEditor.addClass("new")),u.show(),i.html(),t.html(""),app.currentEditor.data("teardownCallback")&&app.currentEditor.data("teardownCallback")(),app.currentEditor=undefined,n.stopImmediatePropagation()}))},app.MessageType=Object,app.MessageType.Error=0,app.MessageType.Information=1,app.MessageType.Warning=2,app.MessageType.Success=3,app.HasPageNotification=function(){return $("#PageNotification").length},app.IsPageNotificationVisible=function(){return $("#PageNotification").css("display")!="none"},app.HidePageNotification=function(){$("#PageNotification").fadeTo(400,0,function(){$(this).slideUp(400,function(){})})},app.SetPageNotification=function(n,t,i){var f;window.scrollTo(0,0),i=i!==undefined?i:!1;var o=null,u="",r=null,e=null;if(app.HasPageNotification()&&!i){if(r=$("#PageNotification"),e=$("#PageNotificationMessage"),e.text()==n&&r.is(":visible"))return r;r.removeClass("information problem success attention"),e.text(n)}else f="<div class='notification' id='PageNotification'>",f+="<a href='#' class='close' title='Close'><span><\/span><\/a>",f+="<div id='PageNotificationMessage'>"+n+"<\/div><\/div>",r=$(f);if(n&&n.length>0&&n!="undefined"){switch(parseInt(t,10)){case app.MessageType.Error:u="problem";break;case app.MessageType.Information:u="information";break;case app.MessageType.Warning:u="attention";break;case app.MessageType.Success:u="success"}r.addClass(u),r.find("a").click(function(){return $(this).parent().fadeTo(400,0,function(){$(this).slideUp(400,function(){})}),!1}),app.HasPageNotification()?r.fadeTo(400,1,function(){$(this).slideDown(400)}):$("#InfoArea").append(r)}return o=r},$.ajaxSetup({statusCode:{0:app.handleTimeoutStopBackOrClick,200:app.clearError,449:function(n,t,i){n.statusText==="Retry with authentication"&&app.authenticate(n,t,i)},403:app.handle403Errors,400:function(n,t,i){app.setError("Bad request received. This is likely a bug.  Please report the error.",n,t,i)},404:function(n){Wndsr.error("Requested URL not found (HTTP 404 received).",n)},422:function(n,t,i){app.setError("Validation error occurred.",n,t,i)},500:function(n){app.setError("Internal server error. Please try again. If this does not work, please report the error.",n)}},error:function(n){app.lastAjaxError={originalRequest:this,jqXHR:n}}}),Handlebars.registerHelper("thirtyChars",function(n){return n===null||n===undefined?"":n.length<=30?n:n.substring(0,30)+"..."}),Handlebars.registerHelper("sixtyChars",function(n){return n===null||n===undefined?"":n.length<=60?n:n.substring(0,60)+"..."}),Handlebars.registerHelper("oneHundredChars",function(n){return n===null||n===undefined?"":n.length<=100?n:n.substring(0,100)+"..."}),Handlebars.registerHelper("formatDate",function(n){var t=null;return t=typeof n=="object"?moment(n._d):moment(n),t.format("M/D/YYYY")}),Handlebars.registerHelper("formatDateUtc",function(n){var t=null;return t=typeof n=="object"?n._d.indexOf(!1)?moment(n._d):moment.utc(n._d):n.indexOf(!1)?moment(n):moment.utc(n),t.format("M/D/YYYY")}),Handlebars.registerHelper("formatTime",function(n){var t=moment(n);return t.format("h:mm a")}),Handlebars.registerHelper("compare",function(n,t,i,r){var u,f;if(arguments.length<3)throw new Error("Handlerbars Helper 'compare' needs 2 parameters");if(r===undefined&&(r=i,i=t,t="==="),u={"==":function(n,t){return n==t},"===":function(n,t){return n===t},"!=":function(n,t){return n!=t},"!==":function(n,t){return n!==t},"<":function(n,t){return n<t},">":function(n,t){return n>t},"<=":function(n,t){return n<=t},">=":function(n,t){return n>=t},"typeof":function(n,t){return typeof n==t}},!u[t])throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+t);return f=u[t](n,i),f?r.fn(this):r.inverse(this)}),Handlebars.registerHelper("violationSeq",function(){return r++,r}),app.resetViolationSeqNum=function(){r=0},app.createUUID=function(){for(var n=[],r="0123456789ABCDEF",t=0;t<32;t++)n[t]=r.substr(Math.floor(Math.random()*16),1);n[12]="4",n[16]=r.substr(n[16]&3|8,1);var i=n.join(""),u=/(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/,i=i.toLowerCase().replace(u,"$1-$2-$3-$4-$5");return i},app.getDataFailed=function(){Wndsr.error("Failed getting data"),alert("Still waiting on server to send data, refresh the page to try again.")},app.convertDMSToDD=function(n,t,i,r){var u=n+t/60+i/3600;return(r=="S"||r=="W")&&(u=u*-1),u},app.rotateImage=function(n,t,i){var r=$.Deferred();return $("<img/>").attr("src",t+n).load(function(){var n=document.createElement("canvas"),u=n.getContext("2d");n.width=this.width,n.height=this.height,u.translate(this.width*.5,this.height*.5),u.rotate(i*Math.PI/180),u.translate(-this.width*.5,-this.height*.5),u.drawImage(this,0,0),t.toUpperCase().indexOf("JPEG")>0?r.resolve($("<img/>").attr("src",n.toDataURL("image/jpeg"))):r.resolve($("<img/>").attr("src",n.toDataURL()))}),r.promise()},app.resizeBase64Img=function(n,t,i,r){var u=$.Deferred();return $("<img/>").attr("src",t+n).load(function(){var n,t;(i===null||i===undefined||i===0)&&(i=this.width*(r/this.height)),(r===null||r===undefined||r===0)&&(r=this.height*(i/this.width)),n=document.createElement("canvas"),n.width=i,n.height=r,t=n.getContext("2d"),t.scale(i/this.width,r/this.height),t.drawImage(this,0,0),u.resolve($("<img/>").attr("src",n.toDataURL()))}),u.promise()},app.displayForms=function(n){n.completed!==null&&n.completed!==undefined&&n.completed!==""&&(alert("This inspection is completed and cannot be edited"),window.location=app.vroot()+"Inspection/"),app.persist.getOrganizations(function(i){app.persist.getFormVersions(function(r){app.persist.getForms(function(u){app.persist.getFormSections(function(f){var v=i,k=[],a,y,l,d,c,s,p,g,h,o,e,it,ut,ft,et,rt,w,b;if(app.principal.organizationList===undefined)for(a=0;a<v.length;v++)k.push(v[a].id);else for(a=0;a<app.principal.organizationList.length;a++)if(!(k.indexOf(app.principal.organizationList[a])>=0)){for(k.push(app.principal.organizationList[a]),y=null,l=0;l<v.length;l++)if(app.principal.organizationList[a]===v[l].id){y=v[l].parentOrganizationId;continue}while(y!==null){if(k.indexOf(y)>=0){y=null;continue}for(k.push(y),l=0;l<v.length;l++)if(y===v[l].id){y=v[l].parentOrganizationId;continue}}}var nt=[],tt=[],ot=n!==undefined&&n.site!==undefined?n.site.siteName:"";for($("#CurrentForms").prev().children("h2").text("Forms for "+ot),$("#CurrentForms").html(""),$("#AdditionalForms").html(""),d=0;d<u.length;d++){if(c={},c.sortedFormSections=[],s=null,p=r.filter(function(n){return n.formId===u[d].id}),p=p.sort(function(n,t){return t.versionNumber-n.versionNumber}),p.length===1)s=p[0];else if(p.length>1){for(e=0;e<n.inspectionForms.length;e++)if(s=p.find(function(t){return t.id===n.inspectionForms[e].formVersionId}),s)break;s||(s=p[0])}if(s!==null)if(g=n.inspectionForms.find(function(n){return n.formVersionId===s.id&&!n.isDeleted}),c.id=s.id,c.name=u[d].name,c.reportIndex=u[d].reportIndex,h=f.filter(function(n){return n.formVersionId===s.id}),h=h.sort(function(n,t){var r=n.sectionSortOrder,i=t.sectionSortOrder;return r===null||r===undefined?0:i===null||i===undefined?0:r<i?-1:r>i?1:0}),o={},e=0,g){for(g.score&&(c.score=g.score.toFixed(2)),e=0;e<h.length;e++)o={},it=g.inspectionFormSections.find(function(n){return n.formSectionId===h[e].id}),o.id=h[e].id,o.sectionTitle=h[e].sectionTitle,o.isVisible=it?it.isVisible:!0,c.sortedFormSections.push(o);nt.push(c)}else if(s.isActive&&k.indexOf(r.organizationId)>=0){for(e=0;e<h.length;e++)o={},o.id=h[e].id,o.sectionTitle=h[e].sectionTitle,o.isVisible=h[e].visibilityFormula?!1:!0,c.sortedFormSections.push(o);tt.push(c)}}for(nt=nt.sort(function(n,t){var r=n.reportIndex,i=t.reportIndex;return r===null||r===undefined?0:i===null||i===undefined?0:r<i?-1:r>i?1:0}),tt=tt.sort(function(n,t){var r=n.name.toUpperCase(),i=t.name.toUpperCase();return r===null||r===undefined?0:i===null||i===undefined?0:r<i?-1:r>i?1:0}),ut={templates:nt,currentInspectionId:n.id},ft=$.trim(t(ut)),$("#CurrentForms").html(ft),et={templates:tt,currentInspectionId:n.id},rt=$.trim(t(et)),$("#AdditionalForms").html(rt),w=0;w<n.inspectionForms.length;w++)if(n.inspectionForms[w].hasMissingAnswer)for(b=0;b<n.inspectionForms[w].inspectionFormSections.length;b++)n.inspectionForms[w].inspectionFormSections[b].hasMissingAnswer&&($("li[data-formsection-id="+n.inspectionForms[w].inspectionFormSections[b].formSectionId+"]").addClass("invalidSection"),$("li[data-formsection-id="+n.inspectionForms[w].inspectionFormSections[b].formSectionId+"]").parent().parent().prev().addClass("invalidForm"));$.unblockUI()},app.getDataFailed,n.principalId)},app.getDataFailed)},app.getDataFailed,n.principalId)},app.getDataFailed)},app.showRepeatingSectionsWithTableData=function(n,t,i){var u=[];i(u)},app.showRepeatingSectionsWithData=function(n,t,i){for(var s=[],e,o,r,f,u=0;u<t.sortedFormSections.length;u++)if(e=[],o=t.sortedFormSections[u],o.repeatingSectionsCount>=0){for(r=0;r<n.inspectionFormAnswers.length;r++)for(f=0;f<t.sortedFormSections[u].sortedFormControls.length;f++)t.sortedFormSections[u].sortedFormControls[f].id!==n.inspectionFormAnswers[r].formControlId||n.inspectionFormAnswers[r].isDeleted||e.indexOf(n.inspectionFormAnswers[r].repeatingSection)<0&&e.push(n.inspectionFormAnswers[r].repeatingSection);s.push(t.sortedFormSections[u].id+"|"+e.length)}i(s)},app.getSectionIndexes=function(n,t){for(var r=[],u,i=0;i<t.inspectionFormAnswers.length;i++)for(u=0;u<n.sortedFormControls.length;u++)n.sortedFormControls[u].id!==t.inspectionFormAnswers[i].formControlId||t.inspectionFormAnswers[i].isDeleted||r.indexOf(t.inspectionFormAnswers[i].repeatingSection)<0&&r.push(t.inspectionFormAnswers[i].repeatingSection);return r=r.sort(function(n,t){return n-t})},app.validateControl=function(n,t,i){var r,u,s,e,f,o;if(n.isRequiredInput&&n.isAllowedInput&&n.controlTypeFilename!=="instructions.html"){for(f=!1,r=0;r<t.inspectionFormAnswers.length;r++)if(t.inspectionFormAnswers[r].formControlId===n.id)if(t.inspectionFormAnswers[r].isVisible){if(t.inspectionFormAnswers[r].controlValue!==undefined&&t.inspectionFormAnswers[r].controlValue!==null&&t.inspectionFormAnswers[r].controlValue.length>0&&t.inspectionFormAnswers[r].repeatingSection===i)try{u=JSON.parse(t.inspectionFormAnswers[r].controlValue),u.answer!==undefined&&u.answer.length>0?f=!0:u.ampm!==undefined&&u.ampm.length>0&&u.hours!==undefined&&u.minutes!==undefined?f=!0:u.latitude!==undefined&&u.longitude!==null?f=!0:u.text!==undefined&&u.text!==null&&u.text!==""&&(f=!0)}catch(h){}}else f=!0;if(!f)return!1}if(n.controlTypeFilename==="table.html"&&n.isAllowedInput)for(r=0;r<t.inspectionFormAnswers.length;r++)if(t.inspectionFormAnswers[r].formControlId===n.id&&t.inspectionFormAnswers[r].controlValue!==undefined&&t.inspectionFormAnswers[r].controlValue!==null&&t.inspectionFormAnswers[r].controlValue.length>0&&t.inspectionFormAnswers[r].repeatingSection===i)try{for(u=JSON.parse(t.inspectionFormAnswers[r].controlValue),s=JSON.parse(n.controlDefinition),e=0;e<s.columns.length;e++)if(s.columns[e].isRequired&&u.answer.length>0){for(f=!1,o=0;o<u.answer.length;o++)u.answer[o][e]!==null&&u.answer[o][e]!==undefined&&u.answer[o][e]!==""&&(f=!0);if(!f)return!1}}catch(h){}return!0},app.getInvalidRepeatingSectionIndexes=function(n,t){for(var f=[],e=!1,r,u,i=0;i<t.sortedFormControls.length;i++)if(t.sortedFormControls[i].isRequiredInput){e=!0;break}if(!e)return f;for(r=app.getSectionIndexes(t,n),i=0;i<r.length;i++)for(u=0;u<t.sortedFormControls.length;u++)if(!app.validateControl(t.sortedFormControls[u],n,r[i])){f.push(r[i]);break}return f},app.validateInspectionFormWithData=function(n,t,i){for(var c=[],l=!1,v,e,f,u,a,s,o,h,r=0;r<t.sortedFormSections.length;r++){if(l=!1,t===null)return i(c);if(t.sortedFormSections[r].repeatingSectionsCount!==undefined&&t.sortedFormSections[r].repeatingSectionsCount!==null)v=app.getInvalidRepeatingSectionIndexes(n,t.sortedFormSections[r]),v.length>0&&c.push(t.sortedFormSections[r]);else for(e=0;e<t.sortedFormSections[r].sortedFormControls.length;e++){if(l)break;if(t.sortedFormSections[r].sortedFormControls[e].isRequiredInput&&t.sortedFormSections[r].sortedFormControls[e].isAllowedInput&&t.sortedFormSections[r].sortedFormControls[e].controlTypeFilename!=="instructions.html"){for(o=!1,f=0;f<n.inspectionFormAnswers.length;f++)if(n.inspectionFormAnswers[f].formControlId===t.sortedFormSections[r].sortedFormControls[e].id)if(n.inspectionFormAnswers[f].isVisible){if(n.inspectionFormAnswers[f].controlValue!==undefined&&n.inspectionFormAnswers[f].controlValue!==null&&n.inspectionFormAnswers[f].controlValue.length>0)try{u=JSON.parse(n.inspectionFormAnswers[f].controlValue),u.answer!==undefined&&u.answer.length>0?o=!0:u.ampm!==undefined&&u.ampm.length>0&&u.hours!==undefined&&u.minutes!==undefined?o=!0:u.latitude!==undefined&&u.longitude!==null?o=!0:u.text!==undefined&&u.text!==null&&u.text!==""&&(o=!0)}catch(y){}}else o=!0;o||(c.push(t.sortedFormSections[r]),l=!0)}if(t.sortedFormSections[r].sortedFormControls[e].controlTypeFilename==="table.html"&&t.sortedFormSections[r].sortedFormControls[e].isAllowedInput)for(f=0;f<n.inspectionFormAnswers.length;f++)if(n.inspectionFormAnswers[f].formControlId===t.sortedFormSections[r].sortedFormControls[e].id&&n.inspectionFormAnswers[f].controlValue!==undefined&&n.inspectionFormAnswers[f].controlValue!==null&&n.inspectionFormAnswers[f].controlValue.length>0)try{for(u=JSON.parse(n.inspectionFormAnswers[f].controlValue),a=JSON.parse(t.sortedFormSections[r].sortedFormControls[e].controlDefinition),s=0;s<a.columns.length;s++)if(a.columns[s].isRequired&&u.answer.length>0){for(o=!1,h=0;h<u.answer.length;h++)u.answer[h][s]!==null&&u.answer[h][s]!==undefined&&u.answer[h][s]!==""&&(o=!0);if(!o){c.push(t.sortedFormSections[r]),l=!0;break}}}catch(y){}}}i(c)},app.validateInspectionForm=function(n,t){app.getInspectionForm(n,function(n){app.getFormVersion(n.formVersionId,function(i){app.validateInspectionFormWithData(n,i,t)},app.getDataFailed)},app.getDataFailed)},app.showRepeatingSections=function(n,t){app.getInspectionForm(n,function(n){app.getFormVersion(n.formVersionId,function(i){app.showRepeatingSectionsWithTableData(n,i,t)},app.getDataFailed)},app.getDataFailed)},app.loadForms=function(n){Wndsr.info("Load Forms for Inspection "+n),$.blockUI({message:"<h1>Please Wait...<\/h1>"}),app.getConflictList(function(t){if((t===null||t===undefined)&&(t=[]),t.length>0)for(var i=0;i<t.length;i++)if(t[i].inspectionId===n)return window.location=app.vroot()+"Synchronize/SyncConflict?inspectionId="+n,!1;Inspection.Load(n,function(n){app.displayForms(n)},app.getDataFailed)},app.getDataFailed)},app.getProfileOrganizations=function(n,t){app.getOrganizationList(function(t){var f=[],r,u,i;if(app.principal.organizationList===undefined)for(r=0;r<t.length;t++)f.push(t[r].id);else for(r=0;r<app.principal.organizationList.length;r++)if(!(f.indexOf(app.principal.organizationList[r])>=0)){for(f.push(app.principal.organizationList[r]),u=null,i=0;i<t.length;i++)if(app.principal.organizationList[r]===t[i].id){u=t[i].parentOrganizationId;continue}while(u!==null){if(f.indexOf(u)>=0){u=null;continue}for(f.push(u),i=0;i<t.length;i++)if(u===t[i].id){u=t[i].parentOrganizationId;continue}}}n(f)},t)},app.getInspectionTypes=function(n,t){app.getOrganizationList(function(i){app.getProfileOrganizations(function(t){for(var u=[],f,o,e,r=0;r<i.length;r++)if(t.indexOf(i[r].id)>=0)for(f=0;f<i[r].inspectionTypes.length;f++){for(o=!1,e=0;e<u.length;e++)u[e].id===i[r].inspectionTypes[f].id&&(o=!0);o||u.push(i[r].inspectionTypes[f])}u=u.sort(app.compareInspectionTypes),n(u)},t)},t)},app.compareInspectionTypes=function(n,t){return n.name<t.name?-1:n.name>t.name?1:0},app.getWebSqlKeys=function(t,i){try{n.transaction(function(n){n.executeSql("SELECT Key FROM KeyValue",[],function(n,i){i.rows.length===0?t(null):t(i)},function(){i()})})}catch(r){i()}},app.getWebSql=function(t,i,r){n.transaction(function(n){n.executeSql("SELECT Value FROM KeyValue WHERE Key = ?",[t],function(n,t){if(t.rows.length===0)i(null);else{var u=t.rows.item(0).Value,r=JSON.parse(u);i(r)}},function(){r()})})},app.setWebSql=function(t,i,r,u){var f=!1,e=null,o=0,s=t.replace(/\-/g,"").toUpperCase();n.transaction(function(e){e.executeSql("DELETE FROM KeyValue WHERE Key = ? OR Key = ?",[t,s],function(){n.transaction(function(n){n.executeSql("INSERT INTO KeyValue (Key, Value) VALUES(?, ?)",[t,JSON.stringify(i)],function(){f=!0,r()},function(n,t){alert("Oops. Error was "+t.message+" (Code "+t.code+")"),u()})})},function(n,t){alert("Oops. Error was "+t.message+" (Code "+t.code+")"),u()})}),/iphone|ipad/i.test(navigator.userAgent)&&(e=setInterval(function(){o++,f?clearInterval(e):o<7?n.transaction(function(e){e.executeSql("DELETE FROM KeyValue WHERE Key = ?",[t],function(){n.transaction(function(n){n.executeSql("INSERT INTO KeyValue (Key, Value) VALUES(?, ?)",[t,JSON.stringify(i)],function(){f=!0,r()},function(n,t){alert("Oops. Error was "+t.message+" (Code "+t.code+")"),u()})})},function(n,t){alert("Oops. Error was "+t.message+" (Code "+t.code+")"),u()})}):(clearInterval(e),alert("Waiting for iPad database size increase..."),n.transaction(function(e){e.executeSql("DELETE FROM KeyValue WHERE Key = ?",[t],function(){n.transaction(function(n){n.executeSql("INSERT INTO KeyValue (Key, Value) VALUES(?, ?)",[t,JSON.stringify(i)],function(){f=!0,r()},function(n,t){alert("Oops. Error was "+t.message+" (Code "+t.code+")"),u()})})},function(n,t){alert("Oops. Error was "+t.message+" (Code "+t.code+")"),u()})}),setTimeout(function(){f||(alert("Maximum size of iPad database exceeded.  Cannot save any more photos or answers on the iPad."),u())},5e3))},5e3))},app.deleteWebSql=function(t,i,r){n.transaction(function(n){n.executeSql("DELETE FROM KeyValue WHERE Key = ?",[t],function(){i()},function(){r()})})},app.clearWebSql=function(){n.transaction(function(n){n.executeSql("DELETE FROM KeyValue",[],null,null)})},app.getFormVersionList=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getFormVersionList - isMobile = "+r),r?app.getWebSql("formVersionList",n,t):i!==null&&i!==undefined&&i.length>0?$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetFormVersionListForInspection/"+i,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t}):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetFormVersionList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getOrganizationList=function(n,t){var i=app.isMobile();Wndsr.info("app.getOrganizationList - isMobile = "+i),i?app.getWebSql("organizationList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetOrganizationList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getProjectList=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getProjectList - isMobile = "+r),r&&!i?app.getWebSql("projectList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetProjectList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getPrincipalList=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getPrincipalList - isMobile = "+r),r&&!i?app.getWebSql("principalList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetPrincipalList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getPrincipal=function(n,t){var r=app.isMobile();Wndsr.info("app.getPrincipal - isMobile = "+r),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetUserPrincipal",contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getSensitivePrincipalList=function(n,t){var i=app.isMobile();Wndsr.info("app.getSensitivePrincipalList - isMobile = "+i),i?app.getWebSql("principalSensitiveList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetSensitivePrincipalList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getInspectionList=function(n,t){var i=app.isMobile();Wndsr.info("app.getInspectionList - isMobile = "+i),i?app.getWebSql("inspectionList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getInspectionFormList=function(n,t){var i=app.isMobile();Wndsr.info("app.getInspectionFormList - isMobile = "+i),i?app.getWebSql("inspectionFormList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionFormList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getInspectionFormMediaList=function(n,t){var i=app.isMobile();Wndsr.info("app.getInspectionFormMediaList - isMobile = "+i),i?app.getWebSql("inspectionFormMediaList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionFormMediaList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getConflictList=function(n,t){var i=app.isMobile();Wndsr.info("app.getConflictList - isMobile = "+i),i&&!app.isOnline?app.getWebSql("conflictList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetConflictList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getConflictListInspection=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getConflictListInspection - isMobile = "+r),r?app.getWebSql("conflictList",t,i):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetConflictListInspection/"+n,contentType:"application/json; charset=utf-8",success:t,headers:{"cache-control":"no-cache"},error:i})},app.clearConflictList=function(n,t){var i=app.isMobile();Wndsr.info("app.clearConflictList - isMobile = "+i),i?app.setWebSql("conflictList",[],n,t):n()},app.getFormVersion=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getFormVersion - isMobile = "+r),r?app.getWebSql(n,t,i):app.post(app.vroot()+"Synchronize/GetFormVersion/",{id:n},t,i)},app.getInspection=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.getInspection - isMobile = "+u),u&&!r?app.getWebSql(n,t,i):app.post(app.vroot()+"Synchronize/GetInspection/",{id:n},t,i)},app.getProject=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.getProject - isMobile = "+u),u&&!r?app.getWebSql(n,t,i):app.post(app.vroot()+"Synchronize/GetProject/",{id:n},t,i)},app.getInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getInspectionForm - isMobile = "+r),r?app.getWebSql(n,t,i):app.post(app.vroot()+"Synchronize/GetInspectionForm/",{id:n},t,i)},app.getInspectionFormMedia=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getInspectionFormMedia - isMobile = "+r),r?app.getWebSql(n,t,i):app.post(app.vroot()+"Synchronize/GetInspectionFormMedia/",{id:n},t,i)},app.deleteInspectionFormMedia=function(n,t,i){var r=app.isMobile();Wndsr.info("app.deleteInspectionFormMedia - isMobile = "+r+" id = "+n),r?app.getInspectionFormMediaList(function(r){(r===null||r===undefined)&&(r=[]);for(var u in r)if(r[u].id===n){r[u].isDeleted=!0;break}app.setWebSql("inspectionFormMediaList",r,function(){app.deleteWebSql(n,t,i)},i)},i):app.post(app.vroot()+"Synchronize/DeleteInspectionFormMedia/",{id:n},t,i)},app.updateInspection=function(n,t,i,r){var u=app.isMobile(),f=n.completed!==null&&n.completed!==undefined;Wndsr.info("app.updateInspection - isMobile = "+u+", inspectionId = "+n.id),u&&!r?app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.id){r[u].isDirty=!0,r[u].isComplete=f,r[u].actualStart=n.actualStart,r[u].requestReviewDate=n.requestReviewDate,r[u].type=n.inspectionTypeCode,r[u].scheduledStart=n.scheduledStart,n.siteKey!==undefined?r[u].siteKey=n.siteKey:n.site!==undefined&&n.site.siteKey!==undefined&&(r[u].siteKey=n.site.siteKey);break}app.setWebSql("inspectionList",r,function(){app.setWebSql(n.id,n,t,i)},i)},i):app.post(app.vroot()+"Synchronize/UpdateInspection/",{inspection:n},t,i)},app.updateInspectionFormScore=function(n,t,i){app.post(app.vroot()+"Synchronize/UpdateInspectionFormScore/",{inspectionForm:n},function(n){t&&t(n)},i)},app.updateInspectionFormSection=function(n,t,i){app.post(app.vroot()+"Synchronize/UpdateInspectionFormSection/",{inspectionFormSection:n},function(n){t&&t(n)},i)},app.updateInspectionFormRepeatingSection=function(n,t,i){app.post(app.vroot()+"Synchronize/UpdateInspectionFormRepeatingSection/",{inspectionFormRepeatingSection:n},function(n){t&&t(n)},i)},app.updateInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.updateInspectionForm - isMobile = "+r+", inspectionFormId = "+n.id),r?app.getInspectionFormList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.id){r[u].isDirty=!0;break}app.setWebSql("inspectionFormList",r,function(){app.setWebSql(n.id,n,function(){app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.inspectionId){r[u].isFormDirty=!0,app.setWebSql("inspectionList",r,function(){t({inspectionForm:n,isConflict:!1})},i);break}},i)},i)},i)},i):app.post(app.vroot()+"Synchronize/UpdateInspectionForm/",{inspectionForm:n},function(i){n=i.inspectionForm,t(i)},i)},app.updateInspectionFormAnswers=function(n,t,i,r,u){var f=app.isMobile();Wndsr.info("app.updateInspectionFormAnswers - isMobile = "+f+", inspectionFormId = "+n),f?Wndsr.error("Error - attempt to save answers in a mobile mode"):app.post(app.vroot()+"Synchronize/UpdateInspectionFormAnswers/",{inspectionFormId:n,inspectionFormAnswers:t,dataVersion:i},function(n){r(n)},u)},app.addInspectionFormRepeatingSection=function(n,t,i){var r=app.isMobile();Wndsr.info("app.addInspectionFormRepeatingSection - isMobile = "+r+", inspectionFormRepeatingSectionId = "+n.id),n.isDirty=!0,n.isNew=!0,r?t(!0):app.post(app.vroot()+"Synchronize/AddInspectionFormRepeatingSection/",{inspectionFormRepeatingSection:n},function(n){t(n)},i)},app.deleteInspectionFormRepeatingSection=function(n,t,i){var r=app.isMobile(),u;Wndsr.info("app.deleteInspectionFormRepeatingSection - isMobile = "+r+", inspectionFormRepeatingSectionId = "+n.id),n.isDirty=!0,n.isDeleted=!0,r?u=0:app.post(app.vroot()+"Synchronize/DeleteInspectionFormRepeatingSection/",{inspectionFormRepeatingSection:n},function(n){t(n)},i)},app.addInspectionFormMedia=function(n,t,i,r,u,f,e,o,s,h,c,l,a){var v=app.isMobile();Wndsr.info("app.addInspectionFormMedia - isMobile = "+v+", inspectionFormId = "+n.id),t.isDirty=!0,v?app.getInspectionFormMediaList(function(v){(v===null||v===undefined)&&(v=[]);var y={};y.id=app.createUUID(),y.changedOn=new moment,y.isDirty=!0,y.isNew=!0,y.isDeleted=!1,t.inspectionFormMedia.push({id:y.id,isNew:!0,isDirty:!0,isDeleted:!1,mediaPath:"",mimeType:i,metadataComment:c,metaDataTags:"",mediaObject:r,imageCapturedTime:h,gpsLatitude:u,gpsLongitude:f,gpsAltitude:e,gpsAzimuth:o,gpsOrientation:s}),v.push(y),app.setWebSql("inspectionFormMediaList",v,function(){var v={};v.id=y.id,v.mediaPath="",v.mimeType=i,v.metadataComment=c,v.metaDataTags="",v.mediaObject=r,v.imageCapturedTime=h,v.gpsLatitude=u,v.gpsLongitude=f,v.gpsAltitude=e,v.gpsAzimuth=o,v.gpsOrientation=s,v.isDirty=!1,v.isNew=!1,v.isDeleted=!1,app.setWebSql(v.id,v,function(){app.updateInspectionForm(n,function(){l(v.id,t)},a)},a)},a)},a):app.post(app.vroot()+"Synchronize/AddInspectionFormMedia/",{inspectionFormAnswer:t,mimeType:i,mediaObject:r,latitude:u,longitude:f,altitude:e,azimuth:o,orientation:s,imageDateTime:h,comment:c},function(i){t=i.inspectionFormAnswer,n.dataVersion=i.dataVersion,l(i.inspectionFormMedia.id,t)},a)},app.updateInspectionFormMedia=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.updateInspectionFormMedia - isMobile = "+u+", inspectionFormMediaId = "+n),u?app.getInspectionFormMediaList(function(u){(u===null||u===undefined)&&(u=[]);for(var f in u)if(u[f].id===n){u[f].isDirty=!0;break}app.setWebSql("inspectionFormMediaList",u,function(){app.getWebSql(n,function(u){u.metadataComment=t,app.setWebSql(n,u,i,r)},r)},r)},r):app.post(app.vroot()+"Synchronize/UpdateInspectionFormMedia/",{id:n,comment:t},function(){i()},r)},app.addInspection=function(n,t,r){var u=app.isMobile(),f=n.completed!==null&&n.completed!==undefined;Wndsr.info("app.addInspection - isMobile = "+u+", inspectionId = "+n.id),u?app.getInspectionList(function(u){var e={};e.id=n.id,e.scheduledStart=n.scheduledStart,e.actualStart=n.actualStart,u[i].requestReviewDate=n.requestReviewDate,e.siteName=n.site.siteName,e.siteCity=n.site.siteAddresses[0].city,e.siteKey=n.site.siteKey,e.siteAddress="",e.type=n.inspectionTypeCode,e.changedOn=n.changedOn,e.isDirty=!0,e.isDeleted=!1,e.isNew=!0,e.isComplete=f,u.push(e),app.setWebSql("inspectionList",u,function(){app.setWebSql(n.id,n,t,r)},r)},r):app.post(app.vroot()+"Synchronize/NewInspection/",{inspection:n},t,r)},app.addInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.addInspectionForm - isMobile = "+r+", inspectionFormId = "+n.id),r?app.getInspectionFormList(function(r){var u={};u.id=n.id,u.inspectionId=n.inspectionId,u.dataVersion=n.dataVersion,u.changedOn=n.changedOn,u.isDirty=!0,u.isDeleted=!1,u.isNew=!0,r.push(u),app.setWebSql("inspectionFormList",r,function(){app.getInspectionForm(u.inspectionId,function(r){r.inspectionFormInfoList.push({id:n.id,isActive:!0,formVersionId:n.formVersionId,isDeleted:!1}),r.isDirty=!0,app.setWebSql(r.id,r,function(){app.setWebSql(n.id,n,function(){app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.inspectionId){r[u].isFormDirty=!0,app.setWebSql("inspectionList",r,function(){t({inspectionForm:n,isConflict:!1})},i);break}},i)},i)},i)},i)},i)},i):app.post(app.vroot()+"Synchronize/NewInspectionForm/",{inspectionForm:n},t,i)},app.deleteInspection=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.deleteInspection - isMobile = "+u+", inspectionId = "+n),!r&&u?app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n){r[u].isDirty=!0,r[u].isDeleted=!0;break}app.setWebSql("inspectionList",r,t,i)},i):app.post(app.vroot()+"Synchronize/DeleteInspection/",{id:n},t,i)},app.deleteInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.deleteInspectionForm - isMobile = "+r+", inspectionId = "+n),r?app.getInspectionFormList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n){r[u].isDirty=!0,r[u].isDeleted=!0;break}app.setWebSql("inspectionFormList",r,function(){app.getWebSql(n,function(r){app.getWebSql(r.inspectionId,function(u){for(var f=0;f<u.inspectionFormInfoList.length;f++)if(u.inspectionFormInfoList[f].id===n){u.inspectionFormInfoList[f].isDeleted=!0;break}app.setWebSql(r.inspectionId,u,function(){app.getInspectionList(function(n){for(var u=0;u<n.length;u++)if(n[u].id===r.inspectionId){n[u].isFormDirty=!0,app.setWebSql("inspectionList",n,function(){t({inspectionForm:r,isConflict:!1})},i);break}},i)},i)},i)},i)},i)},i):app.post(app.vroot()+"Synchronize/DeleteInspectionForm/",{id:n},t,i)})})(),function(){app.persist={},app.persist.dbName="nSpect",app.persist.dbVersion=26,app.persist.syncSession=null,window.indexedDB=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,window.IDBTransaction=window.IDBTransaction||window.webkitIDBTransaction||window.msIDBTransaction,window.IDBKeyRange=window.IDBKeyRange||window.webkitIDBKeyRange||window.msIDBKeyRange,window.indexedDB||window.alert("Your browser doesn't support a stable version of IndexedDB."),app.persist.db=null,app.persist.dbErrror=function(n){Wndsr.error("Error opening "+app.persist.dbName+" DB",n),alert("Error opening "+app.persist.dbName+" DB")};var n=window.indexedDB.open(app.persist.dbName,app.persist.dbVersion);n.onerror=function(n){Wndsr.error("Error opening "+app.persist.dbName+" DB",n),alert("Error opening "+app.persist.dbName+" DB")},n.onsuccess=function(){Wndsr.info("Successfully connected to "+app.persist.dbName+" DB"),app.persist.db=n.result,app.persist.db.onerror=app.persist.dbErrror},n.onupgradeneeded=function(n){var u,f,r,t,i;Wndsr.info("Upgradinging DB"),app.persist.db=n.target.result,app.persist.db.onerror=app.persist.dbErrror;try{app.persist.db.deleteObjectStore("inspection")}catch(e){}app.persist.db.createObjectStore("inspection",{keyPath:"id"});try{app.persist.db.deleteObjectStore("inspectionCmeValue")}catch(e){}app.persist.db.createObjectStore("inspectionCmeValue",{keyPath:"id"});try{app.persist.db.deleteObjectStore("inspectionForm")}catch(e){}app.persist.db.createObjectStore("inspectionForm",{keyPath:"id"});try{app.persist.db.deleteObjectStore("inspectionFormSection")}catch(e){}app.persist.db.createObjectStore("inspectionFormSection",{keyPath:"id"});try{app.persist.db.deleteObjectStore("inspectionFormRepeatingSection")}catch(e){}app.persist.db.createObjectStore("inspectionFormRepeatingSection",{keyPath:"id"});try{app.persist.db.deleteObjectStore("inspectionFormAnswer")}catch(e){}u=app.persist.db.createObjectStore("inspectionFormAnswer",{keyPath:"id"}),u.createIndex("inspectionId","inspectionId",{unique:!1});try{app.persist.db.deleteObjectStore("inspectionFormMedia")}catch(e){}f=app.persist.db.createObjectStore("inspectionFormMedia",{keyPath:"id"}),f.createIndex("inspectionId","inspectionId",{unique:!1});try{app.persist.db.deleteObjectStore("keyValue")}catch(e){}app.persist.db.createObjectStore("keyValue",{keyPath:"key"});try{app.persist.db.deleteObjectStore("site")}catch(e){}app.persist.db.createObjectStore("site",{keyPath:"id"});try{app.persist.db.deleteObjectStore("siteAddress")}catch(e){}app.persist.db.createObjectStore("siteAddress",{keyPath:"id"});try{app.persist.db.deleteObjectStore("principal")}catch(e){}r=app.persist.db.createObjectStore("principal",{keyPath:"id"}),r.createIndex("displayName","displayName",{unique:!1});try{app.persist.db.deleteObjectStore("project")}catch(e){}app.persist.db.createObjectStore("project",{keyPath:"id"});try{app.persist.db.deleteObjectStore("autoAssignForm")}catch(e){}app.persist.db.createObjectStore("autoAssignForm",{keyPath:"id"});try{app.persist.db.deleteObjectStore("group")}catch(e){}app.persist.db.createObjectStore("group",{keyPath:"id"});try{app.persist.db.deleteObjectStore("groupRole")}catch(e){}app.persist.db.createObjectStore("groupRole",{keyPath:"id"});try{app.persist.db.deleteObjectStore("organization")}catch(e){}app.persist.db.createObjectStore("organization",{keyPath:"id"});try{app.persist.db.deleteObjectStore("orgGroup")}catch(e){}app.persist.db.createObjectStore("orgGroup",{keyPath:"id"});try{app.persist.db.deleteObjectStore("role")}catch(e){}app.persist.db.createObjectStore("role",{keyPath:"id"});try{app.persist.db.deleteObjectStore("inspectionType")}catch(e){}app.persist.db.createObjectStore("inspectionType",{keyPath:"id"});try{app.persist.db.deleteObjectStore("orgInspectionType")}catch(e){}app.persist.db.createObjectStore("orgInspectionType",{keyPath:"id"});try{app.persist.db.deleteObjectStore("form")}catch(e){}app.persist.db.createObjectStore("form",{keyPath:"id"});try{app.persist.db.deleteObjectStore("formVersion")}catch(e){}app.persist.db.createObjectStore("formVersion",{keyPath:"id"});try{app.persist.db.deleteObjectStore("formSection")}catch(e){}t=app.persist.db.createObjectStore("formSection",{keyPath:"id"}),t.createIndex("formVersionId","formVersionId",{unique:!1});try{app.persist.db.deleteObjectStore("formControl")}catch(e){}i=app.persist.db.createObjectStore("formControl",{keyPath:"id"}),i.createIndex("formVersionId","formVersionId",{unique:!1});try{app.persist.db.deleteObjectStore("file")}catch(e){}app.persist.db.createObjectStore("file",{keyPath:"fileName"})},app.persist.getFile=function(n,t,i,r){if(app.isMobile()){var e=[],f=app.persist.db.transaction("file").objectStore("file"),u=f.get(n);u.onerror=function(t){console.log("Error getting image fileName = "+n),Wndsr.error("Error getting image fileName = "+n,t),i(t)},u.onsuccess=function(){console.log("image found for fileName = "+n),Wndsr.info("image found for fileName = "+n),u.result?t(u.result,r):t(null,r)}}else app.post(app.vroot()+"Mobile/GetImageWeb/",{id:n},function(n){t(n,r)},i)},app.persist.putFile=function(n,t,i,r){if(app.isMobile()){var f=app.persist.db.transaction("file","readwrite").objectStore("file"),e={fileName:n.id,data:t},u=f.put(e);u.onsuccess=function(n){i(n)},u.onerror=function(n){Wndsr.error("Error putting file",n),r(n)}}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadImageWeb/",{syncSession:app.persist.syncSession,inspectionFormMediaId:n.id,mediaObject:t},function(){i(event)},r):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadImageWeb/",{syncSession:app.persist.syncSession,inspectionFormMediaId:n.id,mediaObject:t},function(){i(event)},r)},r)},app.persist.requestSync=function(n,t){app.isMobile()||(Wndsr.info("Requesting Sync"),app.post(app.vroot()+"Mobile/RequestSync/",{syncSession:null,deviceId:null},function(t){Wndsr.info("Finish Sending changes to server"),app.persist.syncSession=t.syncSession,n()},t))},app.persist.syncChanges=function(n,t){app.isMobile()?n():(Wndsr.info("Sending changes to server"),app.post(app.vroot()+"Mobile/ProcessUpload/",{syncSession:app.persist.syncSession},function(){Wndsr.info("Finish Sending changes to server"),app.persist.syncSession=null,n()},t))},app.persist.getKeyValue=function(n,t,i){Wndsr.info("Getting KeyValue Key = "+n);var u=app.persist.db.transaction(["keyValue"]),f=u.objectStore("keyValue"),r=f.get(n);r.onerror=function(t){Wndsr.error("Error getting KeyValue key = "+n,t),i(t)},r.onsuccess=function(){Wndsr.info("KeyValue found for key = "+n),r.result?t(r.result.value):t(null)}},app.persist.setKeyValue=function(n,t,i,r){Wndsr.info("Setting KeyValue Key = "+n);var u=app.persist.db.transaction(["keyValue"],"readwrite").objectStore("keyValue").put({key:n,value:t});u.onsuccess=function(){Wndsr.info("KeyValue set for key = "+n),i(!0)},u.onerror=function(t){Wndsr.error("Error setting KeyValue key = "+n,t),r(t)}},app.persist.getInspectionIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspection"]),u=r.objectStore("inspection"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspection Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionIds should only be called on mobile")},app.persist.getInspection=function(n,t,i){app.post(app.vroot()+"Mobile/GetInspection/",{id:n},function(n){t(n)},i)},app.persist.getUnassignedInspection=function(n,t,i){app.post(app.vroot()+"Mobile/GetUnassignedInspection/",{inspectionId:n},function(n){t(n)},i)},app.persist.getReviewInspection=function(n,t,i){app.post(app.vroot()+"Mobile/GetReviewInspection/",{inspectionId:n},function(n){t(n)},i)},app.persist.updateUnassignedInspection=function(n,t,i){app.post(app.vroot()+"Mobile/UpdateUnassignedInspection/",{inspectionId:n.id,principalId:n.principalId,inspectionTypeCode:n.inspectionTypeCode,scheduledStart:n.scheduledStart,actualStart:n.actualStart},function(){t()},i)},app.persist.updateReviewInspection=function(n,t,i){app.post(app.vroot()+"Mobile/UpdateReviewInspection/",{inspectionId:n.id,principalId:n.principalId,inspectionTypeCode:n.inspectionTypeCode,scheduledStart:n.scheduledStart,actualStart:n.actualStart,siteKey:n.siteKey,reviewRequestDate:n.reviewRequestDate,reviewPrincipalId:n.reviewPrincipalId},function(){t()},i)},app.persist.getInspections=function(n,t){if(app.isMobile())if(app.persist.db){var r=[],u=app.persist.db.transaction("inspection").objectStore("inspection"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspections",n),t(n)}}else setTimeout(function(){app.persist.getInspections(n,t)},10);else app.post(app.vroot()+"Mobile/GetInspections/",{inspectionIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getDirtyInspections=function(n,t){if(app.persist.db){var r=[],u=app.persist.db.transaction("inspection").objectStore("inspection"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(i.value.isDirty&&r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting dirty inspections",n),t(n)}}else setTimeout(function(){app.persist.getDirtyInspections(n,t)},10)},app.persist.putInspection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspection","readwrite").objectStore("inspection"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting inspection",n),pu,i(n)}}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspections/",{syncSession:app.persist.syncSession,inspections:[n]},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspections/",{syncSession:app.persist.syncSession,inspections:[n]},function(){t(event)},i)},i)},app.persist.putInspections=function(n,t,i){if(n.length===0)t();else if(app.isMobile()){var r=n.pop();app.persist.putInspection(r,function(){app.persist.putInspections(n,t,i)},i)}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspections/",{syncSession:app.persist.syncSession,inspections:n},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspections/",{syncSession:app.persist.syncSession,inspections:n},function(){t(event)},i)},i)},app.persist.deleteInspection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspection","readwrite").objectStore("inspection"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing inspections",n),i(n)}}},app.persist.deleteInspections=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspection(r,function(){app.persist.deleteInspections(n,t,i)},i)}},app.persist.getSiteIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["site"]),u=r.objectStore("site"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all site Ids"),t(n)}}else Wndsr.error("app.persist.getSiteIds should only be called on mobile")},app.persist.getSites=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("site").objectStore("site"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting sites",n),t(n)}}else app.post(app.vroot()+"Mobile/GetSites/",{siteIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getSiteForInspection=function(n,t,i){app.post(app.vroot()+"Mobile/GetSiteForInspection/",{inspectionId:n},function(n){t(n)},i)},app.persist.putSite=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("site","readwrite").objectStore("site"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting site",n),i(n)}}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadSites/",{syncSession:app.persist.syncSession,sites:[n]},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadSites/",{syncSession:app.persist.syncSession,sites:[n]},function(){t(event)},i)},i)},app.persist.putSites=function(n,t,i){if(n.length===0)t();else if(app.isMobile()){var r=n.pop();app.persist.putSite(r,function(){app.persist.putSites(n,t,i)},i)}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadSites/",{syncSession:app.persist.syncSession,sites:n},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadSites/",{syncSession:app.persist.syncSession,sites:n},function(){t(event)},i)},i)},app.persist.deleteSite=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("site","readwrite").objectStore("site"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing sites",n),i(n)}}},app.persist.deleteSites=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteSite(r,function(){app.persist.deleteSites(n,t,i)},i)}},app.persist.getSiteAddressIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["siteAddress"]),u=r.objectStore("siteAddress"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all siteAddress Ids"),t(n)}}else Wndsr.error("app.persist.getSiteAddressIds should only be called on mobile")},app.persist.getSiteAddresses=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("siteAddress").objectStore("siteAddress"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting siteAddresses",n),t(n)}}else app.post(app.vroot()+"Mobile/GetSiteAddresses/",{siteAddressIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putSiteAddress=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("siteAddress","readwrite").objectStore("siteAddress"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting siteAddress",n),i(n)}}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadSiteAddresses/",{syncSession:app.persist.syncSession,siteAddresses:[n]},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadSiteAddresses/",{syncSession:app.persist.syncSession,siteAddresses:[n]},function(){t(event)},i)},i)},app.persist.putSiteAddresses=function(n,t,i){if(n.length===0)t();else if(app.isMobile()){var r=n.pop();app.persist.putSiteAddress(r,function(){app.persist.putSiteAddresses(n,t,i)},i)}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadSiteAddresses/",{syncSession:app.persist.syncSession,siteAddresses:n},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadSiteAddresses/",{syncSession:app.persist.syncSession,siteAddresses:n},function(){t(event)},i)},i)},app.persist.deleteSiteAddress=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("siteAddress","readwrite").objectStore("siteAddress"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing siteAddresses",n),i(n)}}},app.persist.deleteSiteAddresses=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteSiteAddress(r,function(){app.persist.deleteSiteAddresses(n,t,i)},i)}},app.persist.getPrincipalIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["principal"]),u=r.objectStore("principal"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all principal Ids"),t(n)}}else Wndsr.error("app.persist.getPrincipalIds should only be called on mobile")},app.persist.getPrincipals=function(n,t){if(app.isMobile())if(app.persist.db){var r=[],u=app.persist.db.transaction("principal").objectStore("principal"),f=u.index("displayName"),i=f.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting principals",n),t(n)}}else setTimeout(function(){app.persist.getPrincipals(n,t)},10);else app.post(app.vroot()+"Mobile/GetPrincipals/",{principalIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putPrincipal=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("principal","readwrite").objectStore("principal"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting principal",n),i(n)}}},app.persist.putPrincipals=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putPrincipal(r,function(){app.persist.putPrincipals(n,t,i)},i)}},app.persist.deletePrincipal=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("principal","readwrite").objectStore("principal"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing principals",n),i(n)}}},app.persist.deletePrincipals=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deletePrincipal(r,function(){app.persist.deletePrincipals(n,t,i)},i)}},app.persist.getProjectIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["project"]),u=r.objectStore("project"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all project Ids"),t(n)}}else Wndsr.error("app.persist.getProjectIds should only be called on mobile")},app.persist.getProjects=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("project").objectStore("project"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting projects",n),t(n)}}else app.post(app.vroot()+"Mobile/GetProjects/",{projectIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putProject=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("project","readwrite").objectStore("project"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting project",n),i(n)}}},app.persist.putProjects=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putProject(r,function(){app.persist.putProjects(n,t,i)},i)}},app.persist.deleteProject=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("project","readwrite").objectStore("project"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing projects",n),i(n)}}},app.persist.deleteProjects=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteProject(r,function(){app.persist.deleteProjects(n,t,i)},i)}},app.persist.getAutoAssignFormIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["autoAssignForm"]),u=r.objectStore("autoAssignForm"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all autoAssignForm Ids"),t(n)}}else Wndsr.error("app.persist.getAutoAssignFormIds should only be called on mobile")},app.persist.getAutoAssignForms=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("autoAssignForm").objectStore("autoAssignForm"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting autoAssignForms",n),t(n)}}else app.post(app.vroot()+"Mobile/GetAutoAssignForms/",{autoAssignFormIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putAutoAssignForm=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("autoAssignForm","readwrite").objectStore("autoAssignForm"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting autoAssignForm",n),i(n)}}},app.persist.putAutoAssignForms=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putAutoAssignForm(r,function(){app.persist.putAutoAssignForms(n,t,i)},i)}},app.persist.deleteAutoAssignForm=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("autoAssignForm","readwrite").objectStore("autoAssignForm"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing autoAssignForms",n),i(n)}}},app.persist.deleteAutoAssignForms=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteAutoAssignForm(r,function(){app.persist.deleteAutoAssignForms(n,t,i)},i)}},app.persist.getGroupIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["group"]),u=r.objectStore("group"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all group Ids"),t(n)}}else Wndsr.error("app.persist.getGroupIds should only be called on mobile")},app.persist.getGroups=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("group").objectStore("group"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting groups",n),t(n)}}else app.post(app.vroot()+"Mobile/GetGroups/",{groupIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putGroup=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("group","readwrite").objectStore("group"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting group",n),i(n)}}},app.persist.putGroups=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putGroup(r,function(){app.persist.putGroups(n,t,i)},i)}},app.persist.deleteGroup=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("group","readwrite").objectStore("group"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing groups",n),i(n)}}},app.persist.deleteGroups=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteGroup(r,function(){app.persist.deleteGroups(n,t,i)},i)}},app.persist.getGroupRoleIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["groupRole"]),u=r.objectStore("groupRole"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all groupRole Ids"),t(n)}}else Wndsr.error("app.persist.getGroupRoleIds should only be called on mobile")},app.persist.getGroupRoles=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("groupRole").objectStore("groupRole"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting groupRoles",n),t(n)}}else app.post(app.vroot()+"Mobile/GetGroupRoles/",{groupRoleIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putGroupRole=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("groupRole","readwrite").objectStore("groupRole"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting groupRole",n),i(n)}}},app.persist.putGroupRoles=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putGroupRole(r,function(){app.persist.putGroupRoles(n,t,i)},i)}},app.persist.deleteGroupRole=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("groupRole","readwrite").objectStore("groupRole"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing groupRoles",n),i(n)}}},app.persist.deleteGroupRoles=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteGroupRole(r,function(){app.persist.deleteGroupRoles(n,t,i)},i)}},app.persist.getOrganizationIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["organization"]),u=r.objectStore("organization"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all organization Ids"),t(n)}}else Wndsr.error("app.persist.getOrganizationIds should only be called on mobile")},app.persist.getOrganizations=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("organization").objectStore("organization"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting organizations",n),t(n)}}else app.post(app.vroot()+"Mobile/GetOrganizations/",{organizationIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putOrganization=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("organization","readwrite").objectStore("organization"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting organization",n),i(n)}}},app.persist.putOrganizations=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putOrganization(r,function(){app.persist.putOrganizations(n,t,i)},i)}},app.persist.deleteOrganization=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("organization","readwrite").objectStore("organization"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing organizations",n),i(n)}}},app.persist.deleteOrganizations=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteOrganization(r,function(){app.persist.deleteOrganizations(n,t,i)},i)}},app.persist.getOrgGroupIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["orgGroup"]),u=r.objectStore("orgGroup"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all orgGroup Ids"),t(n)}}else Wndsr.error("app.persist.getOrgGroupIds should only be called on mobile")},app.persist.getOrgGroups=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("orgGroup").objectStore("orgGroup"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting orgGroups",n),t(n)}}else app.post(app.vroot()+"Mobile/GetOrgGroups/",{orgGroupIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putOrgGroup=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("orgGroup","readwrite").objectStore("orgGroup"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting orgGroup",n),i(n)}}},app.persist.putOrgGroups=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putOrgGroup(r,function(){app.persist.putOrgGroups(n,t,i)},i)}},app.persist.deleteOrgGroup=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("orgGroup","readwrite").objectStore("orgGroup"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing orgGroups",n),i(n)}}},app.persist.deleteOrgGroups=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteOrgGroup(r,function(){app.persist.deleteOrgGroups(n,t,i)},i)}},app.persist.getRoleIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["role"]),u=r.objectStore("role"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all role Ids"),t(n)}}else Wndsr.error("app.persist.getRoleIds should only be called on mobile")},app.persist.getRoles=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("role").objectStore("role"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting roles",n),t(n)}}else app.post(app.vroot()+"Mobile/GetRoles/",{roleIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putRole=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("role","readwrite").objectStore("role"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting role",n),i(n)}}},app.persist.putRoles=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putRole(r,function(){app.persist.putRoles(n,t,i)},i)}},app.persist.deleteRole=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("role","readwrite").objectStore("role"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing roles",n),i(n)}}},app.persist.deleteRoles=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteRole(r,function(){app.persist.deleteRoles(n,t,i)},i)}},app.persist.getInspectionTypeIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspectionType"]),u=r.objectStore("inspectionType"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspectionType Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionTypeIds should only be called on mobile")},app.persist.getInspectionTypes=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("inspectionType").objectStore("inspectionType"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspectionTypes",n),t(n)}}else app.post(app.vroot()+"Mobile/GetInspectionTypes/",{inspectionTypeIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putInspectionType=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionType","readwrite").objectStore("inspectionType"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting inspectionType",n),i(n)}}},app.persist.putInspectionTypes=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putInspectionType(r,function(){app.persist.putInspectionTypes(n,t,i)},i)}},app.persist.deleteInspectionType=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionType","readwrite").objectStore("inspectionType"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing inspectionTypes",n),i(n)}}},app.persist.deleteInspectionTypes=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspectionType(r,function(){app.persist.deleteInspectionTypes(n,t,i)},i)}},app.persist.getOrgInspectionTypeIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["orgInspectionType"]),u=r.objectStore("orgInspectionType"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all orgInspectionType Ids"),t(n)}}else Wndsr.error("app.persist.getOrgInspectionTypeIds should only be called on mobile")},app.persist.getOrgInspectionTypes=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("orgInspectionType").objectStore("orgInspectionType"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting orgInspectionTypes",n),t(n)}}else app.post(app.vroot()+"Mobile/GetOrgInspectionTypes/",{orgInspectionTypeIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putOrgInspectionType=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("orgInspectionType","readwrite").objectStore("orgInspectionType"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting orgInspectionType",n),i(n)}}},app.persist.putOrgInspectionTypes=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putOrgInspectionType(r,function(){app.persist.putOrgInspectionTypes(n,t,i)},i)}},app.persist.deleteOrgInspectionType=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("orgInspectionType","readwrite").objectStore("orgInspectionType"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing orgInspectionTypes",n),i(n)}}},app.persist.deleteOrgInspectionTypes=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteOrgInspectionType(r,function(){app.persist.deleteOrgInspectionTypes(n,t,i)},i)}},app.persist.getFormIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["form"]),u=r.objectStore("form"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all form Ids"),t(n)}}else Wndsr.error("app.persist.getFormIds should only be called on mobile")},app.persist.getForms=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("form").objectStore("form"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting forms",n),t(n)}}else app.post(app.vroot()+"Mobile/GetForms/",{formIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getForm=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("form").objectStore("form"),r=u.get(n);r.onsuccess=function(){t(r.result)},r.onerror=function(n){Wndsr.error("Error getting form",n),i(n)}}else app.post(app.vroot()+"Mobile/GetForm/",{id:n},function(n){t(n)},i)},app.persist.putForm=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("form","readwrite").objectStore("form"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting form",n),i(n)}}},app.persist.putForms=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putForm(r,function(){app.persist.putForms(n,t,i)},i)}},app.persist.deleteForm=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("form","readwrite").objectStore("form"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing forms",n),i(n)}}},app.persist.deleteForms=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteForm(r,function(){app.persist.deleteForms(n,t,i)},i)}},app.persist.getFormVersionIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["formVersion"]),u=r.objectStore("formVersion"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all formVersion Ids"),t(n)}}else Wndsr.error("app.persist.getFormVersionIds should only be called on mobile")},app.persist.getFormVersions=function(n,t,i){if(app.isMobile()){var u=[],f=app.persist.db.transaction("formVersion").objectStore("formVersion"),r=f.openCursor();r.onsuccess=function(t){var i=t.target.result;i?(u.push(i.value),i.continue()):n(u)},r.onerror=function(n){Wndsr.error("Error getting formVersions",n),t(n)}}else i?app.post(app.vroot()+"Mobile/GetFormVersions/",{formVersionIds:[],principalId:i,lastSyncTime:null},function(t){n(t.add)},t):app.post(app.vroot()+"Mobile/GetFormVersions/",{formVersionIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getFormVersion=function(n,t,i){if(app.isMobile())if(app.persist.db){var u=app.persist.db.transaction("formVersion").objectStore("formVersion"),r=u.get(n);r.onsuccess=function(){t(r.result)},r.onerror=function(n){Wndsr.error("Error getting formVersion",n),i(n)}}else setTimeout(function(){app.persist.getFormVersion(n,t,i)},10);else app.post(app.vroot()+"Mobile/GetFormVersion/",{id:n},function(n){t(n)},i)},app.persist.putFormVersion=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("formVersion","readwrite").objectStore("formVersion"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting formVersion",n),i(n)}}},app.persist.putFormVersions=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putFormVersion(r,function(){app.persist.putFormVersions(n,t,i)},i)}},app.persist.deleteFormVersion=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("formVersion","readwrite").objectStore("formVersion"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing formVersions",n),i(n)}}},app.persist.deleteFormVersions=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteFormVersion(r,function(){app.persist.deleteFormVersions(n,t,i)},i)}},app.persist.getFormSectionIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["formSection"]),u=r.objectStore("formSection"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all formSection Ids"),t(n)}}else Wndsr.error("app.persist.getFormSectionIds should only be called on mobile")},app.persist.getFormSections=function(n,t,i){if(app.isMobile()){var u=[],f=app.persist.db.transaction("formSection").objectStore("formSection"),r=f.openCursor();r.onsuccess=function(t){var i=t.target.result;i?(u.push(i.value),i.continue()):n(u)},r.onerror=function(n){Wndsr.error("Error getting formSections",n),t(n)}}else i?app.post(app.vroot()+"Mobile/GetFormSections/",{formSectionIds:[],principalId:i,lastSyncTime:null},function(t){n(t.add)},t):app.post(app.vroot()+"Mobile/GetFormSections/",{formSectionIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getFormSectionsByFormVersionId=function(n,t,i){if(app.isMobile()){var u=[],f=app.persist.db.transaction("formSection").objectStore("formSection"),o=f.index("formVersionId"),e=IDBKeyRange.only(n),r=o.openCursor(e);r.onsuccess=function(n){var i=n.target.result;i?(u.push(i.value),i.continue()):t(u)},r.onerror=function(n){Wndsr.error("Error getting formSections",n),i(n)}}else app.post(app.vroot()+"Mobile/GetFormSectionsByFormVersionId/",{formVersionId:n},function(n){t(n.add)},i)},app.persist.putFormSection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("formSection","readwrite").objectStore("formSection"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting formSection",n),i(n)}}},app.persist.putFormSections=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putFormSection(r,function(){app.persist.putFormSections(n,t,i)},i)}},app.persist.deleteFormSection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("formSection","readwrite").objectStore("formSection"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing formSections",n),i(n)}}},app.persist.deleteFormSections=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteFormSection(r,function(){app.persist.deleteFormSections(n,t,i)},i)}},app.persist.getFormControlIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["formControl"]),u=r.objectStore("formControl"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all formControl Ids"),t(n)}}else Wndsr.error("app.persist.getFormControlIds should only be called on mobile")},app.persist.getFormControls=function(n,t,i){if(app.isMobile()){var u=[],f=app.persist.db.transaction("formControl").objectStore("formControl"),r=f.openCursor();r.onsuccess=function(t){var i=t.target.result;i?(u.push(i.value),i.continue()):n(u)},r.onerror=function(n){Wndsr.error("Error getting formControls",n),t(n)}}else i?app.post(app.vroot()+"Mobile/GetFormControls/",{formControlIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t):app.post(app.vroot()+"Mobile/GetFormControls/",{formControlIds:[],principalId:i,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getFormControlsByFormVersionId=function(n,t,i){if(app.isMobile()){var u=[],f=app.persist.db.transaction("formControl").objectStore("formControl"),o=f.index("formVersionId"),e=IDBKeyRange.only(n),r=o.openCursor(e);r.onsuccess=function(n){var i=n.target.result;i?(u.push(i.value),i.continue()):t(u)},r.onerror=function(n){Wndsr.error("Error getting formSections",n),i(n)}}else app.post(app.vroot()+"Mobile/GetFormControlsByFormVersionId/",{formVersionId:n},function(n){t(n.add)},i)},app.persist.putFormControl=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("formControl","readwrite").objectStore("formControl"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting formControl",n),i(n)}}},app.persist.putFormControls=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putFormControl(r,function(){app.persist.putFormControls(n,t,i)},i)}},app.persist.deleteFormControl=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("formControl","readwrite").objectStore("formControl"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing formControls",n),i(n)}}},app.persist.deleteFormControls=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteFormControl(r,function(){app.persist.deleteFormControls(n,t,i)},i)}},app.persist.getInspectionCmeValueIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspectionCmeValue"]),u=r.objectStore("inspectionCmeValue"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspectionCmeValue Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionCmeValueIds should only be called on mobile")},app.persist.getInspectionCmeValues=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("inspectionCmeValue").objectStore("inspectionCmeValue"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspectionCmeValues",n),t(n)}}else app.post(app.vroot()+"Mobile/GetInspectionCmeValues/",{inspectionCmeValueIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putInspectionCmeValue=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionCmeValue","readwrite").objectStore("inspectionCmeValue"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting inspectionCmeValue",n),i(n)}}},app.persist.putInspectionCmeValues=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putInspectionCmeValue(r,function(){app.persist.putInspectionCmeValues(n,t,i)},i)}},app.persist.deleteInspectionCmeValue=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionCmeValue","readwrite").objectStore("inspectionCmeValue"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing inspectionCmeValues",n),i(n)}}},app.persist.deleteInspectionCmeValues=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspectionCmeValue(r,function(){app.persist.deleteInspectionCmeValues(n,t,i)},i)}},app.persist.getInspectionFormIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspectionForm"]),u=r.objectStore("inspectionForm"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspectionForm Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionFormIds should only be called on mobile")},app.persist.getInspectionForms=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("inspectionForm").objectStore("inspectionForm"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspectionForms",n),t(n)}}else app.post(app.vroot()+"Mobile/GetInspectionForms/",{inspectionFormIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getInspectionFormsForInspection=function(n,t,i){app.post(app.vroot()+"Mobile/GetInspectionFormsForInspection/",{inspectionId:n},function(n){t(n.items)},i)},app.persist.putInspectionForm=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionForm","readwrite").objectStore("inspectionForm"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting inspectionForm",n),i(n)}}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspectionForms/",{syncSession:app.persist.syncSession,inspectionForms:[n]},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspectionForms/",{syncSession:app.persist.syncSession,inspectionForms:[n]},function(){t(event)},i)},i)},app.persist.putInspectionForms=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putInspectionForm(r,function(){app.persist.putInspectionForms(n,t,i)},i)}},app.persist.deleteInspectionForm=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionForm","readwrite").objectStore("inspectionForm"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing inspectionForms",n),i(n)}}},app.persist.deleteInspectionForms=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspectionForm(r,function(){app.persist.deleteInspectionForms(n,t,i)},i)}},app.persist.getInspectionFormSectionIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspectionFormSection"]),u=r.objectStore("inspectionFormSection"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspectionFormSection Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionFormSectionIds should only be called on mobile")},app.persist.getInspectionFormSections=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("inspectionFormSection").objectStore("inspectionFormSection"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspectionFormSections",n),t(n)}}else app.post(app.vroot()+"Mobile/GetInspectionFormSections/",{inspectionFormSectionIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getInspectionFormSectionsForInspection=function(n,t,i){app.post(app.vroot()+"Mobile/GetInspectionFormSectionsForInspection/",{inspectionId:n},function(n){t(n.items)},i)},app.persist.putInspectionFormSection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionFormSection","readwrite").objectStore("inspectionFormSection"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting inspectionFormSection",n),i(n)}}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspectionFormSections/",{syncSession:app.persist.syncSession,inspectionFormSections:[n]},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspectionFormSections/",{syncSession:app.persist.syncSession,inspectionFormSections:[n]},function(){t(event)},i)},i)},app.persist.putInspectionFormSections=function(n,t,i){if(app.isMobile())if(n.length===0)t();else{var r=n.pop();app.persist.putInspectionFormSection(r,function(){app.persist.putInspectionFormSections(n,t,i)},i)}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspectionFormSections/",{syncSession:app.persist.syncSession,inspectionFormSections:n},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspectionFormSections/",{syncSession:app.persist.syncSession,inspectionFormSections:n},function(){t(event)},i)},i)},app.persist.deleteInspectionFormSection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionFormSection","readwrite").objectStore("inspectionFormSection"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing inspectionFormSections",n),i(n)}}},app.persist.deleteInspectionFormSections=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspectionFormSection(r,function(){app.persist.deleteInspectionFormSections(n,t,i)},i)}},app.persist.getInspectionFormRepeatingSectionIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspectionFormRepeatingSection"]),u=r.objectStore("inspectionFormRepeatingSection"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspectionFormRepeatingSection Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionFormRepeatingSectionIds should only be called on mobile")},app.persist.getInspectionFormRepeatingSections=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("inspectionFormRepeatingSection").objectStore("inspectionFormRepeatingSection"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspectionFormRepeatingSections",n),t(n)}}else app.post(app.vroot()+"Mobile/GetInspectionFormRepeatingSections/",{inspectionFormRepeatingSectionIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getInspectionFormRepeatingSectionsForInspection=function(n,t,i){app.post(app.vroot()+"Mobile/GetInspectionFormRepeatingSectionsForInspection/",{inspectionId:n},function(n){t(n.items)},i)},app.persist.putInspectionFormRepeatingSection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionFormRepeatingSection","readwrite").objectStore("inspectionFormRepeatingSection"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting inspectionFormRepeatingSection",n),i(n)}}},app.persist.putInspectionFormRepeatingSections=function(n,t,i){if(app.isMobile())if(n.length===0)t();else{var r=n.pop();app.persist.putInspectionFormRepeatingSection(r,function(){app.persist.putInspectionFormRepeatingSections(n,t,i)},i)}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspectionFormRepeatingSections/",{syncSession:app.persist.syncSession,inspectionFormRepeatingSections:n},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspectionFormRepeatingSections/",{syncSession:app.persist.syncSession,inspectionFormRepeatingSections:n},function(){t(event)},i)},i)},app.persist.deleteInspectionFormRepeatingSection=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionFormRepeatingSection","readwrite").objectStore("inspectionFormRepeatingSection"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing inspectionFormRepeatingSections",n),i(n)}}},app.persist.deleteInspectionFormRepeatingSections=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspectionFormRepeatingSection(r,function(){app.persist.deleteInspectionFormRepeatingSections(n,t,i)},i)}},app.persist.getInspectionFormAnswerIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspectionFormAnswer"]),u=r.objectStore("inspectionFormAnswer"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspectionFormAnswer Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionFormAnswerIds should only be called on mobile")},app.persist.getInspectionFormAnswers=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("inspectionFormAnswer").objectStore("inspectionFormAnswer"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspectionFormAnswers",n),t(n)}}else app.post(app.vroot()+"Mobile/GetInspectionFormAnswers/",{inspectionFormAnswerIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.getInspectionFormAnswersByInspectionId=function(n,t,i){if(app.isMobile()){var u=[],f=app.persist.db.transaction("inspectionFormAnswer").objectStore("inspectionFormAnswer"),o=f.index("inspectionId"),e=IDBKeyRange.only(n),r=o.openCursor(e);r.onsuccess=function(n){var i=n.target.result;i?(u.push(i.value),i.continue()):t(u)},r.onerror=function(n){Wndsr.error("Error getting inspectionFormAnswersByInspectionId",n),i(n)}}else app.post(app.vroot()+"Mobile/GetInspectionFormAnswersByInspectionId/",{inspectionId:n},function(n){t(n.items)},i)},app.persist.putInspectionFormAnswer=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionFormAnswer","readwrite").objectStore("inspectionFormAnswer"),r=u.put(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error putting inspectionFormAnswer",n),i(n)}}},app.persist.putInspectionFormAnswers=function(n,t,i){if(app.isMobile())if(n.length===0)t();else{var r=n.pop();app.persist.putInspectionFormAnswer(r,function(){app.persist.putInspectionFormAnswers(n,t,i)},i)}else app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspectionFormAnswers/",{syncSession:app.persist.syncSession,inspectionFormAnswers:n},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspectionFormAnswers/",{syncSession:app.persist.syncSession,inspectionFormAnswers:n},function(){t(event)},i)},i)},app.persist.deleteInspectionFormAnswer=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionFormAnswer","readwrite").objectStore("inspectionFormAnswer"),r=u.delete(n);r.onsuccess=function(n){t(n)},r.onerror=function(n){Wndsr.error("Error removing inspectionFormAnswers",n),i(n)}}},app.persist.deleteInspectionFormAnswers=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspectionFormAnswer(r,function(){app.persist.deleteInspectionFormAnswers(n,t,i)},i)}},app.persist.getInspectionFormMediaIds=function(n,t){if(app.isMobile()){var r=app.persist.db.transaction(["inspectionFormMedia"]),u=r.objectStore("inspectionFormMedia"),i=u.getAllKeys();i.onsuccess=function(){n(i.result)},i.onerror=function(n){Wndsr.error("Error getting all inspectionFormMedia Ids"),t(n)}}else Wndsr.error("app.persist.getInspectionFormMediaIds should only be called on mobile")},app.persist.getInspectionFormMedias=function(n,t){if(app.isMobile()){var r=[],u=app.persist.db.transaction("inspectionFormMedia").objectStore("inspectionFormMedia"),i=u.openCursor();i.onsuccess=function(t){var i=t.target.result;i?(r.push(i.value),i.continue()):n(r)},i.onerror=function(n){Wndsr.error("Error getting inspectionFormMedias",n),t(n)}}else app.post(app.vroot()+"Mobile/GetInspectionFormMedias/",{inspectionFormMediaIds:[],principalId:app.principal.id,lastSyncTime:null},function(t){n(t.add)},t)},app.persist.putInspectionFormMedia=function(n,t,i){var e,u,o,r,f;app.isMobile()?n.mediaObject?(o=app.persist.db.transaction("file","readwrite").objectStore("file"),r=o.put({fileName:n.id,data:n.mediaObject}),r.onsuccess=function(){n.mediaObject=undefined;var f=app.persist.db.transaction("inspectionFormMedia","readwrite").objectStore("inspectionFormMedia"),u=f.put(n);u.onsuccess=function(n){t(n)},u.onerror=function(n){Wndsr.error("Error putting inspectionFormMedia",n),i(n)}},r.onerror=function(n){Wndsr.error("Error putting inspectionFormMedia",n),i(n)}):(e=app.persist.db.transaction("inspectionFormMedia","readwrite").objectStore("inspectionFormMedia"),u=e.put(n),u.onsuccess=function(n){t(n)},u.onerror=function(n){Wndsr.error("Error putting inspectionFormMedia",n),i(n)}):n.mediaObject?(f=n.mediaObject.slice(0),n.mediaObject=undefined,app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspectionFormMedias/",{syncSession:app.persist.syncSession,inspectionFormMedias:[n]},function(){app.post(app.vroot()+"Mobile/UploadImageWeb/",{syncSession:app.persist.syncSession,inspectionFormMediaId:n.id,mediaObject:f},function(){t(event)},i)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspectionFormMedias/",{syncSession:app.persist.syncSession,inspectionFormMedias:[n]},function(){app.post(app.vroot()+"Mobile/UploadImageWeb/",{syncSession:app.persist.syncSession,inspectionFormMediaId:n.id,mediaObject:f},function(){t(event)},i)},i)},i)):app.persist.syncSession?app.post(app.vroot()+"Mobile/UploadInspectionFormMedias/",{syncSession:app.persist.syncSession,inspectionFormMedias:[n]},function(){t(event)},i):app.persist.requestSync(function(){app.post(app.vroot()+"Mobile/UploadInspectionFormMedias/",{syncSession:app.persist.syncSession,inspectionFormMedias:[n]},function(){t(event)},i)},i)},app.persist.putInspectionFormMedias=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.putInspectionFormMedia(r,function(){app.persist.putInspectionFormMedias(n,t,i)},i)}},app.persist.deleteInspectionFormMedia=function(n,t,i){if(app.isMobile()){var u=app.persist.db.transaction("inspectionFormMedia","readwrite").objectStore("inspectionFormMedia"),r=u.delete(n);r.onsuccess=function(){var f=app.persist.db.transaction("file","readwrite").objectStore("file"),u=f.delete(n);u.onsuccess=function(n){t(n)},u.onerror=function(n){Wndsr.error("Error removing inspectionFormMedia file",n),i(n)}},r.onerror=function(n){Wndsr.error("Error removing inspectionFormMedia",n),i(n)}}},app.persist.deleteInspectionFormMedias=function(n,t,i){if(n.length===0)t();else{var r=n.pop();app.persist.deleteInspectionFormMedia(r,function(){app.persist.deleteInspectionFormMedias(n,t,i)},i)}},app.persist.getInspectionFormMediasByInspectionId=function(n,t,i){if(app.isMobile()){var u=[],f=app.persist.db.transaction("inspectionFormMedia").objectStore("inspectionFormMedia"),o=f.index("inspectionId"),e=IDBKeyRange.only(n),r=o.openCursor(e);r.onsuccess=function(n){var i=n.target.result;i?(u.push(i.value),i.continue()):t(u)},r.onerror=function(n){Wndsr.error("Error getting getInspectionFormMediasByInspectionId",n),i(n)}}else app.post(app.vroot()+"Mobile/getInspectionFormMediasByInspectionId/",{inspectionId:n},function(n){t(n.items)},i)},app.persist.getItem=function(n,t){var r="";if(r=n.id!==null&&n.id!==undefined?n.id.replace(/\-/g,"").toUpperCase():n.replace(/\-/g,"").toUpperCase(),Wndsr.info("Getting Item "+r),t)localforage.getItem(r).then(function(n){t(n)});else return localforage.getItem(r)},app.persist.setItem=function(n,t,i){var u="";if(u=n.id!==null&&n.id!==undefined?n.id.replace(/\-/g,"").toUpperCase():n.replace(/\-/g,"").toUpperCase(),Wndsr.info("Setting Item "+u),i)localforage.setItem(u,t).then(function(){i()});else return localforage.setItem(u,t)},app.persist.deleteItem=function(n,t){var r="";if(r=n.id!==null&&n.id!==undefined?n.id.replace(/\-/g,"").toUpperCase():n.replace(/\-/g,"").toUpperCase(),Wndsr.info("Deleting Item "+r),t)localforage.removeItem(r).then(function(){t()});else return localforage.removeItem(r)},app.persist.clear=function(){Wndsr.info("Clearing data");var t=app.persist.db.transaction(["keyValue"],["readwrite"]),n=t.objectStore("keyValue");n.clear(),t=app.persist.db.transaction(["inspection"],["readwrite"]),n=t.objectStore("inspection"),n.clear(),t=app.persist.db.transaction(["inspectionCmeValue"],["readwrite"]),n=t.objectStore("inspectionCmeValue"),n.clear(),t=app.persist.db.transaction(["inspectionForm"],["readwrite"]),n=t.objectStore("inspectionForm"),n.clear(),t=app.persist.db.transaction(["inspectionFormSection"],["readwrite"]),n=t.objectStore("inspectionFormSection"),n.clear(),t=app.persist.db.transaction(["inspectionFormRepeatingSection"],["readwrite"]),n=t.objectStore("inspectionFormRepeatingSection"),n.clear(),t=app.persist.db.transaction(["inspectionFormAnswer"],["readwrite"]),n=t.objectStore("inspectionFormAnswer"),n.clear(),t=app.persist.db.transaction(["inspectionFormMedia"],["readwrite"]),n=t.objectStore("inspectionFormMedia"),n.clear(),t=app.persist.db.transaction(["site"],["readwrite"]),n=t.objectStore("site"),n.clear(),t=app.persist.db.transaction(["siteAddress"],["readwrite"]),n=t.objectStore("siteAddress"),n.clear(),t=app.persist.db.transaction(["principal"],["readwrite"]),n=t.objectStore("principal"),n.clear(),t=app.persist.db.transaction(["project"],["readwrite"]),n=t.objectStore("project"),n.clear(),t=app.persist.db.transaction(["autoAssignForm"],["readwrite"]),n=t.objectStore("autoAssignForm"),n.clear(),t=app.persist.db.transaction(["group"],["readwrite"]),n=t.objectStore("group"),n.clear(),t=app.persist.db.transaction(["groupRole"],["readwrite"]),n=t.objectStore("groupRole"),n.clear(),t=app.persist.db.transaction(["organization"],["readwrite"]),n=t.objectStore("organization"),n.clear(),t=app.persist.db.transaction(["orgGroup"],["readwrite"]),n=t.objectStore("orgGroup"),n.clear(),t=app.persist.db.transaction(["role"],["readwrite"]),n=t.objectStore("role"),n.clear(),t=app.persist.db.transaction(["inspectionType"],["readwrite"]),n=t.objectStore("inspectionType"),n.clear(),t=app.persist.db.transaction(["orgInspectionType"],["readwrite"]),n=t.objectStore("orgInspectionType"),n.clear(),t=app.persist.db.transaction(["form"],["readwrite"]),n=t.objectStore("form"),n.clear(),t=app.persist.db.transaction(["formVersion"],["readwrite"]),n=t.objectStore("formVersion"),n.clear(),t=app.persist.db.transaction(["formSection"],["readwrite"]),n=t.objectStore("formSection"),n.clear(),t=app.persist.db.transaction(["formControl"],["readwrite"]),n=t.objectStore("formControl"),n.clear(),t=app.persist.db.transaction(["file"],["readwrite"]),n=t.objectStore("file"),n.clear()},app.persist.export=function(){var n="";return localforage.iterate(function(t,i){n.length>0&&(n+="[END]"),n+="[KEY]"+i+"[VALUE]"+JSON.stringify(t)}).then(function(){var t=document.createElement("a"),r=new Blob(["﻿",n]),i=URL.createObjectURL(r);t.href=i,t.download="data.txt",document.body.appendChild(t),t.click(),document.body.removeChild(t)})},app.persist.import=function(n){for(var i=n.split("[END]"),u,r,t=0;t<i.length;t++)u=i[t].substring(5,i[t].indexOf("[VALUE]")),r=i[t].substring(i[t].indexOf("[VALUE]")+7),r=r.replace("[END]",""),localforage.setItem(u,JSON.parse(r),function(){Wndsr.info("Done!")},function(){Wndsr.error("Failed!")});alert("done")},app.persist.length=function(){return localforage.length()},app.persist.iterate=function(n,t){return localforage.iterate(n,t)},app.getFormVersionList=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getFormVersionList - isMobile = "+r),r?app.persist.getItem("formVersionList",n,t):i!==null&&i!==undefined&&i.length>0?$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetFormVersionListForInspection/"+i,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t}):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetFormVersionList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getOrganizationList=function(n,t){var i=app.isMobile();Wndsr.info("app.getOrganizationList - isMobile = "+i),i?app.persist.getItem("organizationList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetOrganizationList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getProjectList=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getProjectList - isMobile = "+r),r&&!i?app.persist.getItem("projectList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetProjectList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getPrincipalList=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getPrincipalList - isMobile = "+r),r&&!i?app.persist.getItem("principalList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetPrincipalList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getPrincipal=function(n,t){var r=app.isMobile();Wndsr.info("app.getPrincipal - isMobile = "+r),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetUserPrincipal",contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getSensitivePrincipalList=function(n,t){var i=app.isMobile();Wndsr.info("app.getSensitivePrincipalList - isMobile = "+i),i?app.persist.getItem("principalSensitiveList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetSensitivePrincipalList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getInspectionList=function(n,t){var i=app.isMobile();Wndsr.info("app.getInspectionList - isMobile = "+i),i?app.persist.getItem("inspectionList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getInspectionFormList=function(n,t){var i=app.isMobile();Wndsr.info("app.getInspectionFormList - isMobile = "+i),i?app.persist.getItem("inspectionFormList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionFormList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getInspectionFormMediaList=function(n,t){var i=app.isMobile();Wndsr.info("app.getInspectionFormMediaList - isMobile = "+i),i?app.persist.getItem("inspectionFormMediaList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionFormMediaList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getConflictList=function(n,t){var i=app.isMobile();Wndsr.info("app.getConflictList - isMobile = "+i),i?app.persist.getItem("conflictList",n,t):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetConflictList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:n,headers:{"cache-control":"no-cache"},error:t})},app.getConflictListInspection=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getConflictListInspection - isMobile = "+r),r?app.persist.getItem("conflictList",t,i):$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetConflictListInspection/"+n,contentType:"application/json; charset=utf-8",success:t,headers:{"cache-control":"no-cache"},error:i})},app.clearConflictList=function(n,t){var i=app.isMobile();Wndsr.info("app.clearConflictList - isMobile = "+i),i?app.persist.setItem("conflictList",[],n,t):n()},app.getFormVersion=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getFormVersion - isMobile = "+r),r?app.persist.getItem(n,t,i):app.post(app.vroot()+"Synchronize/GetFormVersion/",{id:n},t,i)},app.getInspection=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.getInspection - isMobile = "+u),u&&!r?app.persist.getItem(n,t,i):app.post(app.vroot()+"Synchronize/GetInspection/",{id:n},t,i)},appPersistInspectionHasMissingAnswers=function(n){return new Promise(function(t,i){if(n!==undefined){Wndsr.info("appPersistInspectionHasMissingAnswers");var u=n.id,r=!1;Inspection.Load(u,function(n){for(var v=n.inspectionForms.filter(function(n){return n.inspectionId===u&&n.isActive}),s,f,o,a,h,e,i,c,l=0;l<v.length;l++)for(s=v[l].inspectionFormSections.filter(function(n){return n.isVisible}),f=0;f<s.length;f++){for(o=s[f].inspectionFormAnswers.filter(function(n){return n.isVisible&&(n.inspectionFormRepeatingSectionId===null||n.inspectionFormRepeatingSectionId===undefined)}),i=0;i<o.length;i++)if(o[i]!==undefined&&o[i].isVisible&&o[i].hasMissingAnswer){r=!0;break}if(s[f].inspectionFormRepeatingSections!==undefined)for(a=s[f].inspectionFormRepeatingSections.filter(function(n){return n}),h=0;h<a.length;h++)for(e=a[h].inspectionFormAnswers.filter(function(n){return n.isVisible}),i=0;i<e.length;i++)if(e!==undefined&&e.isVisible&&e.hasMissingAnswer){r=!0;break}}return c=[],c.hasMissingAnswers=r,c.inspection=n,t(c)},app.getDataFailed)}else{console.log("inspection is undefined");const f=new Error("there was an error - inspection is undefined");return i(f)}})},app.getProject=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.getProject - isMobile = "+u),u&&!r?app.persist.getItem(n,t,i):app.post(app.vroot()+"Synchronize/GetProject/",{id:n},t,i)},app.getInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getInspectionForm - isMobile = "+r),r?app.persist.getItem(n,t,i):app.post(app.vroot()+"Synchronize/GetInspectionForm/",{id:n},t,i)},app.getInspectionFormMedia=function(n,t,i){var r=app.isMobile();Wndsr.info("app.getInspectionFormMedia - isMobile = "+r),r?app.persist.getItem(n,t,i):app.post(app.vroot()+"Synchronize/GetInspectionFormMedia/",{id:n},t,i)},app.deleteInspectionFormMedia=function(n,t,i){var r=app.isMobile();Wndsr.info("app.deleteInspectionFormMedia - isMobile = "+r+" id = "+n),r?app.getInspectionFormMediaList(function(r){(r===null||r===undefined)&&(r=[]);for(var u in r)if(r[u].id===n){r[u].isDeleted=!0,r[u].isDirty=!0;break}app.persist.setItem("inspectionFormMediaList",r,function(){app.persist.getItem(n,function(r){r.isDirty=!0,r.isDeleted=!0,r.mediaObject=null,app.persist.setItem(n,r,t,i)},i)},i)},i):app.post(app.vroot()+"Synchronize/DeleteInspectionFormMedia/",{id:n},t,i)},app.updateInspection=function(n,t,i,r){var u=app.isMobile(),f=n.completed!==null&&n.completed!==undefined;Wndsr.info("app.updateInspection - isMobile = "+u+", inspectionId = "+n.id),u&&!r?app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.id){r[u].isDirty=!0,r[u].isComplete=f,r[u].actualStart=n.actualStart,r[u].type=n.inspectionTypeCode,r[u].scheduledStart=n.scheduledStart,n.siteKey!==undefined?r[u].siteKey=n.siteKey:n.site!==undefined&&n.site.siteKey!==undefined&&(r[u].siteKey=n.site.siteKey);break}app.persist.setItem("inspectionList",r,function(){app.persist.setItem(n.id,n,t,i)},i)},i):app.post(app.vroot()+"Synchronize/UpdateInspection/",{inspection:n},t,i)},app.updateInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.updateInspectionForm - isMobile = "+r+", inspectionFormId = "+n.id),r?app.getInspectionFormList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.id){r[u].isDirty=!0;break}app.persist.setItem("inspectionFormList",r,function(){app.persist.setItem(n.id,n,function(){app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.inspectionId){r[u].isFormDirty=!0,app.persist.setItem("inspectionList",r,function(){t({inspectionForm:n,isConflict:!1})},i);break}},i)},i)},i)},i):app.post(app.vroot()+"Synchronize/UpdateInspectionForm/",{inspectionForm:n},function(i){n=i.inspectionForm,t(i)},i)},app.updateInspectionFormAnswers=function(n,t,i,r,u){var f=app.isMobile();Wndsr.info("app.updateInspectionFormAnswers - isMobile = "+f+", inspectionFormId = "+n),f?Wndsr.error("Error - attempt to save answers in a mobile mode"):app.post(app.vroot()+"Synchronize/UpdateInspectionFormAnswers/",{inspectionFormId:n,inspectionFormAnswers:t,dataVersion:i},function(n){r(n)},u)},app.addInspectionFormMedia=function(n,t,i,r,u,f,e,o,s,h,c,l,a){var v=app.isMobile();Wndsr.info("app.addInspectionFormMedia - isMobile = "+v+", inspectionFormId = "+n.id),t.isDirty=!0,v?app.getInspectionFormMediaList(function(v){(v===null||v===undefined)&&(v=[]);var y={};y.id=app.createUUID(),y.inspectionFormId=t.inspectionFormId,y.changedOn=new moment,y.isDirty=!0,y.isNew=!0,y.isDeleted=!1,t.inspectionFormMedia.push({id:y.id,isNew:!0,isDirty:!0,isDeleted:!1,mediaPath:"",mimeType:i,metadataComment:c,metaDataTags:"",mediaObject:"",imageCapturedTime:h,gpsLatitude:u,gpsLongitude:f,gpsAltitude:e,gpsAzimuth:o,gpsOrientation:s}),v.push(y),app.persist.setItem("inspectionFormMediaList",v,function(){var v={};v.id=y.id,v.mediaPath="",v.mimeType=i,v.metadataComment=c,v.metaDataTags="",v.mediaObject=r,v.imageCapturedTime=h,v.gpsLatitude=u,v.gpsLongitude=f,v.gpsAltitude=e,v.gpsAzimuth=o,v.gpsOrientation=s,v.isDirty=!1,v.isNew=!1,v.isDeleted=!1,app.persist.setItem(v.id,v,function(){app.updateInspectionForm(n,function(){l(v.id,t)},a)},a)},a)},a):app.post(app.vroot()+"Synchronize/AddInspectionFormMedia/",{inspectionFormAnswer:t,mimeType:i,mediaObject:r,latitude:u,longitude:f,altitude:e,azimuth:o,orientation:s,imageDateTime:h,comment:c},function(i){t=i.inspectionFormAnswer,n.dataVersion=i.dataVersion,l(i.inspectionFormMedia.id,t)},a)},app.updateInspectionFormMedia=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.updateInspectionFormMedia - isMobile = "+u+", inspectionFormMediaId = "+n),u?app.getInspectionFormMediaList(function(u){(u===null||u===undefined)&&(u=[]);for(var f in u)if(u[f].id===n){u[f].isDirty=!0;break}app.persist.setItem("inspectionFormMediaList",u,function(){app.persist.getItem(n,function(u){u.metadataComment=t,app.persist.setItem(n,u,i,r)},r)},r)},r):app.post(app.vroot()+"Synchronize/UpdateInspectionFormMedia/",{id:n,comment:t},function(){i()},r)},app.addInspection=function(n,t,i){var r=app.isMobile(),u=n.completed!==null&&n.completed!==undefined;Wndsr.info("app.addInspection - isMobile = "+r+", inspectionId = "+n.id),r?app.getInspectionList(function(r){var f={};f.id=n.id,f.scheduledStart=n.scheduledStart,f.actualStart=n.actualStart,f.siteName=n.site.siteName,f.siteCity=n.site.siteAddresses[0].city,f.siteKey=n.site.siteKey,f.siteAddress="",f.type=n.inspectionTypeCode,f.changedOn=n.changedOn,f.isDirty=!0,f.isDeleted=!1,f.isNew=!0,f.isComplete=u,r.unshift(f),app.persist.setItem("inspectionList",r,function(){app.persist.setItem(n.id,n,t,i)},i)},i):app.post(app.vroot()+"Synchronize/NewInspection/",{inspection:n},t,i)},app.addInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.addInspectionForm - isMobile = "+r+", inspectionFormId = "+n.id),r?app.getInspectionFormList(function(r){var u={};u.id=n.id,u.inspectionId=n.inspectionId,u.dataVersion=n.dataVersion,u.changedOn=n.changedOn,u.isDirty=!0,u.isDeleted=!1,u.isNew=!0,r.push(u),app.persist.setItem("inspectionFormList",r,function(){app.getInspectionForm(u.inspectionId,function(r){r.inspectionFormInfoList.push({id:n.id,isActive:!0,formVersionId:n.formVersionId,isDeleted:!1,inspectionFormSections:n.inspectionFormSections}),r.isDirty=!0,app.persist.setItem(r.id,r,function(){app.persist.setItem(n.id,n,function(){app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n.inspectionId){r[u].isFormDirty=!0,app.persist.setItem("inspectionList",r,function(){t({inspectionForm:n,isConflict:!1})},i);break}},i)},i)},i)},i)},i)},i):app.post(app.vroot()+"Synchronize/NewInspectionForm/",{inspectionForm:n},t,i)},app.deleteInspection=function(n,t,i,r){var u=app.isMobile();Wndsr.info("app.deleteInspection - isMobile = "+u+", inspectionId = "+n),!r&&u?app.getInspectionList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n){r[u].isDirty=!0,r[u].isDeleted=!0;break}app.persist.setItem("inspectionList",r,t,i)},i):app.post(app.vroot()+"Synchronize/DeleteInspection/",{id:n},t,i)},app.deleteInspectionForm=function(n,t,i){var r=app.isMobile();Wndsr.info("app.deleteInspectionForm - isMobile = "+r+", inspectionId = "+n),r?app.getInspectionFormList(function(r){for(var u=0;u<r.length;u++)if(r[u].id===n){r[u].isDirty=!0,r[u].isDeleted=!0;break}app.persist.setItem("inspectionFormList",r,function(){app.persist.getItem(n,function(r){app.persist.getItem(r.inspectionId,function(u){for(var f=0;f<u.inspectionFormInfoList.length;f++)if(u.inspectionFormInfoList[f].id===n){u.inspectionFormInfoList[f].isDeleted=!0;break}app.persist.setItem(r.inspectionId,u,function(){app.getInspectionList(function(n){for(var u=0;u<n.length;u++)if(n[u].id===r.inspectionId){n[u].isFormDirty=!0,app.persist.setItem("inspectionList",n,function(){t({inspectionForm:r,isConflict:!1})},i);break}},i)},i)},i)},i)},i)},i):app.post(app.vroot()+"Synchronize/DeleteInspectionForm/",{id:n},t,i)}}(),function(){app.synchronize={},app.synchronize.initialSteps=40,app.synchronize.totalSteps=0,app.synchronize.currentStep=0,app.synchronize.totalImages=0,app.synchronize.currentImage=0,app.synchronize.totalUploadImages=0,app.synchronize.currentUploadImage=0,app.synchronize.localLastSyncTime=null,app.synchronize.serverLastSyncTime=null,app.synchronize.imagesToDownload=[],app.synchronize.imagesToUpload=[],app.synchronize.formVersionList=null,app.synchronize.serverFormVersionList=null,app.synchronize.inspectionList=null,app.synchronize.serverInspectionList=null,app.synchronize.inspectionFormList=null,app.synchronize.serverInspectionFormList=null,app.synchronize.inspectionFormMediaList=null,app.synchronize.serverInspectionFormMediaList=null,app.synchronize.formVersionsToRemove=[],app.synchronize.formVersionsToAdd=[],app.synchronize.inspectionsToRemove=[],app.synchronize.inspectionsToAdd=[],app.synchronize.inspectionFormsToRemove=[],app.synchronize.inspectionFormsToAdd=[],app.synchronize.inspectionFormMediasToRemove=[],app.synchronize.inspectionFormMediasToAdd=[],app.synchronize.listIndex=0,app.synchronize.isSyncing=!1,app.synchronize.deviceId=null,app.synchronize.syncSession=null,app.synchronize.dirtyInspectionCount=0,app.synchronize.dirtyInspectionFormCount=0,app.synchronize.dirtyFormVersionCount=0,app.synchronize.synchronize=function(){if(app.isMobile()&&!app.isSyncing){if(!app.isOnline){alert("You must be online to synchronize");return}Wndsr.info("Begin Start Sync"),app.synchronize.totalSteps=app.synchronize.initialSteps,app.synchronize.currentStep=0,$("html").trigger("syncStart"),app.isSyncing=!0,app.synchronize.isSyncing=!0,app.synchronize.syncSession=null,app.persist.getKeyValue("DEVICE_ID",function(n){app.synchronize.deviceId=n,app.persist.getKeyValue("LOCALLASTSYNCTIME",function(n){app.synchronize.localLastSyncTime=n,app.persist.getKeyValue("SERVERLASTSYNCTIME",function(n){app.synchronize.serverLastSyncTime=n,Wndsr.info("Finish Start Sync"),app.synchronize.requestSync()})})})}},app.synchronize.requestSync=function(){Wndsr.info("Begin Request Sync"),app.synchronize.currentStep++,$("html").trigger("beginRequestSync"),app.post(app.vroot()+"Mobile/RequestSync",{deviceId:app.synchronize.deviceId,syncSession:null},function(n){app.synchronize.deviceId=n.deviceId,app.synchronize.syncSession=n.syncSession,app.persist.setKeyValue("DEVICE_ID",app.synchronize.deviceId,function(){Wndsr.info("Finish Request Sync"),app.synchronize.prepareSync()})},app.synchronize.syncFailed)},app.synchronize.prepareSync=function(){Wndsr.info("Begin Preparing Sync"),app.synchronize.currentStep++,$("html").trigger("prepareSyncStart"),Wndsr.info("Finish Preparing Sync"),app.synchronize.uploadSites()},app.synchronize.uploadSites=function(){Wndsr.info("Begin Upload Sites"),app.synchronize.currentStep++,$("html").trigger("startUploadSites");var n=[];app.persist.getSites(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadSites/",{syncSession:app.synchronize.syncSession,sites:n},function(){Wndsr.info("Finish Upload Sites"),app.synchronize.uploadSiteAddresses()}):(Wndsr.info("Finish Upload Sites"),app.synchronize.uploadSiteAddresses())})},app.synchronize.uploadSiteAddresses=function(){Wndsr.info("Begin Upload Site Addresses"),app.synchronize.currentStep++,$("html").trigger("startUploadSiteAddresses");var n=[];app.persist.getSiteAddresses(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadSiteAddresses/",{syncSession:app.synchronize.syncSession,siteAddresses:n},function(){Wndsr.info("Finish Upload Site Addresses"),app.synchronize.uploadProjects()}):(Wndsr.info("Finish Upload Site Addresses"),app.synchronize.uploadProjects())})},app.synchronize.uploadProjects=function(){Wndsr.info("Begin Upload Projects"),app.synchronize.currentStep++,$("html").trigger("startUploadProjects");var n=[];app.persist.getProjects(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadProjects/",{syncSession:app.synchronize.syncSession,projects:n},function(){Wndsr.info("Finish Upload Projects"),app.synchronize.uploadInspections()}):(Wndsr.info("Finish Upload Projects"),app.synchronize.uploadInspections())})},app.synchronize.uploadInspections=function(){Wndsr.info("Begin Upload Inspections"),app.synchronize.currentStep++,$("html").trigger("startUploadInspections");var n=[];app.persist.getInspections(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadInspections/",{syncSession:app.synchronize.syncSession,inspections:n},function(){Wndsr.info("Finish Upload Inspections"),app.synchronize.uploadInspectionCmeValues()}):(Wndsr.info("Finish Upload Inspections"),app.synchronize.uploadInspectionCmeValues())})},app.synchronize.uploadInspectionCmeValues=function(){Wndsr.info("Begin Upload Inspection Cme Values"),app.synchronize.currentStep++,$("html").trigger("startUploadInspectionCmeValues");var n=[];app.persist.getInspectionCmeValues(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadInspectionCmeValues/",{syncSession:app.synchronize.syncSession,inspectionCmeValues:n},function(){Wndsr.info("Finish Upload Inspection CME Values"),app.synchronize.uploadInspectionForms()}):(Wndsr.info("Finish Upload Inspection CME Values"),app.synchronize.uploadInspectionForms())})},app.synchronize.uploadInspectionForms=function(){Wndsr.info("Begin Upload Inspection Forms"),app.synchronize.currentStep++,$("html").trigger("startUploadInspectionForms");var n=[];app.persist.getInspectionForms(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadInspectionForms/",{syncSession:app.synchronize.syncSession,inspectionForms:n},function(){Wndsr.info("Finish Upload Inspection Forms"),app.synchronize.uploadInspectionFormSections()}):(Wndsr.info("Finish Upload Inspection Forms"),app.synchronize.uploadInspectionFormSections())})},app.synchronize.uploadInspectionFormSections=function(){Wndsr.info("Begin Upload Inspection Form Sections"),app.synchronize.currentStep++,$("html").trigger("startUploadInspectionFormSections");var n=[];app.persist.getInspectionFormSections(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadInspectionFormSections/",{syncSession:app.synchronize.syncSession,inspectionFormSections:n},function(){Wndsr.info("Finish Upload Inspection Form Sections"),app.synchronize.uploadInspectionFormRepeatingSections()}):(Wndsr.info("Finish Upload Inspection Form Sections"),app.synchronize.uploadInspectionFormRepeatingSections())})},app.synchronize.uploadInspectionFormRepeatingSections=function(){Wndsr.info("Begin Upload Inspection Form Repeating Sections"),app.synchronize.currentStep++,$("html").trigger("startUploadInspectionFormRepeatingSections");var n=[];app.persist.getInspectionFormRepeatingSections(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadInspectionFormRepeatingSections/",{syncSession:app.synchronize.syncSession,inspectionFormRepeatingSections:n},function(){Wndsr.info("Finish Upload Inspection Form Repeating Sections"),app.synchronize.uploadInspectionFormAnswers()}):(Wndsr.info("Finish Upload Inspection Form Repeating Sections"),app.synchronize.uploadInspectionFormAnswers())})},app.synchronize.uploadInspectionFormAnswers=function(){Wndsr.info("Begin Upload Inspection Form Answers"),app.synchronize.currentStep++,$("html").trigger("startUploadInspectionFormAnswers");var n=[];app.persist.getInspectionFormAnswers(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]);n.length>0?app.post(app.vroot()+"Mobile/UploadInspectionFormAnswers/",{syncSession:app.synchronize.syncSession,inspectionFormAnswers:n},function(){Wndsr.info("Finish Upload Inspection Form Answers"),app.synchronize.uploadInspectionFormMedias()}):(Wndsr.info("Finish Upload Inspection Form Answers"),app.synchronize.uploadInspectionFormMedias())})},app.synchronize.uploadInspectionFormMedias=function(){Wndsr.info("Begin Upload Inspection Form Medias"),app.synchronize.currentStep++,$("html").trigger("startUploadInspectionFormMedia");var n=[];app.persist.getInspectionFormMedias(function(t){for(var i=0;i<t.length;i++)t[i].isDirty&&n.push(t[i]),t[i].isNew&&app.synchronize.imagesToUpload.push(t[i].id);app.synchronize.totalSteps+=app.synchronize.imagesToUpload.length,app.synchronize.totalUploadImages=app.synchronize.imagesToUpload.length,n.length>0?app.post(app.vroot()+"Mobile/UploadInspectionFormMedias/",{syncSession:app.synchronize.syncSession,inspectionFormMedias:n},function(){Wndsr.info("Finish Upload Inspection Form Answer Medias"),app.synchronize.uploadImages()}):(Wndsr.info("Finish Upload Inspection Form Answer Medias"),app.synchronize.uploadImages())})},app.synchronize.uploadImages=function(){if(app.synchronize.imagesToUpload.length>0){var n=app.synchronize.imagesToUpload.pop();app.synchronize.currentUploadImage++,Wndsr.info("Start Upload image "+n),$("html").trigger("startUploadImage"),app.persist.getFile(n,function(t){app.post(app.vroot()+"Mobile/UploadImageWeb/",{syncSession:app.synchronize.syncSession,inspectionFormMediaId:n,mediaObject:t.data},function(){Wndsr.info("Finish Upload image "+n),app.synchronize.uploadImages()})})}else Wndsr.info("Finish Upload Images"),app.synchronize.processUpload()},app.synchronize.processUpload=function(){Wndsr.info("Begin Process Upload"),app.synchronize.currentStep++,$("html").trigger("startProcessUpload"),app.post(app.vroot()+"Mobile/ProcessUpload/",{syncSession:app.synchronize.syncSession},function(){Wndsr.info("Finish Process Upload"),app.synchronize.syncSession=null,app.synchronize.downloadSites()})},app.synchronize.downloadSites=function(){Wndsr.info("Begin Download Sites"),app.synchronize.currentStep++,$("html").trigger("startDownloadSites"),app.persist.getSiteIds(function(n){app.post(app.vroot()+"Mobile/GetSites/",{siteIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putSites(n.add,function(){app.persist.putSites(n.update,function(){app.persist.deleteSites(n.remove,function(){Wndsr.info("Finish Download Sites"),app.synchronize.downloadSiteAddresses()})})})})})},app.synchronize.downloadSiteAddresses=function(){Wndsr.info("Begin Download Site Addresses"),app.synchronize.currentStep++,$("html").trigger("startDownloadSiteAddresses"),app.persist.getSiteAddressIds(function(n){app.post(app.vroot()+"Mobile/GetSiteAddresses/",{siteAddressIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putSiteAddresses(n.add,function(){app.persist.putSiteAddresses(n.update,function(){app.persist.deleteSiteAddresses(n.remove,function(){Wndsr.info("Finish Download Site Addresses"),app.synchronize.downloadPrincipals()})})})})})},app.synchronize.downloadPrincipals=function(){Wndsr.info("Begin Download Principals"),app.synchronize.currentStep++,$("html").trigger("startDownloadPrincipals"),app.persist.getPrincipalIds(function(n){app.post(app.vroot()+"Mobile/GetPrincipals/",{principalIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putPrincipals(n.add,function(){app.persist.putPrincipals(n.update,function(){app.persist.deletePrincipals(n.remove,function(){Wndsr.info("Finish Download Principals"),app.synchronize.downloadProjects()})})})})})},app.synchronize.downloadProjects=function(){Wndsr.info("Begin Download Projects"),app.synchronize.currentStep++,$("html").trigger("startDownloadProjects"),app.persist.getProjectIds(function(n){app.post(app.vroot()+"Mobile/GetProjects/",{projectIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putProjects(n.add,function(){app.persist.putProjects(n.update,function(){app.persist.deleteProjects(n.remove,function(){Wndsr.info("Finish Download Projects"),app.synchronize.downloadAutoAssignForms()})})})})})},app.synchronize.downloadAutoAssignForms=function(){Wndsr.info("Begin Download Auto Assign Forms"),app.synchronize.currentStep++,$("html").trigger("startDownloadAutoAssignForms"),app.persist.getAutoAssignFormIds(function(n){app.post(app.vroot()+"Mobile/GetAutoAssignForms/",{autoAssignFormIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putAutoAssignForms(n.add,function(){app.persist.putAutoAssignForms(n.update,function(){app.persist.deleteAutoAssignForms(n.remove,function(){Wndsr.info("Finish Download Auto Assign Forms"),app.synchronize.downloadGroups()})})})})})},app.synchronize.downloadGroups=function(){Wndsr.info("Begin Download Groups"),app.synchronize.currentStep++,$("html").trigger("startDownloadGroups"),app.persist.getGroupIds(function(n){app.post(app.vroot()+"Mobile/GetGroups/",{groupIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putGroups(n.add,function(){app.persist.putGroups(n.update,function(){app.persist.deleteGroups(n.remove,function(){Wndsr.info("Finish Download Groups"),app.synchronize.downloadRoles()})})})})})},app.synchronize.downloadRoles=function(){Wndsr.info("Begin Download Roles"),app.synchronize.currentStep++,$("html").trigger("startDownloadRoles"),app.persist.getRoleIds(function(n){app.post(app.vroot()+"Mobile/GetRoles/",{roleIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putRoles(n.add,function(){app.persist.putRoles(n.update,function(){app.persist.deleteRoles(n.remove,function(){Wndsr.info("Finish Download Roles"),app.synchronize.downloadGroupRoles()})})})})})},app.synchronize.downloadGroupRoles=function(){Wndsr.info("Begin Download Group Roles"),app.synchronize.currentStep++,$("html").trigger("startDownloadGroupRoles"),app.persist.getGroupRoleIds(function(n){app.post(app.vroot()+"Mobile/GetGroupRoles/",{groupRoleIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putGroupRoles(n.add,function(){app.persist.putGroupRoles(n.update,function(){app.persist.deleteGroupRoles(n.remove,function(){Wndsr.info("Finish Download Group Roles"),app.synchronize.downloadOrganizations()})})})})})},app.synchronize.downloadOrganizations=function(){Wndsr.info("Begin Download Organizations"),app.synchronize.currentStep++,$("html").trigger("startDownloadOrganizations"),app.persist.getOrganizationIds(function(n){app.post(app.vroot()+"Mobile/GetOrganizations/",{organizationIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putOrganizations(n.add,function(){app.persist.putOrganizations(n.update,function(){app.persist.deleteOrganizations(n.remove,function(){Wndsr.info("Finish Download Organizations"),app.synchronize.downloadOrgGroups()})})})})})},app.synchronize.downloadOrgGroups=function(){Wndsr.info("Begin Download Organization Groups"),app.synchronize.currentStep++,$("html").trigger("startDownloadOrgGroups"),app.persist.getOrgGroupIds(function(n){app.post(app.vroot()+"Mobile/GetOrgGroups/",{orgGroupIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putOrgGroups(n.add,function(){app.persist.putOrgGroups(n.update,function(){app.persist.deleteOrgGroups(n.remove,function(){Wndsr.info("Finish Download Organization Groups"),app.synchronize.downloadInspectionTypes()})})})})})},app.synchronize.downloadInspectionTypes=function(){Wndsr.info("Begin Download Inspection Types"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspectionTypes"),app.persist.getInspectionTypeIds(function(n){app.post(app.vroot()+"Mobile/GetInspectionTypes/",{inspectionTypeIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putInspectionTypes(n.add,function(){app.persist.putInspectionTypes(n.update,function(){app.persist.deleteInspectionTypes(n.remove,function(){Wndsr.info("Finish Download Inspection Types"),app.synchronize.downloadOrgInspectionTypes()})})})})})},app.synchronize.downloadOrgInspectionTypes=function(){Wndsr.info("Begin Download Organization Inspection Types"),app.synchronize.currentStep++,$("html").trigger("startDownloadOrgInspectionTypes"),app.persist.getOrgInspectionTypeIds(function(n){app.post(app.vroot()+"Mobile/GetOrgInspectionTypes/",{orgInspectionTypeIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putOrgInspectionTypes(n.add,function(){app.persist.putOrgInspectionTypes(n.update,function(){app.persist.deleteOrgInspectionTypes(n.remove,function(){Wndsr.info("Finish Download Organization Inspection Types"),app.synchronize.downloadForms()})})})})})},app.synchronize.downloadForms=function(){Wndsr.info("Begin Download Forms"),app.synchronize.currentStep++,$("html").trigger("startDownloadForms"),app.persist.getFormIds(function(n){app.post(app.vroot()+"Mobile/GetForms/",{formIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putForms(n.add,function(){app.persist.putForms(n.update,function(){app.persist.deleteForms(n.remove,function(){Wndsr.info("Finish Download Forms"),app.synchronize.downloadFormVersions()})})})})})},app.synchronize.downloadFormVersions=function(){Wndsr.info("Begin Download Form Versions"),app.synchronize.currentStep++,$("html").trigger("startDownloadFormVersions"),app.persist.getFormVersionIds(function(n){app.post(app.vroot()+"Mobile/GetFormVersions/",{formVersionIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putFormVersions(n.add,function(){app.persist.putFormVersions(n.update,function(){app.persist.deleteFormVersions(n.remove,function(){Wndsr.info("Finish Download Form Versions"),app.synchronize.downloadFormSections()})})})})})},app.synchronize.downloadFormSections=function(){Wndsr.info("Begin Download Form Sections"),app.synchronize.currentStep++,$("html").trigger("startDownloadFormSections"),app.persist.getFormSectionIds(function(n){app.post(app.vroot()+"Mobile/GetFormSections/",{formSectionIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putFormSections(n.add,function(){app.persist.putFormSections(n.update,function(){app.persist.deleteFormSections(n.remove,function(){Wndsr.info("Finish Download Form Sections"),app.synchronize.downloadFormControls()})})})})})},app.synchronize.downloadFormControls=function(){Wndsr.info("Begin Download Form Controls"),app.synchronize.currentStep++,$("html").trigger("startDownloadFormControls"),app.persist.getFormControlIds(function(n){app.post(app.vroot()+"Mobile/GetFormControls/",{formControlIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putFormControls(n.add,function(){app.persist.putFormControls(n.update,function(){app.persist.deleteFormControls(n.remove,function(){Wndsr.info("Finish Download Form Controls"),app.synchronize.downloadInspections()})})})})})},app.synchronize.downloadInspections=function(){Wndsr.info("Begin Download Inspections"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspections"),app.persist.getInspectionIds(function(n){app.post(app.vroot()+"Mobile/GetInspections/",{inspectionIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putInspections(n.add,function(){app.persist.putInspections(n.update,function(){app.persist.deleteInspections(n.remove,function(){Wndsr.info("Finish Download Inspections"),app.synchronize.downloadInspectionCmeValues()})})})})})},app.synchronize.downloadInspectionCmeValues=function(){Wndsr.info("Begin Download Inspection Cme Values"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspectionCmeValues"),app.persist.getInspectionCmeValueIds(function(n){app.post(app.vroot()+"Mobile/GetInspectionCmeValues/",{inspectionCmeValueIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putInspectionCmeValues(n.add,function(){app.persist.putInspectionCmeValues(n.update,function(){app.persist.deleteInspectionCmeValues(n.remove,function(){Wndsr.info("Finish Download Inspection Cme Values"),app.synchronize.downloadInspectionForms()})})})})})},app.synchronize.downloadInspectionForms=function(){Wndsr.info("Begin Download Inspection Forms"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspectionForms"),app.persist.getInspectionFormIds(function(n){app.post(app.vroot()+"Mobile/GetInspectionForms/",{inspectionFormIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putInspectionForms(n.add,function(){app.persist.putInspectionForms(n.update,function(){app.persist.deleteInspectionForms(n.remove,function(){Wndsr.info("Finish Download Inspection Forms"),app.synchronize.downloadInspectionFormSections()})})})})})},app.synchronize.downloadInspectionFormSections=function(){Wndsr.info("Begin Download Inspection Form Sections"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspectionFormSections"),app.persist.getInspectionFormSectionIds(function(n){app.post(app.vroot()+"Mobile/GetInspectionFormSections/",{inspectionFormSectionIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putInspectionFormSections(n.add,function(){app.persist.putInspectionFormSections(n.update,function(){app.persist.deleteInspectionFormSections(n.remove,function(){Wndsr.info("Finish Download Inspection Form Sections"),app.synchronize.downloadInspectionFormRepeatingSections()})})})})})},app.synchronize.downloadInspectionFormRepeatingSections=function(){Wndsr.info("Begin Download Inspection Form Repeating Sections"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspectionFormRepeatingSections"),app.persist.getInspectionFormRepeatingSectionIds(function(n){app.post(app.vroot()+"Mobile/GetInspectionFormRepeatingSections/",{inspectionFormRepeatingSectionIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putInspectionFormRepeatingSections(n.add,function(){app.persist.putInspectionFormRepeatingSections(n.update,function(){app.persist.deleteInspectionFormRepeatingSections(n.remove,function(){Wndsr.info("Finish Download Inspection Form Repeating Sections"),app.synchronize.downloadInspectionFormAnswers()})})})})})},app.synchronize.downloadInspectionFormAnswers=function(){Wndsr.info("Begin Download Inspection Form Answers"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspectionFormAnswers"),app.persist.getInspectionFormAnswerIds(function(n){app.post(app.vroot()+"Mobile/GetInspectionFormAnswers/",{inspectionFormAnswerIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.persist.putInspectionFormAnswers(n.add,function(){app.persist.putInspectionFormAnswers(n.update,function(){app.persist.deleteInspectionFormAnswers(n.remove,function(){Wndsr.info("Finish Download Inspection Form Answers"),app.synchronize.downloadInspectionFormMedias()})})})})})},app.synchronize.downloadInspectionFormMedias=function(){app.synchronize.imagesToDownload=[],Wndsr.info("Begin Download Inspection Form Medias"),app.synchronize.currentStep++,$("html").trigger("startDownloadInspectionFormMedias"),app.persist.getInspectionFormMediaIds(function(n){app.post(app.vroot()+"Mobile/GetInspectionFormMedias/",{inspectionFormMediaIds:n,principalId:app.principal.id,lastSyncTime:app.synchronize.serverLastSyncTime},function(n){app.synchronize.imagesToDownload=n.add.slice(),app.synchronize.totalImages=n.add.length,app.synchronize.totalSteps+=app.synchronize.imagesToDownload.length,app.persist.putInspectionFormMedias(n.add,function(){app.persist.putInspectionFormMedias(n.update,function(){app.persist.deleteInspectionFormMedias(n.remove,function(){Wndsr.info("Finish Download Inspection Form Medias"),app.synchronize.downloadImages()})})})})})},app.synchronize.downloadImages=function(){if(app.synchronize.imagesToDownload.length>0){var n=app.synchronize.imagesToDownload.pop();Wndsr.info("Requesting InspectionFormMedia id = "+n.id),app.synchronize.currentImage++,app.synchronize.currentStep++,$("html").trigger("startDownloadImage"),app.post(app.vroot()+"Synchronize/GetInspectionFormMediaSync/",{id:n.id},function(n){app.persist.putFile(n,n.mediaObject,function(){app.synchronize.downloadImages()})},app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish adding InspectionFormMedia"),Wndsr.info("Getting server Conflict list"),app.synchronize.finishSync()},app.synchronize.finishSync=function(){Wndsr.info("Begin Finish Sync"),app.synchronize.currentStep++,$("html").trigger("startFinishSync"),app.post(app.vroot()+"Mobile/SyncComplete/",{syncSession:app.synchronize.syncSession},function(n){app.isSyncing=!1,app.synchronize.localLastSyncTime=new moment,app.synchronize.serverLastSyncTime=n.lastSyncTime,app.synchronize.syncSession=null,app.persist.setKeyValue("SERVERLASTSYNCTIME",app.synchronize.serverLastSyncTime,function(){app.persist.setKeyValue("LOCALLASTSYNCTIME",app.synchronize.localLastSyncTime,function(){app.synchronize.currentStep++,$("html").trigger("synchronizeComplete"),Wndsr.info("Finish Finish Sync")})})},app.synchronize.syncFailed)},app.synchronize.uploadData=function(n,t,i){if(n>=app.synchronize.syncState.length){Wndsr.info("Finish uploading data"),$("html").trigger("uploadDataSuccess"),app.synchronize.processUpload();return}if(t===null&&i===null&&$("html").trigger("startSyncInspection",app.synchronize.syncState[n].id),t!==null&&t>=app.synchronize.syncState[n].inspectionFormList.length)return $("html").trigger("finishSyncInspection",app.synchronize.syncState[n].id),n++,app.synchronize.uploadData(n,null,null);if(i!==null&&i>=app.synchronize.syncState[n].inspectionFormList[t].inspectionFormMediaList.length)return $("html").trigger("finishSyncInspectionForm",app.synchronize.syncState[n].inspectionFormList[t].inspectionFormId),t++,app.synchronize.uploadData(n,t,null);if(t===null&&i===null)if(app.synchronize.syncState[n].isDirty)app.persist.getItem(app.synchronize.syncState[n].id).then(function(t){if(t!==null)t.isDirty=app.synchronize.syncState[n].isDirty,t.isNew=app.synchronize.syncState[n].isNew,t.isDeleted=app.synchronize.syncState[n].isDeleted,Wndsr.info("Updating Inspection, inspectionId = "+t.id),$("html").trigger("uploadDataItemBegin",[t.id,null,null]),$("html").trigger("startUploadInspection",t.id),app.post(app.vroot()+"NewSynchronize/UpdateInspection/",{inspection:t,syncSession:app.synchronize.syncSession},function(){return app.synchronize.uploadedInspectionCount++,$("html").trigger("uploadDataItemSuccess",[t.id,null,null]),$("html").trigger("finishUploadInspection",t.id),app.synchronize.uploadData(n,0,null)},app.synchronize.syncFailed);else return Wndsr.info("Inspection was null"),app.synchronize.uploadedInspectionCount++,$("html").trigger("uploadDataItemSuccess",[t.id,null,null]),$("html").trigger("finishUploadInspection",t.id),app.synchronize.uploadData(n,0,null)});else return app.synchronize.uploadData(n,0,null);else if(i===null)if(app.synchronize.syncState[n].inspectionFormList[t].isDirty)app.persist.getItem(app.synchronize.syncState[n].inspectionFormList[t].id).then(function(i){if(i!=null)i.isDirty=app.synchronize.syncState[n].inspectionFormList[t].isDirty,i.isNew=app.synchronize.syncState[n].inspectionFormList[t].isNew,i.isDeleted=app.synchronize.syncState[n].inspectionFormList[t].isDeleted,i.isDeleted&&!i.isNew?(Wndsr.info("Deleting Inspection Form, inspectionId = "+app.synchronize.syncState[n].id+", inspectionFormId = "+i.id),$("html").trigger("uploadDataItemBegin",[app.synchronize.syncState[n].id,i.id,null]),$("html").trigger("startUploadInspectionForm",i.id),app.post(app.vroot()+"NewSynchronize/UpdateInspectionForm/",{inspectionForm:i,syncSession:app.synchronize.syncSession},function(){return app.synchronize.uploadedInspectionFormCount++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,i.id,null]),$("html").trigger("finishUploadInspectionForm",i.id),app.synchronize.uploadData(n,t,0)},app.synchronize.syncFailed)):i.isNew&&!i.isDeleted?(Wndsr.info("Adding Inspection Form, inspectionId = "+app.synchronize.syncState[n].id+", inspectionFormId = "+i.id),$("html").trigger("uploadDataItemBegin",[app.synchronize.syncState[n].id,i.id,null]),$("html").trigger("startUploadInspectionForm",i.id),app.post(app.vroot()+"NewSynchronize/UpdateInspectionForm/",{inspectionForm:i,syncSession:app.synchronize.syncSession},function(){return app.synchronize.uploadedInspectionFormCount++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,i.id,null]),$("html").trigger("finishUploadInspectionForm",i.id),app.synchronize.uploadData(n,t,0)},app.synchronize.syncFailed)):(Wndsr.info("Updating Inspection Form, inspectionId = "+app.synchronize.syncState[n].id+", inspectionFormId = "+i.id),$("html").trigger("uploadDataItemBegin",[app.synchronize.syncState[n].id,i.id,null]),$("html").trigger("startUploadInspectionForm",i.id),app.post(app.vroot()+"NewSynchronize/UpdateInspectionForm/",{inspectionForm:i,syncSession:app.synchronize.syncSession},function(){return app.synchronize.uploadedInspectionFormCount++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,i.id,null]),$("html").trigger("finishUploadInspectionForm",i.id),app.synchronize.uploadData(n,t,0)},app.synchronize.syncFailed));else return Wndsr.info("Inspection Form was null"),app.synchronize.uploadedInspectionFormCount++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,i.id,null]),$("html").trigger("finishUploadInspectionForm",i.id),app.synchronize.uploadData(n,t,0)});else return app.synchronize.uploadData(n,t,0);else if(app.synchronize.syncState[n].inspectionFormList[t].inspectionFormMediaList[i].isDirty)app.persist.getItem(app.synchronize.syncState[n].inspectionFormList[t].inspectionFormMediaList[i].id).then(function(r){if(r!=null)r.isDirty=app.synchronize.syncState[n].inspectionFormList[t].inspectionFormMediaList[i].isDirty,r.isNew=app.synchronize.syncState[n].inspectionFormList[t].inspectionFormMediaList[i].isNew,r.isDeleted=app.synchronize.syncState[n].inspectionFormList[t].inspectionFormMediaList[i].isDeleted,r.isDeleted&&!r.isNew?(Wndsr.info("Deleting Inspection Form Media, inspectionId = "+app.synchronize.syncState[n].id+", inspectionFormId = "+app.synchronize.syncState[n].inspectionFormList[t].id+", inspectionFormMediaId = "+r.id),$("html").trigger("uploadDataItemBegin",[app.synchronize.syncState[n].id,app.synchronize.syncState[n].inspectionFormList[t].id,r.id]),$("html").trigger("startUploadInspectionFormMedia",r.id),app.post(app.vroot()+"NewSynchronize/UpdateInspectionFormMediaDelete/",{inspectionFormMedia:r,syncSession:app.synchronize.syncSession},function(){return app.synchronize.uploadedInspectionFormMediaCount++,i++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,app.synchronize.syncState[n].inspectionFormList[t].id,r.id]),$("html").trigger("finishUploadInspectionFormMedia",r.id),app.synchronize.uploadData(n,t,i)},app.synchronize.syncFailed)):r.isNew&&!r.isDeleted?(Wndsr.info("Adding Inspection Form Media, inspectionId = "+app.synchronize.syncState[n].id+", inspectionFormId = "+app.synchronize.syncState[n].inspectionFormList[t].id+", inspectionFormMediaId = "+r.id),$("html").trigger("uploadDataItemBegin",[app.synchronize.syncState[n].id,app.synchronize.syncState[n].inspectionFormList[t].id,r.id]),$("html").trigger("startUploadInspectionFormMedia",r.id),app.post(app.vroot()+"NewSynchronize/UpdateInspectionFormMedia/",{inspectionFormMedia:r,syncSession:app.synchronize.syncSession},function(){return app.synchronize.uploadedInspectionFormMediaCount++,i++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,app.synchronize.syncState[n].inspectionFormList[t].id,r.id]),$("html").trigger("finishUploadInspectionFormMedia",r.id),app.synchronize.uploadData(n,t,i)},app.synchronize.syncFailed)):(Wndsr.info("Updating Inspection Form Media, inspectionId = "+app.synchronize.syncState[n].id+", inspectionFormId = "+app.synchronize.syncState[n].inspectionFormList[t].id+", inspectionFormMediaId = "+r.id),$("html").trigger("uploadDataItemBegin",[app.synchronize.syncState[n].id,app.synchronize.syncState[n].inspectionFormList[t].id,r.id]),$("html").trigger("startUploadInspectionFormMedia",r.id),app.post(app.vroot()+"NewSynchronize/UpdateInspectionFormMedia/",{inspectionFormMedia:r,syncSession:app.synchronize.syncSession},function(){return app.synchronize.uploadedInspectionFormMediaCount++,i++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,app.synchronize.syncState[n].inspectionFormList[t].id,r.id]),$("html").trigger("finishUploadInspectionFormMedia",r.id),app.synchronize.uploadData(n,t,i)},app.synchronize.syncFailed));else return Wndsr.info("Inspection Form Media was null"),app.synchronize.uploadedInspectionFormMediaCount++,i++,$("html").trigger("uploadDataItemSuccess",[app.synchronize.syncState[n].id,app.synchronize.syncState[n].inspectionFormList[t].id,r.id]),$("html").trigger("finishUploadInspectionFormMedia",r.id),app.synchronize.uploadData(n,t,i)});else return app.synchronize.uploadData(n,t,i++)},app.synchronize.prepareDownload=function(){var n;for(Wndsr.info("Clearing Inspection dirty flags"),n=0;n<app.synchronize.inspectionList.length;n++)app.synchronize.inspectionList[n].isDeleted=!1,app.synchronize.inspectionList[n].isDirty=!1,app.synchronize.inspectionList[n].isNew=!1;for(app.persist.setItem("INSPECTIONLIST",app.synchronize.inspectionList),Wndsr.info("Clearing Inspection Form dirty flags"),n=0;n<app.synchronize.inspectionFormList.length;n++)app.synchronize.inspectionFormList[n].isDeleted=!1,app.synchronize.inspectionFormList[n].isDirty=!1,app.synchronize.inspectionFormList[n].isNew=!1;for(app.persist.setItem("INSPECTIONFORMLIST",app.synchronize.inspectionFormList),Wndsr.info("Clearing Inspection Form Media dirty flags"),n=0;n<app.synchronize.inspectionFormMediaList.length;n++)app.synchronize.inspectionFormMediaList[n].isDeleted=!1,app.synchronize.inspectionFormMediaList[n].isDirty=!1,app.synchronize.inspectionFormMediaList[n].isNew=!1;app.persist.setItem("INSPECTIONFORMMEDIALIST",app.synchronize.inspectionFormMediaList),Wndsr.info("Preparing Download"),$("html").trigger("prepareDownloadBegin"),app.post(app.vroot()+"NewSynchronize/GetOfflineLists/",{syncSession:app.synchronize.syncSession},function(n){app.synchronize.serverFormVersionList=n.formVersionList,app.synchronize.serverInspectionList=n.inspectionList,app.synchronize.serverInspectionFormList=n.inspectionFormList,app.synchronize.serverInspectionFormMediaList=n.inspectionFormMediaList,Promise.all([app.persist.setItem("CONFLICTLIST",n.conflictList),app.persist.setItem("ORGANIZATIONLIST",n.organizationList),app.persist.setItem("PRINCIPALLIST",n.principalList),app.persist.setItem("PRINCIPALSENSITIVELIST",n.principalSensitiveSensitive),app.persist.setItem("PROJECTLIST",n.projectList)]).then(function(){var t,r,i;for(Wndsr.info("Begin finding FormVersions to remove"),i=0;i<app.synchronize.formVersionList.length;i++){for(r=!1,t=0;t<n.formVersionList.length;t++)if(app.synchronize.formVersionList[i].id===n.formVersionList[t].id){r=!0;break}r||app.synchronize.formVersionsToRemove.push(app.synchronize.formVersionList[i])}for(Wndsr.info("Finish finding formVersions to remove, count = "+app.synchronize.formVersionsToRemove.length),Wndsr.info("Begin finding formVersions to add"),t=0;t<n.formVersionList.length;t++){for(r=!1,i=0;i<app.synchronize.formVersionList.length;i++)if(n.formVersionList[t].id===app.synchronize.formVersionList[i].id){r=!0;break}r||app.synchronize.formVersionsToAdd.push(n.formVersionList[t].id)}for(Wndsr.info("Finish finding templates to add, count = "+app.synchronize.formVersionsToAdd.length),Wndsr.info("Begin finding Inspections to remove"),i=0;i<app.synchronize.inspectionList.length;i++){for(r=!1,t=0;t<n.inspectionList.length;t++)if(app.synchronize.inspectionList[i].id===n.inspectionList[t].id){r=!0;break}r||app.synchronize.inspectionsToRemove.push(app.synchronize.inspectionList[i])}for(Wndsr.info("Finish finding inspections to remove, count = "+app.synchronize.inspectionsToRemove.length),Wndsr.info("Begin finding inspections to add"),t=0;t<n.inspectionList.length;t++){for(r=!1,i=0;i<app.synchronize.inspectionList.length;i++)if(n.inspectionList[t].id===app.synchronize.inspectionList[i].id&&n.inspectionList[t].changedOn===app.synchronize.inspectionList[i].changedOn){r=!0;break}r||app.synchronize.inspectionsToAdd.push(n.inspectionList[t].id)}for(Wndsr.info("Finish finding inspections to add, count = "+app.synchronize.inspectionsToAdd.length),Wndsr.info("Begin finding InspectionForms to remove"),i=0;i<app.synchronize.inspectionFormList.length;i++){for(r=!1,t=0;t<n.inspectionFormList.length;t++)if(app.synchronize.inspectionFormList[i].id===n.inspectionFormList[t].id){r=!0;break}r||app.synchronize.inspectionFormsToRemove.push(app.synchronize.inspectionFormList[i])}for(Wndsr.info("Finish finding inspectionForms to remove, count = "+app.synchronize.inspectionFormsToRemove.length),Wndsr.info("Begin finding inspectionForms to add"),t=0;t<n.inspectionFormList.length;t++){for(r=!1,i=0;i<app.synchronize.inspectionFormList.length;i++)if(n.inspectionFormList[t].id===app.synchronize.inspectionFormList[i].id&&n.inspectionFormList[t].changedOn===app.synchronize.inspectionFormList[i].changedOn){r=!0;break}r||app.synchronize.inspectionFormsToAdd.push(n.inspectionFormList[t].id)}for(Wndsr.info("Finish finding inspectionForms to add, count = "+app.synchronize.inspectionFormsToAdd.length),Wndsr.info("Begin finding InspectionFormMedias to remove"),i=0;i<app.synchronize.inspectionFormMediaList.length;i++){for(r=!1,t=0;t<n.inspectionFormMediaList.length;t++)if(app.synchronize.inspectionFormMediaList[i].id===n.inspectionFormMediaList[t].id){r=!0;break}r||app.synchronize.inspectionFormMediasToRemove.push(app.synchronize.inspectionFormMediaList[i])}for(Wndsr.info("Finish finding inspectionFormMedias to remove, count = "+app.synchronize.inspectionFormMediasToRemove.length),Wndsr.info("Begin finding inspectionFormMedias to add"),t=0;t<n.inspectionFormMediaList.length;t++){for(r=!1,i=0;i<app.synchronize.inspectionFormMediaList.length;i++)if(n.inspectionFormMediaList[t].id===app.synchronize.inspectionFormMediaList[i].id&&n.inspectionFormMediaList[t].changedOn===app.synchronize.inspectionFormMediaList[i].changedOn){r=!0;break}r||app.synchronize.inspectionFormMediasToAdd.push(n.inspectionFormMediaList[t].id)}Wndsr.info("Finish finding inspectionFormMedias to add, count = "+app.synchronize.inspectionFormMediasToAdd.length),Wndsr.info("Finished processing download"),Wndsr.info("Begin downloading FormVersions"),app.synchronize.dirtyFormVersionCount=app.synchronize.formVersionsToAdd.length,app.synchronize.dirtyInspectionFormMediaCount=app.synchronize.inspectionFormMediasToAdd.length,app.synchronize.dirtyInspectionCount=app.synchronize.inspectionsToAdd.length,app.synchronize.dirtyInspectionFormCount=app.synchronize.inspectionFormsToAdd.length,app.synchronize.totalTirdty=app.synchronize.dirtyFormVersionCount+app.synchronize.dirtyInspectionFormMediaCount+app.synchronize.dirtyInspectionCount+app.synchronize.dirtyInspectionFormCount,$("html").trigger("prepareDownloadSuccess"),app.synchronize.downloadFormVersions()},function(n){alert(n)})},app.synchronize.syncFailed)},app.synchronize.syncFailed=function(n){n.statusText==="Retry with authentication"?alert("Your session has expired, please log in again."):alert("Synchronization failed.  Unable to upload all data from the tablet."),app.isSyncing=!1,app.syncId=null,Wndsr.setLocalStorage("SyncKey",null),$.unblockUI()},app.synchronize.syncFailedPostUpload=function(){alert("All data was uploaded, but the synchronization failed downloading data to the tablet.  Logging user out."),app.principal=null,app.isMobile(),Wndsr.clearLocalStorage(),window.location.reload(),app.isSyncing=!1,app.syncId=null,Wndsr.setLocalStorage("SyncKey",null),$.unblockUI()},app.synchronize.getLocalFormVersionListSuccess=function(n){Wndsr.info("Success Getting local FormVersion list"),app.synchronize.formVersionList=n===null?[]:n,Wndsr.info("Getting local Inspection list"),app.getWebSql("inspectionList",app.synchronize.getLocalInspectionListSuccess,app.synchronize.syncFailed)},app.synchronize.getLocalInspectionListSuccess=function(n){Wndsr.info("Success Getting local Inspection list"),app.synchronize.inspectionList=n===null?[]:n,Wndsr.info("Getting local InspectionForm list"),app.getWebSql("inspectionFormList",app.synchronize.getLocalInspectionFormListSuccess,app.synchronize.syncFailed)},app.synchronize.getLocalInspectionFormListSuccess=function(n){Wndsr.info("Success Getting local InspectionForm list"),app.synchronize.inspectionFormList=n===null?[]:n,Wndsr.info("Getting local InspectionFormMedia list"),app.getWebSql("inspectionFormMediaList",app.synchronize.getLocalInspectionFormMediaListSuccess,app.synchronize.syncFailed)},app.synchronize.getLocalInspectionFormMediaListSuccess=function(n){var i,t;Wndsr.info("Success Getting local InspectionFormMedia list"),app.synchronize.inspectionFormMediaList=n===null?[]:n,$.blockUI({message:"<h1>Uploading Inspections<\/h1>"});var u=0,r=0,f=0;for(i=0;i<app.synchronize.inspectionList.length;i++)t=app.synchronize.inspectionList[i],t.isDirty&&(t.isDeleted&&!t.isNew?f++:t.isNew&&!t.isDeleted?r++:u++);app.post(app.vroot()+"Synchronize/ReportInspectionData/",{syncId:app.syncId,dirtyCount:u,newCount:r,deletedCount:f},function(){Wndsr.info("Begin Uploading Dirty Inspections"),app.synchronize.syncDirtyInspections()},app.synchronize.syncFailed)},app.synchronize.syncDirtyInspections=function(){for(var n,i,t;app.synchronize.listIndex<app.synchronize.inspectionList.length;)if(n=app.synchronize.inspectionList[app.synchronize.listIndex],app.synchronize.listIndex++,n.isDirty){n.isDeleted&&!n.isNew?app.post(app.vroot()+"Synchronize/DeleteInspection/",{id:n.id,syncId:app.syncId},app.synchronize.syncDirtyInspections,app.synchronize.syncFailed):n.isNew&&!n.isDeleted?app.getWebSql(n.id,app.synchronize.addNewInspection,app.synchronize.syncFailed):app.getInspection(n.id,app.synchronize.updateInspection,app.synchronize.syncFailed);return}Wndsr.info("Finish Uploading Dirty Inspections"),$.blockUI({message:"<h1>Uploading Inspection Forms<\/h1>"}),app.synchronize.listIndex=0;var u=0,r=0,f=0;for(i=0;i<app.synchronize.inspectionFormList.length;i++)t=app.synchronize.inspectionFormList[i],t.isDirty&&(t.isDeleted&&!t.isNew?f++:t.isNew&&!t.isDeleted?r++:u++);app.post(app.vroot()+"Synchronize/ReportInspectionFormData/",{syncId:app.syncId,dirtyCount:u,newCount:r,deletedCount:f},function(){Wndsr.info("Begin Uploading Dirty InspectionForms"),app.synchronize.syncDirtyInspectionForms()},app.synchronize.syncFailed)},app.synchronize.addNewInspection=function(n){app.post(app.vroot()+"Synchronize/NewInspection/",{inspection:n,syncId:app.syncId},app.synchronize.syncDirtyInspections,app.synchronize.syncFailed)},app.synchronize.updateInspection=function(n){app.post(app.vroot()+"Synchronize/UpdateInspection/",{inspection:n,syncId:app.syncId},app.synchronize.syncDirtyInspections,app.synchronize.syncFailed)},app.synchronize.syncDirtyInspectionForms=function(){for(var n,i,t;app.synchronize.listIndex<app.synchronize.inspectionFormList.length;)if(n=app.synchronize.inspectionFormList[app.synchronize.listIndex],app.synchronize.listIndex++,n.isDirty){n.isDeleted&&!n.isNew?app.post(app.vroot()+"Synchronize/DeleteInspectionForm/",{id:n.id,syncId:app.syncId},function(){app.deleteWebSql(n.id,app.synchronize.syncDirtyInspectionForms,app.synchronize.syncFailed)},app.synchronize.syncFailed):n.isNew&&!n.isDeleted?app.getWebSql(n.id,app.synchronize.addNewInspectionForm,app.synchronize.syncFailed):n.isDeleted?app.synchronize.syncDirtyInspectionForms():app.getWebSql(n.id,app.synchronize.updateInspectionForm,app.synchronize.syncFailed);return}Wndsr.info("Finish Uploading Dirty Inspection Forms"),$.blockUI({message:"<h1>Synchronizing Media<\/h1>"}),app.synchronize.listIndex=0;var u=0,r=0,f=0;for(i=0;i<app.synchronize.inspectionFormMediaList.length;i++)t=app.synchronize.inspectionFormMediaList[i],t.isDirty&&(t.isDeleted&&!t.isNew?f++:t.isNew&&!t.isDeleted?r++:u++);app.post(app.vroot()+"Synchronize/ReportInspectionFormMediaData/",{syncId:app.syncId,dirtyCount:u,newCount:r,deletedCount:f},function(){Wndsr.info("Syncing dirty inspection form media"),app.synchronize.syncDirtyInspectionFormMedias()},app.synchronize.syncFailed)},app.synchronize.addNewInspectionForm=function(n){app.post(app.vroot()+"Synchronize/NewInspectionForm/",{inspectionForm:n,syncId:app.syncId},app.synchronize.syncDirtyInspectionForms,app.synchronize.syncFailed)},app.synchronize.updateInspectionForm=function(n){app.post(app.vroot()+"Synchronize/UpdateInspectionForm/",{inspectionForm:n,syncId:app.syncId},app.synchronize.syncDirtyInspectionForms,app.synchronize.syncFailed)},app.synchronize.syncDirtyInspectionFormMedias=function(){while(app.synchronize.listIndex<app.synchronize.inspectionFormMediaList.length){var n=app.synchronize.inspectionFormMediaList[app.synchronize.listIndex];if(app.synchronize.listIndex++,n.isDeleted){app.post(app.vroot()+"Synchronize/DeleteInspectionFormMedia/",{id:n.id,syncId:app.syncId},app.synchronize.syncDirtyInspectionFormMedias,app.synchronize.syncFailed);return}if(n.isNew){app.getWebSql(n.id,function(t){app.post(app.vroot()+"Synchronize/UpdateInspectionFormMediaSync/",{id:n.id,mimeType:t.mimeType,mediaObject:t.mediaObject,latitude:t.gpsLatitude,longitude:t.gpsLongitude,altitude:t.gpsAltitude,azimuth:t.gpsAzimuth,orientation:t.gpsOrientation,imageDateTime:t.imageCapturedTime,comment:t.metadataComment,syncId:app.syncId},app.synchronize.syncDirtyInspectionFormMedias,app.synchronize.syncFailed)},app.synchronize.syncFailed);return}if(n.isDirty){app.getWebSql(n.id,function(t){app.post(app.vroot()+"Synchronize/UpdateInspectionFormMedia/",{id:n.id,comment:t.metadataComment,syncId:app.syncId},app.synchronize.syncDirtyInspectionFormMedias,app.synchronize.syncFailed)},app.synchronize.syncFailed);return}}Wndsr.info("Finish Uploading Dirty Inspection Form Media"),$.blockUI({message:"<h1>Synchronizing Principals<\/h1>"}),Wndsr.info("Getting server Principal list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetPrincipalList/"+app.principal.id,headers:{"cache-control":"no-cache"},contentType:"application/json; charset=utf-8",success:app.synchronize.getPrincipalListSuccess,error:app.synchronize.syncFailed})},app.synchronize.getPrincipalListSuccess=function(n){n||app.synchronize.syncFailed(),Wndsr.info("Request server principal list Success"),app.setWebSql("principalList",n,function(){$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetSensitivePrincipalList/"+app.principal.id,headers:{"cache-control":"no-cache"},contentType:"application/json; charset=utf-8",success:app.synchronize.getSensitivePrincipalListSuccess,error:app.synchronize.syncFailedPostUpload})},app.synchronize.syncFailedPostUpload)},app.synchronize.getSensitivePrincipalListSuccess=function(n){Wndsr.info("Request server sensitive principal list Success"),app.setWebSql("principalSensitiveList",n,function(){$.blockUI({message:"<h1>Synchronizing Projects<\/h1>"}),Wndsr.info("Getting server Project list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetProjectList/"+app.principal.id,headers:{"cache-control":"no-cache"},contentType:"application/json; charset=utf-8",success:app.synchronize.getProjectListSuccess,error:app.synchronize.syncFailedPostUpload})},app.synchronize.syncFailedPostUpload)},app.synchronize.getProjectListSuccess=function(n){Wndsr.info("Request server project list Success"),app.setWebSql("projectList",n,function(){$.blockUI({message:"<h1>Synchronizing Organizations<\/h1>"}),Wndsr.info("Getting server Organization list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetOrganizationList/"+app.principal.id,headers:{"cache-control":"no-cache"},contentType:"application/json; charset=utf-8",success:app.synchronize.getServerOrganizationListSuccess,error:app.synchronize.syncFailedPostUpload})},app.synchronize.syncFailedPostUpload)},app.synchronize.getServerOrganizationListSuccess=function(n){Wndsr.info("Request server sensitive organization list Success"),app.setWebSql("organizationList",n,function(){$.blockUI({message:"<h1>Synchronizing Templates<\/h1>"}),Wndsr.info("Getting server FormVersion list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetFormVersionList/"+app.principal.id,headers:{"cache-control":"no-cache"},contentType:"application/json; charset=utf-8",success:app.synchronize.getServerFormVersionListSuccess,error:app.synchronize.syncFailedPostUpload})},app.synchronize.syncFailedPostUpload)},app.synchronize.getServerFormVersionListSuccess=function(n){var r,f,u;if(!n){app.synchronize.syncFailedPostUpload();return}for(Wndsr.info("Request server formVersion list Success"),Wndsr.info("Begin finding FormVersions to remove"),u=0;u<app.synchronize.formVersionList.length;u++){for(f=!1,r=0;r<n.length;r++)if(app.synchronize.formVersionList[u].id===n[r].id){f=!0;break}f||app.synchronize.formVersionsToRemove.push(app.synchronize.formVersionList[u])}for(Wndsr.info("Finish finding formVersions to remove, count = "+app.synchronize.formVersionsToRemove.length),Wndsr.info("Begin finding formVersions to add"),r=0;r<n.length;r++){for(f=!1,u=0;u<app.synchronize.formVersionList.length;u++)if(n[r].id===app.synchronize.formVersionList[u].id){f=!0;break}f||app.synchronize.formVersionsToAdd.push(n[r].id)}Wndsr.info("Finish finding templates to add, count = "+app.synchronize.formVersionsToAdd.length),Wndsr.info("Setting local FormVersion list"),app.setWebSql("formVersionList",n,app.synchronize.setLocalFormVersionListSuccess,app.synchronize.syncFailedPostUpload)},app.synchronize.setLocalFormVersionListSuccess=function(){Wndsr.info("Success setting local FormVersion list"),Wndsr.info("Begin removing FormVersions"),app.synchronize.removeLocalFormVersions()},app.synchronize.removeLocalFormVersions=function(){if(app.synchronize.formVersionsToRemove.length>0){var n=app.synchronize.formVersionsToRemove.pop();Wndsr.info("Removing FormVersion id = "+n),app.deleteWebSql(n,app.synchronize.removeLocalFormVersions,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish removing FormVerions"),Wndsr.info("Begin adding FormVersions"),app.synchronize.addLocalFormVersions()},app.synchronize.addLocalFormVersions=function(){if(app.synchronize.formVersionsToAdd.length>0){var n=app.synchronize.formVersionsToAdd.pop();Wndsr.info("Requesting FormVersion id = "+n),app.post(app.vroot()+"Synchronize/GetFormVersion/",{id:n},app.synchronize.getServerFormVersionSuccess,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish adding FormVerions"),$.blockUI({message:"<h1>Synchronizing Inspections<\/h1>"}),Wndsr.info("Getting server Inspection list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:app.synchronize.getServerInspectionListSuccess,headers:{"cache-control":"no-cache"},error:app.synchronize.syncFailedPostUpload})},app.synchronize.getServerFormVersionSuccess=function(n){if(!n){app.synchronize.syncFailedPostUpload();return}Wndsr.info("Request FormVersion success"),app.setWebSql(n.id,n,app.synchronize.addLocalFormVersions,app.synchronize.syncFailedPostUpload)},app.synchronize.getServerInspectionListSuccess=function(n){var r,f,u;if(!n){app.synchronize.syncFailedPostUpload();return}for(Wndsr.info("Request server inspection list Success"),Wndsr.info("Begin finding Inspections to remove"),u=0;u<app.synchronize.inspectionList.length;u++){for(f=!1,r=0;r<n.length;r++)if(app.synchronize.inspectionList[u].id===n[r].id){f=!0;break}f||app.synchronize.inspectionsToRemove.push(app.synchronize.inspectionList[u])}for(Wndsr.info("Finish finding inspections to remove, count = "+app.synchronize.inspectionsToRemove.length),Wndsr.info("Begin finding inspections to add"),r=0;r<n.length;r++){for(f=!1,u=0;u<app.synchronize.inspectionList.length;u++)if(n[r].id===app.synchronize.inspectionList[u].id&&n[r].changedOn===app.synchronize.inspectionList[u].changedOn){f=!0;break}f||app.synchronize.inspectionsToAdd.push(n[r].id)}Wndsr.info("Finish finding inspections to add, count = "+app.synchronize.inspectionsToAdd.length),Wndsr.info("Setting local Inspection list"),app.setWebSql("inspectionList",n,app.synchronize.setLocalInspectionListSuccess,app.synchronize.syncFailedPostUpload)},app.synchronize.setLocalInspectionListSuccess=function(){Wndsr.info("Success setting local Inspection list"),Wndsr.info("Begin removing Inspections"),app.synchronize.removeLocalInspections()},app.synchronize.removeLocalInspections=function(){if(app.synchronize.inspectionsToRemove.length>0){var n=app.synchronize.inspectionsToRemove.pop();Wndsr.info("Removing Inspection id = "+n),app.deleteWebSql(n,app.synchronize.removeLocalInspections,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish removing Inspections"),Wndsr.info("Begin adding Inspections"),app.synchronize.addLocalInspections()},app.synchronize.addLocalInspections=function(){if(app.synchronize.inspectionsToAdd.length>0){var n=app.synchronize.inspectionsToAdd.pop();Wndsr.info("Requesting Inspection id = "+n),app.post(app.vroot()+"Synchronize/GetInspection/",{id:n},app.synchronize.getServerInspectionSuccess,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish adding Inspection"),$.blockUI({message:"<h1>Synchronizing Inspection Forms<\/h1>"}),Wndsr.info("Getting server InspectionForm list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionFormList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:app.synchronize.getServerInspectionFormListSuccess,headers:{"cache-control":"no-cache"},error:app.synchronize.syncFailedPostUpload})},app.synchronize.getServerInspectionSuccess=function(n){if(!n){app.synchronize.syncFailedPostUpload();return}Wndsr.info("Request Inspection success"),app.setWebSql(n.id,n,app.synchronize.addLocalInspections,app.synchronize.syncFailedPostUpload)},app.synchronize.getServerInspectionFormListSuccess=function(n){var r,f,u;if(!n){app.synchronize.syncFailedPostUpload();return}for(Wndsr.info("Request server inspectionForm list Success"),Wndsr.info("Begin finding InspectionForms to remove"),u=0;u<app.synchronize.inspectionFormList.length;u++){for(f=!1,r=0;r<n.length;r++)if(app.synchronize.inspectionFormList[u].id===n[r].id){f=!0;break}f||app.synchronize.inspectionFormsToRemove.push(app.synchronize.inspectionFormList[u])}for(Wndsr.info("Finish finding inspectionForms to remove, count = "+app.synchronize.inspectionFormsToRemove.length),Wndsr.info("Begin finding inspectionForms to add"),r=0;r<n.length;r++){for(f=!1,u=0;u<app.synchronize.inspectionFormList.length;u++)if(n[r].id===app.synchronize.inspectionFormList[u].id&&n[r].changedOn===app.synchronize.inspectionFormList[u].changedOn){f=!0;break}f||app.synchronize.inspectionFormsToAdd.push(n[r].id)}Wndsr.info("Finish finding inspectionForms to add, count = "+app.synchronize.inspectionFormsToAdd.length),Wndsr.info("Setting local InspectionForm list"),app.setWebSql("inspectionFormList",n,app.synchronize.setLocalInspectionFormListSuccess,app.synchronize.syncFailedPostUpload)},app.synchronize.setLocalInspectionFormListSuccess=function(){Wndsr.info("Success setting local InspectionForm list"),Wndsr.info("Begin removing InspectionForms"),app.synchronize.removeLocalInspectionForms()},app.synchronize.removeLocalInspectionForms=function(){if(app.synchronize.inspectionFormsToRemove.length>0){var n=app.synchronize.inspectionFormsToRemove.pop();Wndsr.info("Removing InspectionForm id = "+n),app.deleteWebSql(n,app.synchronize.removeLocalInspectionForms,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish removing InspectionForms"),Wndsr.info("Begin adding InspectionForms"),app.synchronize.addLocalInspectionForms()},app.synchronize.addLocalInspectionForms=function(){if(app.synchronize.inspectionFormsToAdd.length>0){var n=app.synchronize.inspectionFormsToAdd.pop();Wndsr.info("Requesting InspectionForm id = "+n),app.post(app.vroot()+"Synchronize/GetInspectionForm/",{id:n},app.synchronize.getServerInspectionFormSuccess,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish adding InspectionForm"),$.blockUI({message:"<h1>Synchronizing Inspection Form Media<\/h1>"}),Wndsr.info("Getting server InspectionFormMedia list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetInspectionFormMediaList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:app.synchronize.getServerInspectionFormMediaListSuccess,headers:{"cache-control":"no-cache"},error:app.synchronize.syncFailedPostUpload})},app.synchronize.getServerInspectionFormSuccess=function(n){if(!n){app.synchronize.syncFailedPostUpload();return}Wndsr.info("Request InspectionForm success"),app.setWebSql(n.id,n,app.synchronize.addLocalInspectionForms,app.synchronize.syncFailedPostUpload)},app.synchronize.getServerInspectionFormMediaListSuccess=function(n){var r,f,u;if(!n){app.synchronize.syncFailedPostUpload();return}for(Wndsr.info("Request server inspectionFormMedia list Success"),Wndsr.info("Begin finding InspectionFormMedias to remove"),u=0;u<app.synchronize.inspectionFormMediaList.length;u++){for(f=!1,r=0;r<n.length;r++)if(app.synchronize.inspectionFormMediaList[u].id===n[r].id){f=!0;break}f||app.synchronize.inspectionFormMediasToRemove.push(app.synchronize.inspectionFormMediaList[u])}for(Wndsr.info("Finish finding inspectionFormMedias to remove, count = "+app.synchronize.inspectionFormMediasToRemove.length),Wndsr.info("Begin finding inspectionFormMedias to add"),r=0;r<n.length;r++){for(f=!1,u=0;u<app.synchronize.inspectionFormMediaList.length;u++)if(n[r].id===app.synchronize.inspectionFormMediaList[u].id&&n[r].changedOn===app.synchronize.inspectionFormMediaList[u].changedOn){f=!0;break}f||app.synchronize.inspectionFormMediasToAdd.push(n[r].id)}Wndsr.info("Finish finding inspectionFormMedias to add, count = "+app.synchronize.inspectionFormMediasToAdd.length),Wndsr.info("Setting local InspectionFormMedia list"),app.setWebSql("inspectionFormMediaList",n,app.synchronize.setLocalInspectionFormMediaListSuccess,app.synchronize.syncFailedPostUpload)},app.synchronize.setLocalInspectionFormMediaListSuccess=function(){Wndsr.info("Success setting local InspectionFormMedia list"),Wndsr.info("Begin removing InspectionFormMedias"),app.synchronize.removeLocalInspectionFormMedias()},app.synchronize.removeLocalInspectionFormMedias=function(){if(app.synchronize.inspectionFormMediasToRemove.length>0){var n=app.synchronize.inspectionFormMediasToRemove.pop();Wndsr.info("Removing InspectionFormMedia id = "+n.id),app.deleteWebSql(n,app.synchronize.removeLocalInspectionFormMedias,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish removing InspectionFormMedias"),Wndsr.info("Begin adding InspectionFormMedias"),app.synchronize.addLocalInspectionFormMedias()},app.synchronize.addLocalInspectionFormMedias=function(){if(app.synchronize.inspectionFormMediasToAdd.length>0){var n=app.synchronize.inspectionFormMediasToAdd.pop();Wndsr.info("Requesting InspectionFormMedia id = "+n),app.post(app.vroot()+"Synchronize/GetInspectionFormMediaSync/",{id:n},app.synchronize.getServerInspectionFormMediaSuccess,app.synchronize.syncFailedPostUpload)}else Wndsr.info("Finish adding InspectionFormMedia"),$.blockUI({message:"<h1>Checking for any synchronization conflicts<\/h1>"}),Wndsr.info("Getting server Conflict list"),$.ajax({type:"POST",url:app.vroot()+"Synchronize/GetConflictList/"+app.principal.id,contentType:"application/json; charset=utf-8",success:app.synchronize.getServerConflictListSuccess,headers:{"cache-control":"no-cache"},error:app.synchronize.syncFailedPostUpload})},app.synchronize.getServerInspectionFormMediaSuccess=function(n){if(!n){app.synchronize.syncFailedPostUpload();return}Wndsr.info("Request InspectionFormMedia success"),app.setWebSql(n.id,n,app.synchronize.addLocalInspectionFormMedias,app.synchronize.syncFailedPostUpload)},app.synchronize.getServerConflictListSuccess=function(n){if(!n){app.synchronize.syncFailedPostUpload();return}Wndsr.info("Request server conflict list Success"),Wndsr.info("Setting local Conflict list"),app.setWebSql("conflictList",n,app.synchronize.setLocalConflictListSuccess,app.synchronize.syncFailedPostUpload)},app.synchronize.setLocalConflictListSuccess=function(){Wndsr.info("Success setting local Conflict list"),Wndsr.info("Sync Complete");var n=moment();Wndsr.setLocalStorage("lastSyncTime",n),Wndsr.setLocalStorage("SyncKey",null),app.persist.setItem("SYNC_SESSION",null),app.persist.setItem("SYNCSTATE",null),app.synchronize.finishSync()},app.synchronize.checkSync=function(){app.isSyncing||app.isOnline&&(Wndsr.info("Looking for dirty inspections"),app.persist.getDirtyInspections(function(n){if(n.length>0)Wndsr.info("Synchronization Needed"),$("html").trigger("synchronizeNeeded");else{Wndsr.info("No dirty inspectionsfound");var t=parseFloat($("body").data("syncrhonize-pull-frequency"));app.persist.getKeyValue("LOCALLASTSYNCTIME",function(n){if(n===null)Wndsr.info("Pull Frequency: "+t+" minutes"),Wndsr.info("Last Synchronize Time: Never"),$("html").trigger("synchronizeNeeded");else{var u=moment(),i=moment(n._d),r=u.diff(i,"minutes",!0);Wndsr.info("Pull Frequency: "+t+" minutes"),Wndsr.info("Last Synchronize Time: "+i.format("M/D/YYYY h:mm:ss a")),Wndsr.info("Time Difference: "+r+" minutes"),r>t?(Wndsr.info("Synchronization Needed"),$("html").trigger("synchronizeNeeded")):Wndsr.info("No Synchronization Needed")}},app.synchronize.syncFailed)}},app.synchronize.syncFailed))}}(),function(){if($("#Content").data("currentView")==="Synchronize/SyncConflict"){var t=null,u=[],n=[],r=function(){var n=Wndsr.getUrlParam("inspectionId");n==null?app.getConflictList(function(n){if((n===undefined||n===null)&&(n=[]),n.length>0){var r={syncConflictForms:n},i=t(r);$("#InspectionFormConflictsTables").html(i)}else window.location=app.vroot()+"Inspection"},function(){alert("Failed getting synchronization conflicts")}):app.getConflictListInspection(n,function(i){if((i===undefined||i===null)&&(i=[]),i.length>0){var u={syncConflictForms:i},r=t(u);$("#InspectionFormConflictsTables").html(r)}else window.location=n!==null?app.vroot()+"Inspection":app.vroot()+"Inspection"},function(){alert("Failed getting synchronization conflicts")})},i=function(){if(n.length>0){var t=n.pop();app.getInspectionForm(t,function(n){n.isActive=!1,n.isDirty=!0,app.updateInspectionForm(n,function(){i()},function(){alert("Failed fixing synchronization conflicts")})},function(){alert("Failed fixing synchronization conflicts")})}else app.clearConflictList(function(){window.location=app.vroot()+"Inspection"},function(){alert("Failed fixing synchronization conflicts")})};$(function(){app.applyTheme($("#Content")),$("#ResolveConflictsButton").button(),t=Handlebars.compile($("#inspection-form-conflict-template").html());$("html").on("synchronizeComplete",r);r();$("html").on("click",".js-conflict-row",function(){$(this).parents("table").find("input[type=radio]").attr("checked",!1),$(this).find("input[type=radio]").attr("checked",!0)});$("#ResolveConflictsButton").on("click",function(){for(var u=$("table"),r,t=0;t<u.length;t++)if($(u[t]).find("input:checked").length===0){alert("Please select a version for each form");return}for(r=$(".syncConflict input:radio:not(:checked)"),t=0;t<r.length;t++)n.push($(r[t]).data("inspection-form-id"));if(n.length!==0){$.blockUI(),i();return}})})}}(),function(){$("#Content").data("currentView")==="FormVersion/Index"&&$(function(){var t,n;app.applyTheme($("#Content")),$("#FormsButton").addClass("ui-pressed"),t=Wndsr.getUrlParam("inspectionId"),app.loadForms(t),$("#FormNavigation").show(),$("#Container").css("padding-top",$("#FormsHeader").outerHeight()),app.principal.isSensitiveEdit?$("#CompleteInspection").parent().show():$("#CompleteInspection").parent().hide();$("#CurrentForms").on("click","li",function(){var i=$(this).data("formversion-id"),t=$(this).data("formsection-id"),n=$(this).data("inspection-id");return window.location=app.vroot()+"InspectionForm?inspectionId="+n+"&formVersionId="+i+"&formSectionId="+t,!1});$("#CurrentForms").on("click",".js-repeating-row",function(){var i=$($(this).parents("li")[0]).data("formversion-id"),r=$($(this).parents("li")[0]).data("formsection-id"),n=$($(this).parents("li")[0]).data("inspection-id"),t=$(this).data("index");return window.location=app.vroot()+"InspectionForm?inspectionId="+n+"&formVersionId="+i+"&formSectionId="+r+"&sectionIndex="+t,!1});n=Wndsr.getUrlParam("projectId"),n!==null&&n!==undefined&&n!==""&&$("#BackProjectButton").show().click(function(){window.location=app.vroot()+"Project/"+n+"/Edit"}),$("#FormSectionList").focus()})}(),function(){var t=!1,i=!1,n=null;$("#Content").data("currentView")==="FormVersion/Edit"&&(app.setupFormulaBuilder=function(t,i){return $(t).removeClass("invalid-formula"),System.import("global-adapter-js").then(function(n){return n.default.compile=function(n){var t=$(n)[0];return function(){return t}},System.import("formula-editor-js")}).then(function(r){var e=i?i.validationEnabled:!0,u,f;if(t&&!t.tagName){if($(t).size()==0)return;t=t[0]}return u=[],i&&i.values&&Object.keys(i.values).forEach(function(n){var f='Value of control "'+i.values[n].control.label+'" from "'+i.values[n].sectionName+'" section',t=new r.TemplateHint(n,f);u.push(t)}),f={buttonContainer:t.nextElementSibling.firstElementChild,templateHints:u,templateParser:function(n,t,r){var e,u;if(n=n.replace(/`/g,""),e="`"+n+"`",i&&i.values&&Object.keys(i.values).indexOf(n)==-1)return new Error("Invalid Tag: "+n);if(t&&r!=null){var o=undefined,f=t[r+1],s=i.values[n].control;if(f&&f.type==="StaticIndexer"&&f.value=="."&&(u=t[r+2],u))if(u.type==="Identifier")o=u.value;else return new Error("Invalid Tag: "+e+f.value+u.value)}},onChange:function(n,i){if(n.errors&&n.errors.length){var r=n.errors.length==1?n.errors[0].message:"<ul>"+n.errors.map(function(n){return"<li>"+n.message+"<\/li>"}).join("")+"<\/ul>";$.validator.addMethod("invalid-formula",function(){return!n.errors||!n.errors.length},r),$(t).removeClass("invalid-formula").addClass("invalid-formula")}$(t).val(i),t.form&&$(t).valid()}},n=new r.FormulaEditor(t,f)})},$(function(){var e,f,r,o,u;$("#DoneButton").button(),$("#PreviewButton").button(),$("#PublishButton").button(),$("#ExportButton").button(),$("#SectionNewButton").button({icons:{primary:"ui-icon-admin-add"}}).button("disable"),$("#SectionEditButton").button({icons:{primary:"ui-icon-admin-edit"}}).button("disable"),$("#SectionDeleteButton").button({icons:{primary:"ui-icon-admin-delete"}}).button("disable"),$("#SectionUpButton").button({icons:{primary:"ui-icon-admin-up"}}).button("disable"),$("#SectionDownButton").button({icons:{primary:"ui-icon-admin-down"}}).button("disable"),$("#QuestionNewButton").button({icons:{primary:"ui-icon-admin-add"}}).button("disable"),$("#QuestionEditButton").button({icons:{primary:"ui-icon-admin-edit"}}).button("disable"),$("#QuestionDeleteButton").button({icons:{primary:"ui-icon-admin-delete"}}).button("disable"),$("#CopyLastQuestionButton").button({icons:{primary:"ui-icon-admin-copy"}}).button("disable"),$("#IsEditable").val()==="True"&&(t=!0,$("#SectionNewButton").button("enable"));$("#ExportButton").on("click",function(){window.location=app.vroot()+"FormVersion/Export/"+$("#FormVersionIdHidden").val()});$("#NewSectionDialog").dialog({title:"New Section",autoOpen:!1,modal:!0,resizable:!1,width:440,minWidth:440,buttons:{OK:function(){var r=$.trim($("#SectionName").val()),i=$("#RepeatingSection").is(":checked"),n=$("#RepeatingCount").val(),u=$("#VisibilityFormula").val(),f=$("#Tag").val(),t;if(r===""){alert("Section Name cannot be empty");return}if(i&&n.length>0&&!Wndsr.isNumericInteger(n)){alert("Number of repeating sections allowed must be a whole number or blank.");return}i&&n.length===0&&(n="0"),$.blockUI(),t=$("#FormVersionIdHidden").val(),app.post(app.vroot()+"FormVersion/NewSection/"+t,{id:t,sectionName:r,repeatingSections:i,repeatingCount:n,visibilityFormula:u,tag:f},function(n){window.location=app.vroot()+"FormVersion/Edit/"+n.formVersionId+"?selectedFormSection="+n.formSectionId},function(){alert("Save Failed"),$("#NewSectionDialog").dialog("close"),$.unblockUI()})},Cancel:function(){$("#NewSectionDialog").dialog("close")}}}),$("#EditSectionDialog").dialog({title:"Edit Section",autoOpen:!1,modal:!0,resizable:!1,width:440,minWidth:440,buttons:{OK:function(){var e=$.trim($("#SectionEditName").val()),f=$("#RepeatingEditSection").is(":checked"),i=$("#RepeatingEditCount").val(),h=$("#EditVisibilityFormula").val(),s=$("#EditTag").val(),r,t,u,o;if(e===""){alert("Section Name cannot be empty");return}if(n!==null&&n.errors!==null&&n.errors!==undefined&&n.errors.length>0){for(r="There are errors in the formula\n",t=0;t<n.errors.length;t++)n.errors[t].message?r+=n.errors[t].message+"\n":n.errors[t].description&&(r+=n.errors[t].description+"\n");alert(r);return}if(f&&i.length>0&&!Wndsr.isNumericInteger(i)){alert("Number of repeating sections allowed must be a whole number or blank.");return}f&&i.length===0&&(i="0"),$.blockUI(),u=$("#FormVersionIdHidden").val(),o=$("option:selected","#FormSectionList").data("formsection-id"),app.post(app.vroot()+"FormVersion/EditSection/"+u,{id:u,sectionId:o,sectionName:e,repeatingSections:f,repeatingCount:i,visibilityFormula:h,tag:s},function(n){window.location=app.vroot()+"FormVersion/Edit/"+n.formVersionId+"?selectedFormSection="+n.formSectionId},function(){alert("Save Failed"),$("#EditSectionDialog").dialog("close"),$.unblockUI()})},Cancel:function(){$("#EditSectionDialog").dialog("close")}}}),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#DoneButton").on("click",function(){window.location=app.vroot()+"Form/"});$("#PreviewButton").on("click",function(){return $("#FormSectionList").children().length===0?(alert("At least one section is required to preview"),!1):(window.open(app.vroot()+"InspectionForm?formVersionId="+$("#FormVersionIdHidden").val()+"&formSectionId="+$("#FormSectionList").children(":first").data("formsectionId"),"_blank"),!1)});$("#SaveButton").on("click",function(){});$("#FormSectionList").on("change",function(){var t,i,n;for($("#QuestionsLabel").text("Questions in Section: "+$("option:selected",this).text()),$("#FormControls").html(""),t=$("option[data-formsection-id="+$("option:selected",this).data("formsection-id")+"]","#FormControlsHidden"),i="",n=0;n<t.length;n++)i+=$("<div>").append($(t[n]).clone()).html();$("#FormControls").html(i)});$("#SectionNewButton").on("click",function(){$("#SectionName").val(""),$("#RepeatingSection").attr("checked",!1),$("#RepeatingCount").val(""),$("#NewSectionDialog").dialog("open")});$("#RepeatingSection").on("change",function(){$("#RepeatingSection").is(":checked")?$("#RepeatingCount").removeAttr("disabled"):($("#RepeatingCount").attr("disabled","disabled"),$("#RepeatingCount").val(""))});$("#RepeatingEditSection").on("change",function(){$("#RepeatingEditSection").is(":checked")?$("#RepeatingEditCount").removeAttr("disabled"):($("#RepeatingEditCount").attr("disabled","disabled"),$("#RepeatingEditCount").val(""))});$("#SectionEditButton").on("click",function(){var u=$("option:selected","#FormSectionList").data("section-title"),r=$("option:selected","#FormSectionList").data("repeating-count"),f=$("option:selected","#FormSectionList").data("visibility-formula"),e=$("option:selected","#FormSectionList").data("tag"),t,n;$("#SectionEditName").val(u),$("#EditVisibilityFormula").val(f),$("#EditTag").val(e),r!==""&&r!==undefined?($("#RepeatingEditSection").attr("checked","checked"),$("#RepeatingEditCount").removeAttr("disabled"),r===0?$("#RepeatingEditCount").val(""):$("#RepeatingEditCount").val(r)):($("#RepeatingEditSection").attr("checked",!1),$("#RepeatingEditCount").attr("disabled","disabled"),$("#RepeatingEditCount").val("")),i?($(".CodeMirror").remove(),$(".visButtons").empty(),t=$("#FormVersionIdHidden").val(),n={},n.values={},app.post(app.vroot()+"FormVersion/GetAllTags/"+t,{id:t},function(t){for(var r=0;r<t.items.length;r++)n.values[t.items[r].tag]={sectionName:t.items[r].sectionName,control:t.items[r].control};app.setupFormulaBuilder($("#EditVisibilityFormula"),n),i=!0,$("#EditSectionDialog").dialog("open")},function(){alert("Failed getting tags")})):(t=$("#FormVersionIdHidden").val(),n={},n.values={},app.post(app.vroot()+"FormVersion/GetAllTags/"+t,{id:t},function(t){for(var r=0;r<t.items.length;r++)n.values[t.items[r].tag]={sectionName:t.items[r].sectionName,control:t.items[r].control};app.setupFormulaBuilder($("#EditVisibilityFormula"),n),i=!0,$("#EditSectionDialog").dialog("open")},function(){alert("Failed getting tags")}))});$("#SectionDeleteButton").on("click",function(){if(confirm("Are you sure you want to delete this section?")){$.blockUI();var n=$("#FormVersionIdHidden").val(),t=$("option:selected","#FormSectionList").data("formsection-id");app.post(app.vroot()+"FormVersion/DeleteSection/"+n,{id:n,sectionId:t},function(n){window.location=app.vroot()+"FormVersion/Edit/"+n},function(){alert("Save Failed"),$.unblockUI()})}});$("#SectionUpButton").on("click",function(){$.blockUI();var n=$("#FormVersionIdHidden").val(),t=$("option:selected","#FormSectionList").data("formsection-id");app.post(app.vroot()+"FormVersion/MoveUpSection/"+n,{id:n,sectionId:t},function(n){window.location=app.vroot()+"FormVersion/Edit/"+n.formVersionId+"?selectedFormSection="+n.formSectionId},function(){alert("Save Failed"),$("#EditSectionDialog").dialog("close"),$.unblockUI()})});$("#SectionDownButton").on("click",function(){$.blockUI();var n=$("#FormVersionIdHidden").val(),t=$("option:selected","#FormSectionList").data("formsection-id");app.post(app.vroot()+"FormVersion/MoveDownSection/"+n,{id:n,sectionId:t},function(n){window.location=app.vroot()+"FormVersion/Edit/"+n.formVersionId+"?selectedFormSection="+n.formSectionId},function(){alert("Save Failed"),$("#EditSectionDialog").dialog("close"),$.unblockUI()})});$("#QuestionNewButton").on("click",function(){$.blockUI();var n=$("option:selected","#FormSectionList").data("formsection-id");window.location=app.vroot()+"FormControl/NewFormControl/"+n});$("#CopyLastQuestionButton").on("click",function(){$.blockUI();var n=$("option:selected","#FormSectionList").data("formsection-id");window.location=app.vroot()+"FormControl/CopyLastQuestion/"+n});$("#QuestionEditButton").on("click",function(){$.blockUI();var n=$("option:selected","#FormControls").data("formcontrol-id");window.location=app.vroot()+"FormControl/EditFormControl/"+n});$("#QuestionDeleteButton").on("click",function(){if(confirm("Are you sure you want to delete this question?")){$.blockUI();var n=$("option:selected","#FormControls").data("formcontrol-id");app.post(app.vroot()+"FormControl/DeleteQuestion/"+n,{id:n},function(n){window.location=app.vroot()+"FormVersion/Edit/"+n.formVersionId+"?selectedFormSection="+n.formSectionId},function(){alert("Save Failed"),$.unblockUI()})}});$("#FormSectionList").on("change",function(){f()});e=$("#FormControls").children("option").length,$("#CopyLastQuestionButton").button("disable"),e>0&&$("#CopyLastQuestionButton").button("enable"),f=function(){var r,i,n,u;if(t){$("#SectionEditButton").button("disable"),$("#SectionDeleteButton").button("disable"),$("#SectionUpButton").button("disable"),$("#SectionDownButton").button("disable"),$("#QuestionNewButton").button("disable"),$("#QuestionEditButton").button("disable"),$("#QuestionDeleteButton").button("disable");var e=$("option:selected","#FormSectionList"),f=$("#FormSectionList").prop("selectedIndex"),o=$("#FormSectionList").children("option").length;e!==undefined&&e!==null&&($("#SectionEditButton").button("enable"),$("#SectionDeleteButton").button("enable"),$("#QuestionNewButton").button("enable")),f>0&&$("#SectionUpButton").button("enable"),f<o-1&&$("#SectionDownButton").button("enable")}for($("#QuestionsLabel").text("Questions in Section: "+$("option:selected","#FormSectionList").text()),$("#FormControls").html(""),r=$("option[data-formsection-id="+$("option:selected","#FormSectionList").data("formsection-id")+"]","#FormControlsHidden"),i="",n=0;n<r.length;n++)i+=$("<div>").append($(r[n]).clone()).html();$("#FormControls").html(i),u=$("#FormControls").children("option").length,$("#CopyLastQuestionButton").button("disable"),u>0&&$("#CopyLastQuestionButton").button("enable")};$("#FormControls").on("change",function(){if(t){$("#QuestionEditButton").button("disable"),$("#QuestionDeleteButton").button("disable");var n=$("option:selected","#FormControls");n!==undefined&&n!==null&&($("#QuestionEditButton").button("enable"),$("#QuestionDeleteButton").button("enable"))}});$("#PublishButton").on("click",function(){if(confirm("Are you sure you want to publish this version?")){$.blockUI();var n=$("#FormVersionIdHidden").val();app.post(app.vroot()+"FormVersion/Publish/"+n,{id:n},function(){window.location=app.vroot()+"Form/"},function(){alert("Save Failed"),$.unblockUI()})}});r=Wndsr.getUrlParam("selectedFormSection"),r!==undefined&&($("option[data-formsection-id="+r+"]","#FormSectionList").attr("selected",!0),f()),o=Wndsr.getUrlParam("selectedFormControl"),r!==undefined&&($("option[data-formcontrol-id="+o+"]","#FormControls").attr("selected",!0),t&&($("#QuestionEditButton").button("disable"),$("#QuestionDeleteButton").button("disable"),u=$("option:selected","#FormControls"),u!==undefined&&u!==null&&($("#QuestionEditButton").button("enable"),$("#QuestionDeleteButton").button("enable")))),$("#FormSectionList").focus()}))}(),function(){if($("#Content").data("currentView")==="Inspection/Index"){var w=null,u=null,h=null,s=null,ut=[],o=[],c=[],e=[],r=[],n,t,b=0,tt=0,a=!1,l=[],f=function(){$.blockUI({message:"<h1>Please Wait...<\/h1>"}),app.persist.getPrincipals(function(n){var f,t;for(Wndsr.info("Request principals Success"),o=n===null?[]:n,f="<option><\/option>",c=[],t=0;t<o.length;t++)f+='<option value="'+o[t].id+'">'+o[t].displayName+"<\/option>",o[t].isSensitiveEdit&&c.push(o[t]);for($("#InspectorSelect").html(f),f="<option value=''><\/option>",t=0;t<c.length;t++)f+='<option value="'+c[t].id+'">'+c[t].displayName+"<\/option>";$("#ReviewerSelect").html(f),app.persist.getProjects(function(n){var f,t;for(e=n===null?[]:n,e.sort(function(n,t){return n.projectTitle.localeCompare(t.projectTitle)}),f="<option><\/option>",t=0;t<e.length;t++)f+='<option value="'+e[t].id+'">'+e[t].projectTitle+"<\/option>";$("#ProjectSelect").html(f),app.persist.getInspections(function(n){n?(u=n,u.sort(function(n,t){var r=n.scheduledStart,i=t.scheduledStart;return n.actualStart&&(r=n.actualStart),t.actualStart&&(i=t.actualStart),moment(i).valueOf()-moment(r).valueOf()})):u=[],app.persist.getSites(function(n){h=n?n:[],app.persist.getSiteAddresses(function(n){s=n?n:[],app.persist.getInspectionTypes(function(n){var i,t;for(r=n?n:[],i="<option><\/option>",t=0;t<r.length;t++)i+='<option value="'+r[t].id+'">'+r[t].name+"<\/option>";$("#InspectionTypeSelect").html(i),l=[],u.map(function(n){var t=$.extend({},n),i=h.find(function(t){return n.siteId===t.id}),f=s.find(function(t){return n.siteId===t.siteId}),u=r.find(function(t){return n.inspectionTypeId===t.id});i&&(t.siteKey=i.siteKey,t.siteName=i.siteName),f&&(t.siteCity=f.city),u&&(t.type=u.code),l.push(t)}),p()})})})},i)},i)},i)},i=function(n){n.statusText==="Retry with authentication"?alert("Your session has expired, please log in again."):alert("Failed getting inspection list"),$.unblockUI(),Wndsr.error("GetInspectionList Failed")},p=function(){var i,t,n;$("#InspectionsTable").find("tbody").html(""),i={inspections:l},t=w(i),$("#InspectionsTable").find("tbody").html(t),a&&(n=localStorage.getItem("stickyFilter"),$("#MyInspectionsFilter").val(n),$("#MyInspectionsFilter").keyup()),$.unblockUI()};const nt=function(n){var i=n.hasMissingAnswers,t=n.inspection;return i?(alert("There are missing required questions on this inspection, cannot complete."),$.unblockUI()):(t.completed=moment(new Date).format(),t.isInProgress=!1,t.isComplete=!0,t.isDirty=!0,app.persist.putInspection(t,function(){app.persist.syncChanges(function(){window.location=app.vroot()+"Inspection/"})})),Promise.resolve()};var it=function(n){if(!n){showMapFailed();return}Wndsr.info("getInspectionForCompleteSuccess - has inspection"),appPersistInspectionHasMissingAnswers(n).then(nt)},rt=function(n){if(!n){showMapFailed();return}Wndsr.info("Request inspection Success - incomplete"),n.completed=null,n.isInProgress=!0,n.isDirty=!0,app.persist.putInspection(n,function(){app.persist.syncChanges(v,y)})},k=function(n){if(!n){showMapFailed();return}Wndsr.info("Request inspection Success - complete"),n.hasMissingAnswer?($("#RequiredAnswerMessage").dialog("open"),$.unblockUI()):($.blockUI(),n.reviewRequestDate=moment(new Date).format(),n.isDirty=!0,app.persist.putInspection(n,function(){app.persist.syncChanges(v,y)}))},ft=function(){alert("Failed getting inspection to complete"),$.unblockUI(),Wndsr.error("GetInspection Failed - complete")},v=function(n){Wndsr.info("Update inspection Success"),n!==undefined&&n.message!==null&&n.message!==undefined&&alert(n.message),app.isMobile()&&app.synchronize.checkSync(),f()},y=function(){alert("Failed updating inspection"),$.unblockUI(),Wndsr.error("UpdateInspection Failed")},g=function(){app.isMobile()&&app.isOnline&&app.synchronize.checkSync(),f()},d=function(n){var t=n;return t===""?!0:Wndsr.isValidDate(t)?!0:(alert(t+" is an invalid date"),!1)};$(function(){var v=$("#ServiceWorkerRoot").val(),nt,ut,ft,y,c,l,o;"serviceWorker"in navigator?window.addEventListener("load",function(){navigator.serviceWorker.register(v+"/serviceWorker.js",{scope:v+"/"}).then(function(n){console.log("Service Worker Registered with scope: ",n.scope)},function(n){console.log("Service Worker Registration Failed: ",n)})}):console.log("Service workers are not supported."),app.applyTheme($("#Content")),($("#StickyFilter").val()==="true"||$("#StickyFilter").val()==="True")&&(a=!0),b=parseInt($("#MyInspectionsBackDays").val()),tt=parseInt($("#MyInspectionsForwardDays").val());$("#AddSiteDialog").on("blur",".js-date-answer",function(){return d($.trim($(this).val()))?!0:($(this).focus(),$(this).val(""),!1)});app.principal!==null?(app.principal.isSensitiveEdit?$("#MarkInspectionComplete").parent().show():$("#MarkInspectionComplete").parent().hide(),app.principal!==undefined&&app.principal!==null&&app.principal.isAdmin?$("#RemoveInspection").parent().show():$("#RequireAdminForRemovingInspections").val()==="True"&&$("#RemoveInspection").parent().hide()):$("#MarkInspectionComplete").parent().hide();$("html").on("logonComplete",function(){app.principal.isSensitiveEdit?$("#MarkInspectionComplete").parent().show():($("#MarkInspectionComplete").parent().hide(),o.datepicker("disable"),$(".js-inspection-review-date-answer").prop("disabled","disabled"),$("#ReviewerSelect").prop("disabled","disabled")),app.principal!==undefined&&app.principal!==null&&app.principal.isAdmin?$("#RemoveInspection").parent().show():$("#RequireAdminForRemovingInspections").val()==="True"&&$("#RemoveInspection").parent().hide()});$("#InspectionConflicts").dialog({autoOpen:!1,modal:!0,resizable:!1,height:350,minHeight:350,width:500,minWidth:500,buttons:{OK:function(){}}}),$("#RequiredAnswerMessage").dialog({title:"Cannot Complete Inspection",autoOpen:!1,modal:!0,resizable:!1,buttons:{OK:function(){$(this).dialog("close")}}}),$("#HomeButton").addClass("ui-active");$("#AddInspection").on("click",function(){window.location=app.isOnline?app.vroot()+"Site?mode=1":app.vroot()+"Site?mode=0"});$("#AddUnassignedInspection").on("click",function(){app.isOnline?window.location=app.vroot()+"Inspection/UnassignedInspections":alert("You must be online to view unassigned inspections.")});$("html").on("synchronizeComplete",f);$("html").on("logonComplete",function(){f(),app.isMobile()&&app.synchronize.checkSync()});$("html").on("applicationOnline",function(){app.principal!==null&&(app.isOnline&&app.isMobile()&&(app.synchronize.checkSync(),$("#SiteKeyTextBox").attr("disabled",!0)),$("#AddUnassignedInspection").show())});$("html").on("applicationOffline",function(){$("#AddUnassignedInspection").hide(),$("#SiteKeyTextBox").removeAttr("disabled")});$("#InspectionsTable").on("click",".conflictedInspection",function(){if(!app.isOnline)return alert("You must be online to resolve conflicts."),!1});$("html").on("synchronizeNeeded",app.synchronize.synchronize);$("html").on("synchronizeComplete",function(){p()});$("#InspectionActions").menu(),$(".ui-corner-all",".ui-menu-item").attr("tabindex","0");$("body").on("keydown",function(n){n.keyCode==27&&$("#InspectionActions").hide()});$("#InspectionsTable").on("keypress",".js-options-button",function(n){if(n.keyCode==13||n.keyCode==32){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#InspectionActions").hide();else{app.isOnline?($(".generateReport").show(),$(".generatePDFOption").show(),$(".downlaodImages").show()):($(".generateReport").hide(),$(".generatePDFOption").hide(),$(".downlaodImages").hide());var i=$(this).data("inspection-id"),t=$(this).data("is-complete");t==="True"&&app.principal.isSensitiveEdit?($("#MarkInspectionUnComplete").parent().show(),$("#MarkInspectionComplete").parent().hide()):$("#MarkInspectionUnComplete").parent().hide(),t==="False"&&app.principal.isSensitiveEdit?($("#MarkInspectionUnComplete").parent().hide(),$("#MarkInspectionComplete").parent().show()):$("#MarkInspectionComplete").parent().hide(),$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#InspectionActions").css("top",$(this).offset().top+$(this).height()),$("#InspectionActions").data("inspection-id",i),$("#InspectionActions").show();$("html").on("click",function(){$(this).is("#InspectionActions")||$("#InspectionActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),$("html").off("click"))});$("#InspectionDetails").focus()}return!1}});$("#InspectionsTable").on("click",".js-options-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#InspectionActions").hide();else{app.isOnline?($(".generateReport").show(),$(".generatePDFOption").show(),$(".downlaodImages").show()):($(".generateReport").hide(),$(".generatePDFOption").hide(),$(".downlaodImages").hide());var t=$(this).data("inspection-id"),n=$(this).data("is-complete");n==="True"&&app.principal.isSensitiveEdit?($("#MarkInspectionUnComplete").parent().show(),$("#MarkInspectionComplete").parent().hide()):$("#MarkInspectionUnComplete").parent().hide(),n==="False"&&app.principal.isSensitiveEdit?($("#MarkInspectionUnComplete").parent().hide(),$("#MarkInspectionComplete").parent().show()):$("#MarkInspectionComplete").parent().hide(),$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#InspectionActions").css("top",$(this).offset().top+$(this).height()),$("#InspectionActions").data("inspection-id",t),$("#InspectionActions").show();$("html").on("click",function(){$(this).is("#InspectionActions")||$("#InspectionActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),$("html").off("click"))})}return!1});$("#InspectionHistory").on("click",function(){var n=$("#InspectionActions").data("inspection-id");return $.blockUI({message:"<h1>Inspection History is under construction.<\/h1>"}),setTimeout(function(){$.unblockUI()},1e3),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#MapSiteAddress").on("click",function(){var i=$("#InspectionActions").data("inspection-id"),r=u.find(function(n){return n.id===i}),n=s.find(function(n){return n.siteId===r.siteId}),t="";return n.addressLineOne&&(t+=n.addressLineOne.replace(" ","+")),n.city&&(t+="+"+n.city.replace(" ","+")),n.state&&(t+=","+n.state),n.zipCode&&(t+="+"+n.zipCode),window.open("http://maps.google.com/maps?daddr="+t+"&t=h"),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#RequestInspectionReview").on("click",function(){var t=$("#InspectionActions").data("inspection-id"),n=u.find(function(n){return n.id===t});if(n.isConflict){alert("This inspection has a conflict, you must resolve the conflict and synchronize before requestion a review the inspection");return}return confirm("Are you sure you want to request a review on this inspection?")&&k(n),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#MarkInspectionComplete").on("click",function(){var i=$("#InspectionActions").data("inspection-id"),t=u.find(function(n){return n.id===i}),n=h.find(function(n){return n.id===t.siteId});if($("#RequireSiteKeyForCompleteInspeciton").val()==="True"&&(n.siteKey===null||n.siteKey===undefined||n.siteKey==="")){alert($("#SiteKeyLabel").val()+" is required to complete an inspection");return}if(t.isConflict){alert("This inspection has a conflict, you must resolve the conflict and synchronize before completing the inspection");return}return confirm("Mark Inspection as complete?")&&($.blockUI({message:"<h1>Please Wait...<\/h1>"}),it(t)),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#MarkInspectionUnComplete").on("click",function(){var t=$("#InspectionActions").data("inspection-id"),n;return confirm("Mark Inspection as incomplete?")&&($.blockUI({message:"<h1>Please Wait...<\/h1>"}),n=u.find(function(n){return n.id===t}),rt(n)),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#RemoveInspection").on("click",function(){var t,n;return confirm("Permanently delete all the forms and data for this inspection?")&&(t=$("#InspectionActions").data("inspection-id"),$.blockUI(),n=u.find(function(n){return n.id===t}),n.isDirty=!0,n.isDeleted=!0,app.persist.putInspection(n,function(){app.persist.syncChanges(g,i)},i)),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#ReportGroup").on("change",function(){var f="<option/>",u=$(this).find(":selected").data("output-format"),t,n,r,i;if(u!=undefined)for(t=u.split("|"),n=0;n<t.length;n++)r=t[n].split(";")[0],i=t[n].split(";")[1],f+="<option value='"+i+"'>"+r+"<\/option>";$("#OutputFormat").html(f)});$(".generateReport").on("click",function(){var i=(new Date).getTimezoneOffset(),n=$("#InspectionActions").data("inspection-id"),t=$(this).data("reportType");return $.blockUI(),$("#ReportInspectionId").val(n),app.post(app.vroot()+"Report/GetReportGroups/",{id:n},function(n){for(var u="<option value=''/>",f="<option value=''/>",i,r,t=0;t<n.items.length;t++){for(i="",r=0;r<n.items[t].reportGroupReportFormats.length;r++)i.length>0&&(i+="|"),i+=n.items[t].reportGroupReportFormats[r].reportFormat.description+";"+n.items[t].reportGroupReportFormats[r].reportFormat.fileExtension;u+="<option value='"+n.items[t].id+"' data-output-format='"+i+"'>"+n.items[t].name+"<\/option>"}$("#ReportGroup").html(u),$("#OutputFormat").html(f),$("#ReportDialog").dialog("open"),$.unblockUI()},function(){$.unblockUI(),alert("failed")}),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$(".generateBlankReport").on("click",function(){var i=(new Date).getTimezoneOffset(),t=$("#InspectionActions").data("inspection-id"),n=$(this).data("reportType");return window.location.href=app.vroot()+"Report/GetBlankReport?inspectionId="+t+"&curDateOffset="+i+"&reportType="+n,$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#DownloadImages").on("click",function(){var n=$("#InspectionActions").data("inspection-id");return window.location.href=app.vroot()+"Report/GetImages?inspectionId="+n,!1});$("#ShowViolations").on("click",function(){if(app.isOnline){var n=$("#InspectionActions").data("inspection-id");window.location=app.vroot()+"Inspection/ViolationList?inspectionId="+n}else alert("Violations cannot be displayed while offline")});$("#InspectionDetails").on("click",function(){var a=$("#InspectionActions").data("inspection-id"),c,l,o;$.blockUI();var i=u.find(function(n){return n.id===a}),f=h.find(function(n){return i.siteId===n.id}),p=s.find(function(n){return f.id===n.siteId}),v=r.find(function(n){return n.id===i.inspectionTypeId}),y=e.find(function(n){return n.id===i.projectId});for(n=i,t=f,$("#SiteDisplayName").text(f.siteName),$("#SiteKeyLabel").text(f.siteKey),$("#SiteKeyTextBox").val(f.siteKey),$("#InspectorSelect").val(app.principal.id),$("#ProjectSelect").val(i.projectId),$("#InspectionTypeSelect").val(i.inspectionTypeCode),i.project!==null&&i.project!==undefined&&$("#ProjectTitle").text(y.projectTitle),$("#InspectionDescription").val(i.description),$(".js-date-answer").val(moment(i.scheduledStart).format("M/D/YYYY")),i.actualStart!==undefined&&i.actualStart!==null?$(".js-inspection-date-answer").val(moment(i.actualStart).format("M/D/YYYY")):$(".js-inspection-date-answer").val(""),i.reviewRequestDate!==undefined&&i.reviewRequestDate!==null?$(".js-inspection-review-date-answer").val(moment(i.reviewRequestDate).format("M/D/YYYY")):$(".js-inspection-review-date-answer").val(""),i.reviewPrincipalId!==undefined&&i.reviewPrincipal!==null?$("#ReviewerSelect").val(i.reviewPrincipalId):$("#ReviewerSelect").val(""),f.siteKey!==undefined&&f.siteKey!==null&&f.siteKey!==""?($("#SiteKeyLabel").hide(),$("#SiteKeyTextBox").show()):f.siteKey===undefined||f.siteKey===null||f.siteKey===""?($("#SiteKeyLabel").hide(),$("#SiteKeyTextBox").show()):($("#SiteKeyLabel").show(),$("#SiteKeyTextBox").hide()),i.inspectionSource===undefined||i.inspectionSource===null||i.inspectionSource===""?$("#InspectionSource").text($("#ApplicationName").val()):$("#InspectionSource").text(i.inspectionSource),c="",l=!1,o=0;o<r.length;o++)r[o].id===i.inspectionTypeId&&(l=!0),c+="<option value='"+r[o].id+"'>"+r[o].name+"<\/option>";l&&$("#InspectionTypeSelect").html(c),$("#InspectionTypeSelect").val(v.id),app.isOnline?$("#SiteKeyTextBox").removeAttr("disabled"):$("#SiteKeyTextBox").attr("disabled",!0),$("#AddSiteDialog").dialog("open"),$.unblockUI()});w=Handlebars.compile($("#inspection-row-template").html()),app.principal!==null&&f(),nt=parseInt($("body").data("syncrhonize-pull-frequency")),app.isMobile()&&setInterval(function(){app.principal!==null&&app.isOnline&&app.synchronize.checkSync()},nt*6e4),$("#ReportDialog").dialog({title:"Generate Report",autoOpen:!1,modal:!0,resizable:!1,height:240,minHeight:240,width:500,minWidth:500,buttons:{OK:function(){var t=$("#ReportGroup").val(),n=$("#OutputFormat").val(),r=$("#ReportInspectionId").val(),i=(new Date).getTimezoneOffset();if(t===undefined||t===""){alert("Report Group is required");return}if(n===undefined||n===""){alert("Output Format is required");return}window.location.href=app.vroot()+"Report/GetReportTemplate?inspectionId="+r+"&curDateOffset="+i+"&reportTemplateId="+t+"&reportType="+n.toUpperCase(),$("#ReportDialog").dialog("close")},Cancel:function(){$("#ReportDialog").dialog("close")}}}),$("#AddSiteDialog").dialog({title:"Edit Inspection",autoOpen:!1,modal:!0,resizable:!1,height:700,minHeight:700,width:575,minWidth:575,buttons:{OK:function(){var e=$.trim($(".js-date-answer").val()),r=$.trim($(".js-inspection-date-answer").val()),s=$.trim($(".js-inspection-review-date-answer").val()),v=new moment,a="",u,o,l,c,h;if(e.length===0){alert("Inspection Date is required");return}if(!Wndsr.isValidDate(e)){alert(e+" is an invalid date"),$(".js-date-answer").val("");return}if(r.length>0&&!Wndsr.isValidDate(r)){alert(r+" is an invalid date"),$(".js-inspection-date-answer").val("");return}if(s.length>0){if(u=new moment(s),u=u.startOf("day"),o=new moment,o=o.startOf("day"),l=o.add("d",30),u>l){alert("Review Request date must be less than 30 days in the future");return}if(r.length>0){if(c=new moment(r),u<c.startOf("day")){alert("Review Request date must be after the Evaluation Date");return}}else if(h=new moment(e),u<h.startOf("day")){alert("request review date cannot be before the Scheduled Date"),$(".js-inspection-review-date-answer").val("");return}}if(t.siteKey!==null&&t.siteKey!==undefined&&t.siteKey!==""&&$("#SiteKeyTextBox").is(":visible")&&$("#SiteKeyTextBox").val()==="")return alert($("#SiteKeyLabel").val()+" is required"),!1;$.blockUI(),n.scheduledStart=moment(e).format(),n.changedOn=moment(new Date).format(),n.principalId=$("#InspectorSelect").val(),n.projectId=$("#ProjectSelect").val(),$("#ReviewerSelect").val()!==""?n.reviewPrincipalId=$("#ReviewerSelect").val():(n.reviewPrincipalId=null,n.reviewPrincipal=null),n.inspectionTypeId=$("#InspectionTypeSelect").val(),n.actualStart=r.length>0?moment(r).format():null,$("#SiteKeyTextBox").is(":visible")&&t.sityKey!==$("#SiteKeyTextBox").val()&&(a=t.siteKey,t.siteKey=$("#SiteKeyTextBox").val(),t.isDirty=!0),s.length>0?n.reviewRequestDate=moment(s).format():(n.reviewRequestDate=null,n.reviewPrincipal=null),$("#InspectionDescription").is(":visible")&&(n.description=$("#InspectionDescription").val()),n.isDirty=!0,app.isOnline?t.isDirty?app.post(app.vroot()+"Site/CheckSiteKey/0",{siteId:t.id,siteKey:t.siteKey},function(r){if(r)return $.unblockUI(),t.siteKey=a,alert($("#SiteKeyLabel").val()+" must be unique, please select a different "+$("#SiteKeyLabel").val()+"."),!1;app.persist.putSite(t,function(){app.persist.putInspection(n,function(){app.persist.syncChanges(function(){n=null,t=null,app.synchronize.checkSync(),f(),$("#AddSiteDialog").dialog("close")},i)},i)},i)},function(){$.unblockUI(),alert("failed checking sitekey")}):app.persist.putSite(t,function(){app.persist.putInspection(n,function(){app.persist.syncChanges(function(){n=null,t=null,app.synchronize.checkSync(),f(),$("#AddSiteDialog").dialog("close")},i)},i)},i):app.persist.putInspection(n,function(){app.persist.syncChanges(function(){n=null,t=null,app.synchronize.checkSync(),f(),$("#AddSiteDialog").dialog("close")},i)},i)},Cancel:function(){$("#AddSiteDialog").dialog("close")}}}),ut=$(".js-date-answer"),ft=$(".js-date-hidden"),ft.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:ut,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),y=$(".js-inspection-date-answer"),c=$(".js-inspection-date-hidden"),c.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:y,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),l=$(".js-inspection-review-date-answer"),o=$(".js-inspection-review-date-hidden"),o.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:l,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),app.principal===undefined||app.principal===null||app.principal.isSensitiveEdit||(o.datepicker("disable"),$(".js-inspection-review-date-answer").prop("disabled","disabled"),$("#ReviewerSelect").prop("disabled","disabled")),app.principal!==undefined&&app.principal!==null&&app.principal.isAdmin?$("#RemoveInspection").parent().show():$("#RequireAdminForRemovingInspections").val()==="True"&&$("#RemoveInspection").parent().hide();$("#MyInspectionsFilter").on("keyup",function(){var f=$(this).val().trim().toUpperCase(),t,n,u,r,i;if(f==="")$("tr","#InspectionsTable").show();else for(t=$("tr","#InspectionsTable tbody"),n=0;n<t.length;n++){for(u=!1,r=$("td",t[n]),i=0;i<r.length;i++)if($(r[i]).text().trim().toUpperCase().indexOf(f)>=0){u=!0;break}u?$(t[n]).show():$(t[n]).hide()}a&&localStorage.setItem("stickyFilter",$(this).val().trim())})}),$("#SyncDialog").dialog({closeOnEscape:!1,draggable:!1,autoOpen:!1,height:150,minHeight:150,width:720,minWidth:720,modal:!0,resizable:!1,title:"Synchronizing",open:function(){$(this).prev("div").find(".ui-dialog-titlebar-close").hide()}})}}(),function(){function ai(n){$(st).find(".js-add-row-button").removeAttr("disabled"),$(st).find(".js-location-latlong:last").val(n.coords.latitude+", "+n.coords.longitude);for(var l=$(st).data("formcontrol-id"),u=$(st).find("table"),e=[],t=0,r=$("tr",u),s="",t=0;t<r.length;t++)t!==0&&(e.push({Description:$(".js-location-description",r[t]).val(),Location:$(".js-location-latlong",r[t]).val()}),t>0&&(s+="\r\n"),s+=$(".js-location-description",r[t]).val()+',"'+$(".js-location-latlong",r[t]).val()+'"');$(u).parents("form").find(".js-control-answer").val(JSON.stringify(e));var c=$(u).parents("li").data("formcontrol-id"),i=f(c),o=e,h={answer:o};i.plainTextValue=o,i.controlValue=JSON.stringify(h),i.isDirty=!0,d(i),v(),window.loadMap(i)}function tt(n){return String(n).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}if($("#Content").data("currentView")==="InspectionForm/Index"){var r=null,e=null,bt=null,n=null,ei=null,h=null,t=null,c=null,rt=null,st=null,ci=!1,si=!1,rr=null,ot=[],nr=null,wt=null,or=null,sr=!1,fr=1,bi=!0,it=!1,lt=null,vt=null,dt=null,p=!1,ct=null,ri=1,o=null,s=null,et=0,ut=0,kt=!1,di=!1,ht=null,gt=!1,ir=!1,tr=[],ur=[],ii=new Map,nt=new Map,b=[],a=[],yt=null,y=function(i,u,f){var d,a,y,w,v,it,rt,b,l,k,g,nt,tt;di=!1,bi=!0,d=!0,i==="FIRST"&&(i=e.sortedFormSections[0].id),i==="LAST"&&(i=e.sortedFormSections[e.sortedFormSections.length-1].id),h=i,kt=!1,t=p?n.inspectionFormSections.find(function(n){return n.formSectionId===h}):n.inspectionFormSections.find(function(n){return n.formSectionId===h}),$("#RepeatingSectionDialog").hide(),$("#Questions").unblock();try{if(o=e.sortedFormSections.find(function(n){return n.id===i}),o.repeatingSectionsCount>=0){if(u!==null&&u!==undefined&&u!==""&&(u=parseInt(u,10)),(u||u===0)&&(c=t.inspectionFormRepeatingSections.find(function(n){return n.sectionIndex===u})),a=[],y=1,p||(a=ft(o)),a.length>0){for(s=u?u:a[0],et=a.length,ut=a[a.length-1],w=0;w<t.inspectionFormRepeatingSections.length;w++)if(t.inspectionFormRepeatingSections[w].sectionIndex===s){c=t.inspectionFormRepeatingSections[w];break}if(u===undefined||u===null)y=1;else for(l=0;l<a.length;l++){if(u.toString()===a[l].toString())break;y++}}else s=null,et=0,ut=0,y=0,c=null,d=!1,f||$("#Questions").block({message:"<h1>Press the + button to add a repeating section, press the down arrow to view a list of sections<\/h1>",centerY:!1,css:{top:"0px"}});f&&(kt=!0),$(".ui-button-text","#RepeatingSectionButton").text(y+" of "+et),$("#RepeatingSectionButton").show(),$("#AddSectionButton").show()}else c=null,s=null,et=0,$("#RepeatingSectionButton").hide(),$("#AddSectionButton").hide();if(v="",v=r!==null&&r.site!==null?o.sectionTitle+" - "+r.site.siteKey+" "+r.site.siteName:o.sectionTitle,$("#SectionChooser").attr("title",v),v.length>80&&(v=v.substr(0,77)+"..."),$("#SectionChooser").text(v),$("#Questions ol").html(""),d)for(it={questions:o.sortedFormControls,isShowReferenceDesc:e.isShowReferenceDesc},rt=$.trim(ei(it)),$("#Questions ol").html(rt),b=$("li","#Questions ol"),l=0;l<b.length;l++)k=null,g=$(b[l]).data("formcontrol-id"),p||(o.repeatingSectionsCount>=0?n!==null&&(k=c.inspectionFormAnswers.find(function(n){return n.formControlId===g&&n.repeatingSection===s&&!n.isDeleted})):n!==null&&(k=t.inspectionFormAnswers.find(function(n){return n.formControlId===g&&!n.isDeleted}))),vi(b[l],k);nt=$("h3[data-formversion-id="+e.id+"]","#CurrentForms"),tt=$("li[data-formsection-id="+i+"]",nt.next()),$(".section-selected").removeClass("section-selected"),tt.addClass("section-selected"),$("#Questions").show(),window.scrollTo(0,0)}catch(ot){alert("Error rendering a form control in this section.  This form version should not be used for data entry."),console.error(ot),window.location.href=app.vroot()+"FormVersion?inspectionId="+r.id}},hi=function(t){for(var u,h,c,f,o,s,r=0;r<n.inspectionFormSections.length;r++){for(u=e.sortedFormSections.find(function(t){return t.id===n.inspectionFormSections[r].formSectionId}),u.tag&&ii.set(u.tag,{value:n.inspectionFormSections[r]}),u.visibilityFormula&&b.push({inspectionFormSection:n.inspectionFormSections[r],tagList:at(u.visibilityFormula),visibilityFormula:u.visibilityFormula}),h=0;h<n.inspectionFormSections[r].inspectionFormAnswers.length;h++)c=u.sortedFormControls.find(function(t){return t.id===n.inspectionFormSections[r].inspectionFormAnswers[h].formControlId}),c.tag&&nt.set(u.tag+"|"+c.tag,{value:n.inspectionFormSections[r].inspectionFormAnswers[h]}),c.visibilityFormula&&a.push({inspectionFormAnswer:n.inspectionFormSections[r].inspectionFormAnswers[h],tagList:at(c.visibilityFormula),visibilityFormula:c.visibilityFormula});if(n.inspectionFormSections[r].inspectionFormRepeatingSections)for(f=0;f<n.inspectionFormSections[r].inspectionFormRepeatingSections.length;f++)for(o=0;o<n.inspectionFormSections[r].inspectionFormRepeatingSections[f].inspectionFormAnswers.length;o++)s=u.sortedFormControls.find(function(t){return t.id===n.inspectionFormSections[r].inspectionFormRepeatingSections[f].inspectionFormAnswers[o].formControlId}),s.tag&&nt.set(u.tag+"|"+s.tag+"|"+n.inspectionFormSections[r].inspectionFormRepeatingSections[f].inspectionFormAnswers[o].repeatingSection,{value:n.inspectionFormSections[r].inspectionFormRepeatingSections[f].inspectionFormAnswers[o]}),s.visibilityFormula&&a.push({inspectionFormAnswer:n.inspectionFormSections[r].inspectionFormRepeatingSections[f].inspectionFormAnswers[o],tagList:at(s.visibilityFormula),visibilityFormula:s.visibilityFormula})}t()},g=function(n){var i=$(n).find(".question-toolbar").parent().find(".question-thread"),t;$(n).find(".question-toolbar").addClass("ui-active"),i.removeClass("hide-control"),t=i.find(".question-comment").find("textarea"),app.convertToAutoSize(t),$(n).find(".js-control-comment").resize(),$(n).find(".js-control-recommendation-comment").resize(),$(window).resize()},f=function(n){return c?c.inspectionFormAnswers.find(function(t){return t.formControlId===n}):t.inspectionFormAnswers.find(function(t){return t.formControlId===n})},at=function(n){for(var t=0,i=0,f=[],u,r;n.indexOf("`",t)>=0&&t>=0&&i>=0;)t=n.indexOf("`",t),i=n.indexOf("`",t+1),u=n.substring(t+1,i).split(":")[0],r=n.substring(t+1,i).split(":")[1],t=i+1,f.push({sectionTag:u,questionTag:r});return f},wi=function(n){var u,t,a,i,c,l,h,f,r,s;try{for(u=n.visibilityFormula,t=0;t<n.tagList.length;t++){if(a=ii.get(n.tagList[t].sectionTag).value,!a.isVisible)return!1;if(i=null,n.inspectionFormAnswer.repeatingSection)try{i=nt.get(n.tagList[t].sectionTag+"|"+n.tagList[t].questionTag+"|"+n.inspectionFormAnswer.repeatingSection).value}catch(y){i=nt.get(n.tagList[t].sectionTag+"|"+n.tagList[t].questionTag).value}else i=nt.get(n.tagList[t].sectionTag+"|"+n.tagList[t].questionTag).value;if(!i.isVisible)return!1;if(c=!1,e!==null&&o!==null&&(l=e.sortedFormSections.find(function(n){return n.id===i.formSectionId}),l!==null&&(h=l.sortedFormControls.find(function(n){return n.id===i.formControlId}),h!==null&&h.controlTypeFilename==="multiselect.html"&&(c=!0))),c){if(f="[",i!==null&&i.controlValue!==null&&i.controlValue!==undefined&&(r=JSON.parse(i.controlValue),r.answer!==null&&r.answer!==undefined&&Array.isArray(r.answer)))for(s=0;s<r.answer.length;s++)f+="'"+r.answer[s]+"'",s<r.answer.length-1&&(f+=",");f+="]",u=u.replace("`"+n.tagList[t].sectionTag+":"+n.tagList[t].questionTag+"`",f)}else u=u.replace("`"+n.tagList[t].sectionTag+":"+n.tagList[t].questionTag+"`",'"'+i.plainTextValue+'"')}return yt.run(u)}catch(v){return null}},ki=function(n){var r,t,l,h,c,s,u,i,f;try{for(r=n.visibilityFormula,t=0;t<n.tagList.length;t++){if(l=ii.get(n.tagList[t].sectionTag).value,!l.isVisible)return{value:!1};if(checkQuestion=nt.get(n.tagList[t].sectionTag+"|"+n.tagList[t].questionTag).value,!checkQuestion.isVisible)return{value:!1};if(h=!1,e!==null&&o!==null&&(c=e.sortedFormSections.find(function(n){return n.id===checkQuestion.formSectionId}),c!==null&&(s=c.sortedFormControls.find(function(n){return n.id===checkQuestion.formControlId}),s!==null&&s.controlTypeFilename==="multiselect.html"&&(h=!0))),h){if(u="[",checkQuestion!==null&&checkQuestion.controlValue!==null&&checkQuestion.controlValue!==undefined&&(i=JSON.parse(checkQuestion.controlValue),i.answer!==null&&i.answer!==undefined&&Array.isArray(i.answer)))for(f=0;f<i.answer.length;f++)u+="'"+i.answer[f]+"'",f<i.answer.length-1&&(u+=",");u+="]",r=r.replace("`"+n.tagList[t].sectionTag+":"+n.tagList[t].questionTag+"`",u)}else r=r.replace("`"+n.tagList[t].sectionTag+":"+n.tagList[t].questionTag+"`",'"'+checkQuestion.plainTextValue+'"')}return yt.run(r)}catch(a){return null}},d=function(){for(var v=!1,f=!1,i,t,l,c,s,e,h,o,u=0;u<b.length;u++)if(f=ki(b[u]),f&&b[u].inspectionFormSection.isVisible!==f.value){for(v=!0,b[u].inspectionFormSection.isVisible=f.value,b[u].inspectionFormSection.isDirty=!0,n.isDirty=!0,r.isDirty=!0,pt(),s=!1,e=0;e<n.inspectionFormSections.length;e++)if(n.inspectionFormSections[e].isVisible&&n.inspectionFormSections[e].hasMissingAnswer){s=!0;break}for(n.hasMissingAnswer=s,s?$("li[data-formsection-id="+b[u].inspectionFormSection.formSectionId+"]").parent().parent().prev().addClass("invalidForm"):$("li[data-formsection-id="+b[u].inspectionFormSection.formSectionId+"]").parent().parent().prev().removeClass("invalidForm"),h=!1,o=0;o<r.inspectionForms.length;o++)if(r.inspectionForms[o].hasMissingAnswer){h=!0;break}r.hasMissingAnswer=h,f.value?$('li[data-formsection-id="'+b[u].inspectionFormSection.formSectionId+'"]').show():$('li[data-formsection-id="'+b[u].inspectionFormSection.formSectionId+'"]').hide()}for(i=0;i<a.length;i++)if(f=wi(a[i]),f&&a[i].inspectionFormAnswer.isVisible!==f.value){for(v=!0,a[i].inspectionFormAnswer.isVisible=f.value,a[i].inspectionFormAnswer.isDirty=!0,t=n.inspectionFormSections.find(function(n){return a[i].inspectionFormAnswer.inspectionFormSectionId===n.id}),l=!1,c=0;c<t.inspectionFormAnswers.length;c++)if(t.inspectionFormAnswers[c].isVisible&&t.inspectionFormAnswers[c].hasMissingAnswer){l=!0;break}for(t.hasMissingAnswer=l,l?$("li[data-formsection-id="+t.formSectionId+"]").addClass("invalidSection"):$("li[data-formsection-id="+t.formSectionId+"]").removeClass("invalidSection"),s=!1,e=0;e<n.inspectionFormSections.length;e++)if(n.inspectionFormSections[e].isVisible&&n.inspectionFormSections[e].hasMissingAnswer){s=!0;break}for(n.hasMissingAnswer=s,s?$("li[data-formsection-id="+t.formSectionId+"]").parent().parent().prev().addClass("invalidForm"):$("li[data-formsection-id="+t.formSectionId+"]").parent().parent().prev().removeClass("invalidForm"),h=!1,o=0;o<r.inspectionForms.length;o++)if(r.inspectionForms[o].hasMissingAnswer){h=!0;break}r.hasMissingAnswer=h,f.value&&a[i].inspectionFormAnswer.hasMissingAnswer&&(t.hasMissingAnswer=!0,t.isVisible&&(n.hasMissingAnswer=!0,n.isDirty,r.hasMissingAnswer=!0,r.isDirty=!0,$("li[data-formsection-id="+t.formSectionId+"]").addClass("invalidSection"),$("li[data-formsection-id="+t.formSectionId+"]").parent().parent().prev().addClass("invalidForm"))),t.isDirty=!0,a[i].inspectionFormAnswer.inspectionFormRepeatingSection&&(t.inspectionFormRepeatingSections.find(function(n){a[i].inspectionFormAnswer.inspectionFormRepeatingSectionId===n.id}).isDirty=!0),n.isDirty=!0,r.isDirty=!0,pt(a[i].inspectionFormAnswer,a[i].inspectionFormAnswer.score),f.value?$('li[data-formcontrol-id="'+a[i].inspectionFormAnswer.formControlId+'"]').show():$('li[data-formcontrol-id="'+a[i].inspectionFormAnswer.formControlId+'"]').hide()}v&&d()},v=function(t,i){var s,u,o,f,e;if(Wndsr.info("Checking to save inspection"),!t&&it?Wndsr.info("Save Pending, will rety in 5 seconds"):r.isDirty||(Wndsr.info("No save needed"),i&&i()),r.isDirty&&!it){for(it=!0,Wndsr.info("Saving Inspection"),s=_.cloneDeep(r),r.isDirty=!1,app.isMobile()||(r.isNew=!1),n.isDirty=!1,app.isMobile()||(n.isNew=!1),u=0;u<n.inspectionFormSections.length;u++){if(n.inspectionFormSections[u].isDirty=!1,app.isMobile()||(n.inspectionFormSections[u].isNew=!1),n.inspectionFormSections[u].inspectionFormAnswers)for(o=0;o<n.inspectionFormSections[u].inspectionFormAnswers.length;o++)if(n.inspectionFormSections[u].inspectionFormAnswers[o].isDirty=!1,app.isMobile()||(n.inspectionFormSections[u].inspectionFormAnswers[o].isNew=!1),n.inspectionFormSections[u].inspectionFormAnswers[o].inspectionFormMedia)for(e=0;e<n.inspectionFormSections[u].inspectionFormAnswers[o].inspectionFormMedia.length;e++)n.inspectionFormSections[u].inspectionFormAnswers[o].inspectionFormMedia[e].isDirty=!1,app.isMobile()||(n.inspectionFormSections[u].inspectionFormAnswers[o].inspectionFormMedia[e].isNew=!1);if(n.inspectionFormSections[u].inspectionFormRepeatingSections)for(f=0;f<n.inspectionFormSections[u].inspectionFormRepeatingSections.length;f++)for(n.inspectionFormSections[u].inspectionFormRepeatingSections[f].isDirty=!1,app.isMobile()||(n.inspectionFormSections[u].inspectionFormRepeatingSections[f].isNew=!1),l=0;l<n.inspectionFormSections[u].inspectionFormRepeatingSections[f].inspectionFormAnswers.length;l++)if(n.inspectionFormSections[u].inspectionFormRepeatingSections[f].inspectionFormAnswers[l].isDirty=!1,app.isMobile()||(n.inspectionFormSections[u].inspectionFormRepeatingSections[f].inspectionFormAnswers[l].isNew=!1),n.inspectionFormSections[u].inspectionFormRepeatingSections[f].inspectionFormAnswers[l].inspectionFormMedia)for(e=0;e<n.inspectionFormSections[u].inspectionFormRepeatingSections[f].inspectionFormAnswers[l].inspectionFormMedia.length;e++)n.inspectionFormSections[u].inspectionFormRepeatingSections[f].inspectionFormAnswers[l].inspectionFormMedia[e].isDirty=!1,app.isMobile()||(n.inspectionFormSections[u].inspectionFormRepeatingSections[f].inspectionFormAnswers[l].inspectionFormMedia[e].isNew=!1)}p?(it=!1,Wndsr.info("Saving Complete"),i&&i()):s.Save(function(){it=!1,Wndsr.info("Saving Complete"),i&&i()},w)}else i&&i()},u=function(i,u){var l,y,f,a,e,s,h,v;if(i.isDirty=!0,l=n.inspectionFormSections.find(function(n){return n.id===i.inspectionFormSectionId}),y=o.sortedFormControls.find(function(n){return n.id===i.formControlId}),i.hasMissingAnswer=y.isRequiredInput&&(i.plainTextValue===undefined||i.plainTextValue===null||i.plainTextValue==="")?!0:!1,f=!1,c){for(e=0;e<c.inspectionFormAnswers.length;e++)if(c.inspectionFormAnswers[e].hasMissingAnswer&&c.inspectionFormAnswers[e].isVisible){f=!0;break}for(c.hasMissingAnswer=f,f=!1,a=0;a<t.inspectionFormRepeatingSections.length;a++)if(t.inspectionFormRepeatingSections[a].hasMissingAnswer){f=!0;break}t.hasMissingAnswer=f}else{for(f=!1,e=0;e<t.inspectionFormAnswers.length;e++)if(t.inspectionFormAnswers[e].hasMissingAnswer&&t.inspectionFormAnswers[e].isVisible){f=!0;break}t.hasMissingAnswer=f}for(f=!1,s=0;s<n.inspectionFormSections.length;s++)if(n.inspectionFormSections[s].hasMissingAnswer&&n.inspectionFormSections[s].isVisible){f=!0;break}for(n.hasMissingAnswer=f,f=!1,h=0;h<r.inspectionForms.length;h++)if(r.inspectionForms[h].hasMissingAnswer){f=!0;break}r.hasMissingAnswer=f,l.isDirty=!0,i.inspectionFormRepeatingSectionId&&(v=l.inspectionFormRepeatingSections.find(function(n){return n.id===i.inspectionFormRepeatingSectionId}),v.isDirty=!0),n.isDirty=!0,r.isDirty=!0,r.actualStart||(r.actualStart=(new moment).format("M/D/YYYY")),pt(i,u),d(i,l)},ti=function(n){for(var a=$("#AllowRepeatingSectionCopy").val().toUpperCase()==="TRUE",e=[],f,r,l,c,h,u,i=0;i<n.sortedFormControls.length;i++)if(f=n.sortedFormControls[i].controlTypeFilename,(f==="text.html"||f==="date.html"||f==="number.html"||f==="url.html"||f==="yesno.html"||f==="time.html"||f==="singleselect.html"||f==="location.html")&&(e.push(n.sortedFormControls[i]),e.length>=3))break;for(r="",r+="<thead>",r+="<tr>",r+="<th><\/th>",r+="<th>#<\/th>",i=0;i<e.length;i++)r+=e[i].questionText.length>20?"<th>"+e[i].questionText.substring(0,19)+"...<\/th>":"<th>"+e[i].questionText+"<\/th>";for(a&&(r+="<th class='section-action-copy'><\/th>"),r+="<th class='section-action-up'><\/th><th class='section-action-down'>Action<\/th><th class='section-action-delete'><\/th>",r+="<\/tr>",r+="<\/thead>",r+="<tbody>",l=[],p||(l=ft(o)),t.inspectionFormRepeatingSections=t.inspectionFormRepeatingSections.sort(function(n,t){return n.sectionIndex-t.sectionIndex}),i=0;i<t.inspectionFormRepeatingSections.length;i++)if(!t.inspectionFormRepeatingSections[i].isDeleted){for(r+=t.inspectionFormRepeatingSections[i].sectionIndex===s?"<tr class='section-selected' data-index='"+t.inspectionFormRepeatingSections[i].sectionIndex+"'>":"<tr data-index='"+t.inspectionFormRepeatingSections[i].sectionIndex+"'>",r+=t.inspectionFormRepeatingSections[i].hasMissingAnswer?"<td class='invalidRepeatingSection'>*<\/td>":"<td><\/td>",r+="<td>"+(i+1).toString()+"<\/td>",c=0;c<e.length;c++){for(h="",u=0;u<t.inspectionFormRepeatingSections[i].inspectionFormAnswers.length;u++)if(t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].formControlId===e[c].id&&!t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].isDeleted){h=t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].plainTextValue===undefined||t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].plainTextValue===null?"":t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].plainTextValue.length>20?t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].plainTextValue.substring(0,19)+"...":t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].plainTextValue;break}r+="<td>"+h+"<\/td>"}a&&(i===0?r+="<td><\/td>":(r+="<\/td><td class='js-section-action section-action-copy'>",r+="<button class='js-copy-section' data-index='"+t.inspectionFormRepeatingSections[i].sectionIndex+"'><\/button>",r+="<\/td>")),r+="<td class='js-section-action section-action-up'>",i>0&&(r+="<button class='js-up-section' data-index='"+t.inspectionFormRepeatingSections[i].sectionIndex+"'><\/button>"),r+="<\/td><td class='js-section-action section-action-down' data-index='"+t.inspectionFormRepeatingSections[i].sectionIndex+"'>",i<t.inspectionFormRepeatingSections.length-1&&(r+="<button class='js-down-section' data-index='"+t.inspectionFormRepeatingSections[i].sectionIndex+"'><\/button>"),r+="<\/td><td class='js-section-action section-action-delete'>",r+="<button class='js-delete-section' data-index='"+t.inspectionFormRepeatingSections[i].sectionIndex+"'><\/button>",r+="<\/td>",r+="<\/tr>"}r+="<\/tbody>",$("#RepeatingTable","#RepeatingSectionDialog").html(r),$(".js-up-section").button({text:!1,icons:{primary:"ui-icon-admin-up"}}),$(".js-down-section").button({text:!1,icons:{primary:"ui-icon-admin-down"}}),$(".js-delete-section").button({text:!1,icons:{primary:"ui-icon-admin-delete"}}),$(".js-copy-section").button({text:!1,icons:{primary:"ui-icon-admin-copy"}}),scrollTo(0,0),$("#Questions").block({message:null}),$("#RepeatingSectionDialog").show(),$.unblockUI()},ft=function(t){for(var u=[],r,i=0;i<n.inspectionFormSections.length;i++)if(n.inspectionFormSections[i].formSection){if(n.inspectionFormSections[i].formSection.id===t.id){for(r=0;r<n.inspectionFormSections[i].inspectionFormRepeatingSections.length;r++)n.inspectionFormSections[i].inspectionFormRepeatingSections[r].isDeleted||u.push(n.inspectionFormSections[i].inspectionFormRepeatingSections[r].sectionIndex);break}}else if(n.inspectionFormSections[i].formSectionId===t.id){for(n.inspectionFormSections[i].inspectionFormRepeatingSections===undefined&&(n.inspectionFormSections[i].inspectionFormRepeatingSections=[]),r=0;r<n.inspectionFormSections[i].inspectionFormRepeatingSections.length;r++)n.inspectionFormSections[i].inspectionFormRepeatingSections[r].isDeleted||u.push(n.inspectionFormSections[i].inspectionFormRepeatingSections[r].sectionIndex);break}return u=u.sort(function(n,t){return n-t})},pt=function(t,i){var u,h,f,y,c,e,o,a,s,v,l;if(i!==undefined&&i!==null)if(i=parseFloat(i),t.score=i,u=n.inspectionFormSections.find(function(n){return n.id===t.inspectionFormSectionId}),h=0,t.inspectionFormRepeatingSectionId){for(f=u.inspectionFormRepeatingSections.find(function(n){return n.sectionIndex===t.repeatingSection}),y=0,c=0;c<f.inspectionFormAnswers.length;c++)f.inspectionFormAnswers[c].isVisible&&(y+=f.inspectionFormAnswers[c].score);for(f.score=y,f.isDirty=!0,e=0;e<u.inspectionFormRepeatingSections.length;e++)u.inspectionFormRepeatingSections[e].isDeleted||(h+=u.inspectionFormRepeatingSections[e].score);u.score=h,u.isDirty=!0}else{for(o=0;o<u.inspectionFormAnswers.length;o++)u.inspectionFormAnswers[o].isVisible&&(h+=u.inspectionFormAnswers[o].score);u.score=h,u.isDirty=!0}for(a=0,s=0;s<n.inspectionFormSections.length;s++)n.inspectionFormSections[s].isVisible&&(a+=n.inspectionFormSections[s].score);for(n.score=a,n.isDirty=!0,v=0,l=0;l<r.inspectionForms.length;l++)v+=r.inspectionForms[l].score;r.score=v,r.isDirty=!0},oi=function(n,t){n.val().match(/^\d+$/)||n.val("");var u=n.attr("min"),f=n.attr("max"),r=n.attr("maxlength"),i=parseInt(n.val());if(u&&i<u){n.val("");return}if(f&&i>f){n.val("");return}if(r&&n.val().length>r&&n.val(n.val().substring(0,r)),t&&r&&n.val().length<r){for(i=n.val();i.length<r;)i="0"+i;n.val(i)}};window.initMap=function(){for(var r={center:new google.maps.LatLng(45.490847,-122.671914),zoom:19,mapTypeId:google.maps.MapTypeId.SATELLITE,draggable:!1,scrollwheel:!1,maxZoom:20},t=$(".js-map-canvas"),i,n=0;n<t.length;n++)i=new google.maps.Map(t[n],r);si=!0,window.loadMap()},window.loadMap=function(n){var r;if(n!==undefined&&ot.push(n),si){for(r=0;r<ot.length;r++){var s=$("li[data-formcontrol-id='"+ot[r].formControlId+"']"),l=$(".js-map-canvas",s)[0],c={center:new google.maps.LatLng(45.490847,-122.671914),zoom:19,mapTypeId:google.maps.MapTypeId.SATELLITE,draggable:!1,scrollwheel:!1,maxZoom:20},e=new google.maps.Map(l,c),u=new google.maps.LatLngBounds,t=JSON.parse(ot[r].controlValue);if(t!==undefined&&t!==null)for(i=0;i<t.answer.length;i++)if(t.answer[i].Location!==""&&t.answer[i].Location.indexOf(", ")>0){var h=parseFloat(t.answer[i].Location.substring(0,t.answer[i].Location.indexOf(", "))),o=parseFloat(t.answer[i].Location.substring(t.answer[i].Location.indexOf(", ")+2)),f=new google.maps.LatLng(h,o),a=new google.maps.Marker({position:f,map:e,title:t.answer[i].Description});u.extend(f),e.fitBounds(u)}}ot=[]}};var er=function(n,t){t.rows.length===1&&$("#image_"+t.rows.item(0).Id).attr("src",t.rows.item(0).MimeType+t.rows.item(0).MediaObject)},vi=function(n,t){var o=n,c=$(n).data("formcontrol-id"),kr=$(".js-control-type-file-name",o).val(),vr=$(".js-control-definition",o).val(),br=$(".js-required-control",o).val(),i="",ct=$(".js-is-allowed-input",o).val(),cr,fi,ar,yt,yr,rr,hr,y,gt,ut,bi,p,dt,a,nr,ft,it,bt,l,e,ri,nt,et,h,si,wr,g,ii,ei,ur,fr,wi,gi,ki,tt,ti,lr,pt,s,or,tr;if(vr!==""&&(i=JSON.parse(vr),i.score&&$(n).data("score",i.score)),t==null||t.isVisible||$(o).hide(),t!=null&&t.isAnswerViolation&&($(".ui-icon-violation-set",o).show(),$(o).find(".violation-section").removeClass("hide-control"),t.violationDeterminedDate!==undefined&&t.violationDeterminedDate!==null&&t.violationDeterminedDate.indexOf("T")<0?$(o).find(".js-violation-date").val(moment(t.violationDeterminedDate).format("M/D/YYYY")):t.violationDeterminedDate!==undefined&&t.violationDeterminedDate!==null?$(o).find(".js-violation-date").val(moment.utc(t.violationDeterminedDate).format("M/D/YYYY")):t.violationCreatedDate!==undefined&&t.violationCreatedDate!==null&&$(o).find(".js-violation-date").val(t.violationCreatedDate)),t!=null&&(t.answerComment!==undefined&&t.answerComment!==null&&t.answerComment.length>0||t.recommendationComment!==undefined&&t.recommendationComment!==null&&t.recommendationComment.length>0)&&($(".ui-icon-comment-set",o).show(),$(".js-answer-comment",o).val(t.answerComment),$(".js-answer-recommendation-comment",o).val(t.recommendationComment)),t!=null&&t.latitude!==undefined&&t.latitude!==null&&t.longitude!==undefined&&t.longitude!==null&&(t.latitude.length>0||t.longitude.length>0)&&($(o).find(".ui-icon-gps-set").removeClass("hide-control"),$(o).find(".gps-section").removeClass("hide-control"),$(".js-gps-latlong-answer",o).val(t.latitude+","+t.longitude),$(o).find(".ui-icon-gps-set").removeClass("hide-control")),t!=null&&t.inspectionFormMedia!==undefined&&t.inspectionFormMedia!==null&&t.inspectionFormMedia.length>0){for(cr=!1,fi=0;fi<t.inspectionFormMedia.length;fi++)if(t.inspectionFormMedia[fi].mediaPath!=="signature"&&t.inspectionFormMedia[fi].mediaPath!=="drawing"||t.plainTextValue==="Mobile Signature"||t.plainTextValue==="Mobile Drawing"){cr=!0;break}if(cr)for(ar=$(".js-image-output",o),$(o).find(".ui-icon-photo-set").removeClass("hide-control"),t.inspectionFormMedia.sort(function(n,t){return n.imageCapturedTime>t.imageCapturedTime?1:n.imageCapturedTime<t.imageCapturedTime?-1:0}),a=0;a<t.inspectionFormMedia.length;a++)(t.inspectionFormMedia[a].isDeleted||t.inspectionFormMedia[a].mediaPath==="signature"||t.inspectionFormMedia[a].isDeleted||t.inspectionFormMedia[a].mediaPath==="drawing")&&t.plainTextValue!=="Mobile Signature"&&t.plainTextValue!=="Mobile Drawing"||(yt=document.createElement("li"),yr='<img id="image_'+t.inspectionFormMedia[a].id+'" class="thumbnail" title="'+escape(a)+'"/><div><button class="js-image-info">Info<\/button><button class="js-image-delete">Delete<\/button><\/div>',yt.innerHTML=yr,ar[0].insertBefore(yt,null),$.data(yt,"inspectionformanswer-id",t.id),$.data(yt,"inspectionformmedia-id",t.inspectionFormMedia[a].id),$(".js-image-info",yt).button({text:!1,icons:{primary:"ui-icon-info"}}),$(".js-image-delete",yt).button({text:!1,icons:{primary:"ui-icon-close"}}),app.persist.getFile(t.inspectionFormMedia[a].id,function(n,i){n.data.length>0?app.resizeBase64Img(n.data,i.mimeType,100,null).then(function(n){$("#image_"+i.id).attr("src",n[0].src)}):$("#image_"+t.inspectionFormMedia[a].id).attr("src",$("#OfflineImage").attr("src"))},w,t.inspectionFormMedia[a]))}rr=$(".js-violation-date",o),hr=$(".js-violation-date-hidden",o),hr.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:rr,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),rr.change(function(){var o=$(this).parents("li").data("formcontrol-id"),t=f(o),n,i,s,e;if($.trim($(this).val()).length==0){alert($("#ViolationDate").val()+" is required"),$(this).val(moment(t.violationDeterminedDate).format("M/D/YYYY"));return}if(n=null,n=r.actualStart!==undefined&&r.actualStart!==null?r.actualStart:r.scheduledStart,n=new moment(n),n=n.startOf("day"),i=new moment,i=i.startOf("day"),s=i.add("d",30),e=new moment($(this).val()),e.diff(n,"days",!0)<0){alert($("#ViolationDate").val()+" cannot be before the evaluation date"),$(this).val(moment(t.violationDeterminedDate).format("M/D/YYYY"));return}if(e.diff(n,"days",!0)>60)return alert($("#ViolationDate").val()+" cannot be more than 60 days in the future"),$(this).val(moment(t.violationDeterminedDate).format("M/D/YYYY")),!1;$(this).siblings(".js-violation-date-hidden").val($(this).val()),t.violationDeterminedDate=$(this).val(),t.isDirty=!0,u(t,t.score)}),hr.change(function(){var o=$(this).parents("li").data("formcontrol-id"),n=f(o),t,i,s,e;if($.trim($(this).val()).length==0){alert($("#ViolationDate").val()+" is required"),$(this).val(moment(n.violationDeterminedDate).format("M/D/YYYY"));return}if(t=null,t=r.actualStart!==undefined&&r.actualStart!==null?r.actualStart:r.scheduledStart,t=new moment(t),t=t.startOf("day"),i=new moment,i=i.startOf("day"),s=i.add("d",30),e=new moment($(this).val()),e.diff(t,"days",!0)<0)return alert($("#ViolationDate").val()+" cannot be before the evaluation date"),$(this).val(moment(n.violationDeterminedDate).format("M/D/YYYY")),$(this).siblings(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),!1;if(e.diff(t,"days",!0)>60)return alert($("#ViolationDate").val()+" cannot be more than 60 days in the future"),$(this).val(moment(n.violationDeterminedDate).format("M/D/YYYY")),$(this).siblings(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),!1;$(this).siblings(".js-violation-date").val($(this).val()),n.violationDeterminedDate=$(this).val(),n.isDirty=!0,u(n,n.score)});switch(kr){case"text.html":if(y=$(".js-text-answer",o),br&&y.addClass("required"),i.maxLength!==undefined&&(y.attr("maxlength",i.maxLength),i.maxLength<=15?y.addClass("text-length1"):i.maxLength<=30?y.addClass("text-length2"):i.maxLength<=45?y.addClass("text-length3"):y.addClass("text-length4")),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),y.val(s.answer)}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Text.)")}y.change(function(){var s=$(this).parents("li").data("formcontrol-id"),n=f(s),r=$(this).val(),h={answer:r},i,e,t;n.plainTextValue=r,n.controlValue=JSON.stringify(h),i=$(this).parents("li").find(".js-control-value-violation").val(),i!==""&&(e=JSON.parse(i),r.toUpperCase().indexOf(e.answer.toUpperCase())>=0?($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY"))):($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null,$(o).find(".js-violation-date").val(""))),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)});break;case"date.html":var y=$(".js-date-answer",o),er=$(".js-date-hidden",o),hi=$(".js-add-date-button",o);hi.button({text:!0});hi.on("click",function(){var t;y.val($.datepicker.formatDate("mm/dd/yy",new Date));var r=$(this).parents("li").data("formcontrol-id"),n=f(r),i=$.datepicker.formatDate("mm/dd/yy",new Date),e={answer:i};$(this).siblings(".js-date-hidden").val(i),n.plainTextValue=i,n.controlValue=JSON.stringify(e),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)});if(er.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:y,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),y.val(s.answer),er.val(s.answer)}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Date.)")}y.change(function(){var r=$(this).parents("li").data("formcontrol-id"),n=f(r),i=$(this).val(),e={answer:i},t;$(this).siblings(".js-date-hidden").val(i),n.plainTextValue=i,n.controlValue=JSON.stringify(e),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)}),er.change(function(){var r=$(this).parents("li").data("formcontrol-id"),n=f(r),i=$(this).val(),e={answer:i},t;$(this).siblings(".js-date-answer").val(i),n.plainTextValue=i,n.controlValue=JSON.stringify(e),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)});break;case"number.html":if(y=$(".js-number-answer",o),y.keypress(function(n){var t=n.which?n.which:event.keyCode;return t!=46&&t!=45&&t>31&&(t<48||t>57)?(alert("Only numeric values are allowed"),n.preventDefault(),!1):!0}),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),y.val(s.answer)}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Number.)")}y.change(function(){var s=$(this).parents("li").data("formcontrol-id"),n=f(s),r=$(this).val(),h={answer:r},e,t,i;n.plainTextValue=r,n.controlValue=JSON.stringify(h),n.isDirty=!0,e=$(this).parents("li").find(".js-control-value-violation").val(),e!==""&&(t=JSON.parse(e),t.equals!==undefined&&parseInt(r)===parseInt(t.equals)?($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY"))):t.greaterThan!==undefined&&parseInt(r)>parseInt(t.greaterThan)?($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY"))):t.lessThan!==undefined&&parseInt(r)<parseInt(t.lessThan)?($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY"))):($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null,$(o).find(".js-violation-date").val(""))),n.plainTextValue.length>0?(i=$.trim($($(this).parents("li")[0]).data("score")),i!==undefined&&i!==null&&i!=="null"&&i!==""?u(n,i):u(n,0)):u(n,0)});break;case"url.html":if(y=$(".js-url-answer",o),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),y.val(s.answer)}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is URL.)")}y.change(function(){var r=$(this).parents("li").data("formcontrol-id"),n=f(r),i=$(this).val(),e={answer:i},t;n.plainTextValue=i,n.controlValue=JSON.stringify(e),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)});break;case"yesno.html":if(i.includeNA===undefined?($(".js-input-na",o).remove(),$(".js-label-na",o).remove(),$(".js-radio-button",o).addClass("js-yes-no")):i.includeNA===!1?($(".js-input-na",o).remove(),$(".js-label-na",o).remove(),$(".js-radio-button",o).addClass("js-yes-no")):$(".js-radio-button",o).addClass("js-yes-no-na"),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),s.answer==="Yes"?$(".js-input-yes",o).attr("checked","checked"):s.answer==="No"?$(".js-input-no",o).attr("checked","checked"):s.answer==="NA"&&$(".js-input-na",o).attr("checked","checked")}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is YesNo.)")}$(".js-radio-button",o).buttonset();$("input[type=radio]",o).on("change",function(){var e=$(this).parents("li").data("formcontrol-id"),n=f(e),r=$(this).val(),s={answer:r},t,i;n.plainTextValue=r,n.controlValue=JSON.stringify(s),n.isDirty=!0,t=$(this).parents("li").find(".js-control-value-violation").val(),t!==""&&(i=JSON.parse(t),i.answer!==undefined&&r.toUpperCase()===i.answer.toUpperCase()?($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY"))):($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null,$(o).find(".js-violation-date").val(""))),u(n,0)});break;case"time.html":var lt=$(".js-hour-answer",o),ot=$(".js-min-answer",o),vt=$(".js-am-answer",o),wt=$(".js-pm-answer",o),hi=$(".js-add-time-button",o);if(hi.button({text:!0}),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),lt.val(s.hours),ot.val(s.minutes),s.ampm==="AM"?vt.attr("checked","checked"):s.ampm==="PM"&&wt.attr("checked","checked")}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Time.)")}$(".js-radio-button",o).buttonset();hi.on("click",function(){var s=new Date,n=s.getHours(),r=s.getMinutes(),e,i;r<10&&(r="0"+r),e=n>=12?"PM":"AM",n>12&&(n=n-12),e==="AM"?(vt.attr("checked","checked"),wt.removeAttr("checked","checked")):(wt.attr("checked","checked"),vt.removeAttr("checked","checked")),$(".js-radio-button",o).buttonset("refresh"),$(this).parent().find(".js-hour-answer").val(n),$(this).parent().find(".js-min-answer").val(r);var a=$(this).parents("li").attr("formcontrol-id"),c={hours:n,minutes:r,ampm:e},l=n+":"+r+" "+e,h=$(this).parents("li").data("formcontrol-id"),t=f(h);return t.plainTextValue=l,t.controlValue=JSON.stringify(c),t.isDirty=!0,t.plainTextValue.length>0?(i=$.trim($($(this).parents("li")[0]).data("score")),i!==undefined&&i!==null&&i!=="null"&&i!==""?u(t,i):u(t,0)):u(t,0),!1});vt.on("click",function(n){var r="AM",i;n!==undefined&&n.isTrigger?($(this).attr("checked","checked"),wt.removeAttr("checked")):($(this).attr("checked","checked"),$(".js-pm-answer",o).removeAttr("checked"));var s={hours:$.trim(lt.val()),minutes:$.trim(ot.val()),ampm:r},e=$.trim(lt.val())+":"+$.trim(ot.val())+" "+r,h=$(this).parents("li").data("formcontrol-id"),t=f(h);t.plainTextValue=e,t.controlValue=JSON.stringify(s),t.isDirty=!0,t.plainTextValue.length>0?(i=$.trim($($(this).parents("li")[0]).data("score")),i!==undefined&&i!==null&&i!=="null"&&i!==""?u(t,i):u(t,0)):u(t,0)});wt.on("click",function(n){var r="PM",i;n!==undefined&&n.isTrigger?($(this).attr("checked","checked"),vt.removeAttr("checked")):($(this).attr("checked","checked"),$(".js-am-answer",o).removeAttr("checked"));var s={hours:$.trim(lt.val()),minutes:$.trim(ot.val()),ampm:r},e=$.trim(lt.val())+":"+$.trim(ot.val())+" "+r,h=$(this).parents("li").data("formcontrol-id"),t=f(h);t.plainTextValue=e,t.controlValue=JSON.stringify(s),t.isDirty=!0,t.plainTextValue.length>0?(i=$.trim($($(this).parents("li")[0]).data("score")),i!==undefined&&i!==null&&i!=="null"&&i!==""?u(t,i):u(t,0)):u(t,0)});lt.on("change",function(){var i="",t;vt.attr("checked")==="checked"?i="AM":wt.attr("checked")==="checked"&&(i="PM"),oi($(this),!1);var e={hours:$.trim($(this).val()),minutes:$.trim(ot.val()),ampm:i},r=$.trim($(this).val())+":"+$.trim(ot.val())+" "+i,o=$(this).parents("li").data("formcontrol-id"),n=f(o);n.plainTextValue=r,n.controlValue=JSON.stringify(e),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)});ot.on("change",function(){var i="",t;vt.attr("checked")==="checked"?i="AM":wt.attr("checked")==="checked"&&(i="PM"),oi($(this),!0);var e={hours:$.trim(lt.val()),minutes:$.trim($(this).val()),ampm:i},r=$.trim(lt.val())+":"+$.trim($(this).val())+" "+i,o=$(this).parents("li").data("formcontrol-id"),n=f(o);n.plainTextValue=r,n.controlValue=JSON.stringify(e),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)});break;case"singleselect.html":if(gt=$(".js-radio-button",o),ft=$(".js-select-list",o),i.useRadioButtons!==undefined&&i.useRadioButtons){ft.hide();for(var ht="",e=0,b=!1,e=0;e<i.options.length;e++){if(ut="<label for='"+c+"_"+e.toString()+"'>",ut+=i.options[e].score!==undefined?"<input type='radio' name='"+c+"' score='"+i.options[e].score+"' id='"+c+"_"+e.toString()+"' value=\""+i.options[e].text+'" ':i.options[e].text!==undefined?"<input type='radio' name='"+c+"' id='"+c+"_"+e.toString()+"' value=\""+i.options[e].text+'" ':"<input type='radio' name='"+c+"' id='"+c+"_"+e.toString()+"' value=\""+i.options[e]+'" ',t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),i.options[e].text?$.trim(s.answer.toUpperCase())===$.trim(i.options[e].text.toUpperCase())&&(ut+="checked='checked' "):$.trim(s.answer.toUpperCase())===$.trim(i.options[e].toUpperCase())&&(ut+="checked='checked' ")}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Single Select.)"),console.error(dr),b=!0)}ct==="false"&&(ut+="disabled='disabled' "),ut+="/> ",ut+=i.options[e].text!==undefined?i.options[e].text+"<\/label>":i.options[e]+"<\/label>",ht+=e%2==0?"<tr><td>"+ut+"<\/td>":"<td>"+ut+"<\/td><\/tr>"}i.options.length>0&&i.options.length%2!=0&&(ht+="<td><\/td><\/tr>"),gt.find("tbody").html(ht);gt.on("change","input",function(){var c={answer:$.trim($(this).val())},h=$.trim($(this).parent().text()),l=$(this).parents("li").data("formcontrol-id"),n=f(l),s,i,e,r,t;if(n.plainTextValue=h,n.controlValue=JSON.stringify(c),n.isDirty=!0,s=$(this).parents("li").find(".js-control-value-violation").val(),s!==""&&(i=JSON.parse(s),e=!1,i.answer!==undefined)){for(r=0;r<i.answer.length;r++)$.trim(i.answer[r].toUpperCase())===$.trim(h.toUpperCase())&&($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),e=!0);e||($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,$(o).find(".js-violation-date").val(""),n.violationDeterminedDate=null)}t=$.trim($(this).attr("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)})}else if(i.useHorizontal!==undefined&&i.useHorizontal){for(ft.hide(),bi='<div class="js-radio-button js-yes-no yes-no-answer">',e=0;e<i.options.length;e++){if(p="",i.options[e].text!==undefined){if(p+=i.options[e].score!==undefined?"<input id='"+c+"_"+e+"' class='js-input-yes' type='radio' value='"+i.options[e].text+"' score='"+i.options[e].score+"' name='"+c+"' ":"<input id='"+c+"_"+e+"' class='js-input-yes' type='radio' value='"+i.options[e].text+"' name='"+c+"' ",t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{dt=JSON.parse(t.controlValue),i.options[e].text?$.trim(dt.answer.toUpperCase())===$.trim(i.options[e].text.toUpperCase())&&(p+="checked='checked' "):$.trim(dt.answer.toUpperCase())===$.trim(i.options[e].toUpperCase())&&(p+="checked='checked' ")}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Single Select.)"),console.error(dr),b=!0)}ct==="false"&&(p+="disabled='disabled' "),p+="/>",p+="<label class='js-label-yes' for='"+c+"_"+e+"' "}else{if(p+=i.options[e].score!==undefined?"<input id='"+c+"_"+e+"' class='js-input-yes' type='radio' value='"+i.options[e].text+"' score='"+i.options[e].score+"' name='"+c+"' ":"<input id='"+c+"_"+e+"' class='js-input-yes' type='radio' value='"+i.options[e].text+"' name='"+c+"' ",t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{dt=JSON.parse(t.controlValue),i.options[e].text?$.trim(dt.answer.toUpperCase())===$.trim(i.options[e].text.toUpperCase())&&(p+="checked='checked' "):$.trim(dt.answer.toUpperCase())===$.trim(i.options[e].toUpperCase())&&(p+="checked='checked' ")}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Single Select.)"),console.error(dr),b=!0)}ct==="false"&&(p+="disabled='disabled' "),p+="/>",p+="<label class='js-label-yes' for='"+c+"_"+e+"' "}p+="> ",p+=i.options[e].text!==undefined?i.options[e].text+"<\/label>":i.options[e]+"<\/label>",bi+=p+" "}bi+="<\/div>",gt.parent().removeClass("question-answer-full-width").addClass("question-answer"),gt.parent().html(bi),$(".js-radio-button",o).buttonset();$("input[type=radio]",o).on("change",function(){var c={answer:$.trim($(this).val())},h=$.trim($(this).val()),l=$(this).parents("li").data("formcontrol-id"),n=f(l),s,i,e,r,t;if(n.plainTextValue=h,n.controlValue=JSON.stringify(c),n.isDirty=!0,s=$(this).parents("li").find(".js-control-value-violation").val(),s!==""&&(i=JSON.parse(s),e=!1,i.answer!==undefined)){for(r=0;r<i.answer.length;r++)$.trim(i.answer[r].toUpperCase())===$.trim(h.toUpperCase())&&($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),e=!0);e||($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,$(o).find(".js-violation-date").val(""),n.violationDeterminedDate=null)}t=$.trim($(this).attr("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)})}else{gt.hide();for(var l="<option><\/option>",e=0,b=!1,e=0;e<i.options.length;e++){if(l+=i.options[e].score!==undefined?"<option score='"+i.options[e].score+"' value=\""+i.options[e].text+'" ':i.options[e].text!==undefined?'<option value="'+i.options[e].text+'" ':'<option value="'+i.options[e]+'" ',t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),i.options[e].text!==undefined?s.answer!==undefined&&$.trim(s.answer.toUpperCase())===$.trim(i.options[e].text.toUpperCase())&&(l+="selected='selected' "):s.answer!==undefined&&$.trim(s.answer.toUpperCase())===$.trim(i.options[e].toUpperCase())&&(l+="selected='selected' ")}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Single Select.)"),console.error(dr),b=!0)}l+=i.options[e].text!==undefined?">"+i.options[e].text+"<\/option>":">"+i.options[e]+"<\/option>"}ft.html(l),i.useFilterSelect!==undefined&&i.useFilterSelect&&ft.select2({width:"20em"}),ft.change(function(){var c=$(this).val(),h="",s,r,e,i,t;$(this).find("option").each(function(){$(this).val().toString()===c&&(h=$.trim($(this).text()))});var a={answer:$.trim($(this).val())},l=$(this).parents("li").data("formcontrol-id"),n=f(l);if(n.plainTextValue=h,n.controlValue=JSON.stringify(a),n.isDirty=!0,s=$(this).parents("li").find(".js-control-value-violation").val(),s!==""&&(r=JSON.parse(s),e=!1,r.answer!==undefined)){for(i=0;i<r.answer.length;i++)r.answer[i].toUpperCase()===h.toUpperCase()&&($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),e=!0);e||($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null,$(o).find(".js-violation-date").val(""))}t=$.trim($(this).find("option:selected").attr("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)})}break;case"categorysingleselect.html":var ir=$(".js-category-select-list-categories",o),l=$(".js-category-select-list-options",o),sr=$(".js-category-select-list-options-all",o);ir.change(function(){var r=$(this).val(),t,e,i;l.val("");var u={category:"",text:""},o=$(this).parents("li").data("formcontrol-id"),n=f(o);n.plainTextValue="",n.controlValue=JSON.stringify(u),n.isDirty=!0,t=$(this).parents("li").find(".js-control-value-violation").val(),t!==""&&($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null),d(n),v(),r===""?($(l).html(sr.html()),l.select2({width:"20em",placeholder:"Select an option",allowClear:!0})):(e="",i=$("optgroup[label='"+r+"']",sr),$(l).html(i[0].outerHTML),l.select2({width:"20em",placeholder:"Select an option",allowClear:!0}))});l.on("change",function(){var r="",e="",c=$("option:selected",l),h,t,s,i;c.length>0&&(r=$(c).attr("category"),e=$(c).attr("text"));var v={category:r,text:e},a=$(this).parents("li").data("formcontrol-id"),n=f(a);if(n.plainTextValue=r+": "+e,n.controlValue=JSON.stringify(v),n.isDirty=!0,h=$(this).parents("li").find(".js-control-value-violation").val(),h!==""&&(t=JSON.parse(h),s=!1,t.answer!==undefined)){for(i=0;i<t.answer.length;i++)t.answer[i].category===r&&t.answer[i].text===e&&($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),s=!0);s||($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null,$(o).find(".js-violation-date").val(""))}u(n,0)});var di="<option value=''>(All)<\/option>",at="",b=!1;for(a=0;a<i.categories.length;a++){for(di+='<option value="'+i.categories[a]+'" ',at+="<optgroup label='"+i.categories[a]+"'>",e=0;e<i.options.length;e++)if(i.options[e].category===i.categories[a]){if(at+='<option value="'+e+'" category="'+i.options[e].category+'" text="'+i.options[e].text+'" ',t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),s.category!==undefined&&s.category===i.options[e].category&&s.text!==undefined&&s.text===i.options[e].text&&(at+="selected='selected' ")}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Single Select.)"),console.error(dr),b=!0)}at+=">"+i.options[e].text+"<\/option>"}if(t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),s.category!==undefined&&s.category===i.categories[a]&&(di+="selected='selected' ",selectedCategory=s.category)}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Single Select.)"),console.error(dr),b=!0)}di+=">"+i.categories[a]+"<\/option>",at+="<\/optgroup>"}ir.html(di),l.html(at),sr.html(at),l.select2({width:"20em",placeholder:"Select an option",allowClear:!0}),ir.select2({width:"20em"});break;case"multiselect.html":if(nr=$(".js-checkbox",o),ft=$(".js-select-list",o),i.useCheckboxes!==undefined&&i.useCheckboxes){ft.hide();for(var ht="",e=0,b=!1,e=0;e<i.options.length;e++){if(it="<label for='"+c+"_"+e.toString()+"'>",it+=i.options[e].score!==undefined?"<input type='checkbox' name='"+c+"' score='"+i.options[e].score+"' id='"+c+"_"+e.toString()+"' value=\""+i.options[e].text+'" ':i.options[e].text!==undefined?"<input type='checkbox' name='"+c+"' id='"+c+"_"+e.toString()+"' value=\""+i.options[e].text+'" ':"<input type='checkbox' name='"+c+"' id='"+c+"_"+e.toString()+"' value=\""+i.options[e]+'" ',t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{for(s=JSON.parse(t.controlValue),bt=0,bt=0;bt<s.answer.length;bt++)if(i.options[e].text!==undefined){if($.trim(s.answer[bt].toUpperCase())===$.trim(i.options[e].text.toUpperCase())){it+="checked='checked' ";break}}else if($.trim(s.answer[bt].toUpperCase())===$.trim(i.options[e].toUpperCase())){it+="checked='checked' ";break}}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Multi-Select.)"),b=!0)}ct==="false"&&(it+="disabled='disabled' "),it+="/> ",it+=i.options[e].text!==undefined?i.options[e].text+"<\/label>":i.options[e]+"<\/label>",ht+=e%2==0?"<tr><td>"+it+"<\/td>":"<td>"+it+"<\/td><\/tr>"}i.options.length>0&&i.options.length%2!=0&&(ht+="<td><\/td><\/tr>"),nr.find("tbody").html(ht);nr.on("change","input",function(){for(var r=$(this).parents("tbody").find(":checked"),c=[],t=0,a="",i=0,v,y,s,l,e,h,t=0;t<r.length;t++)c.push($(r[t]).val()),a+=t>0?", "+$.trim($(r[t]).parent().text()):$.trim($(r[t]).parent().text()),v=$(r[t]).attr("score"),v&&(i+=parseFloat(v));var p={answer:c},w=$(this).parents("li").data("formcontrol-id"),n=f(w);if(n.plainTextValue=a,n.controlValue=JSON.stringify(p),n.isDirty=!0,y=$(this).parents("li").find(".js-control-value-violation").val(),y!==""&&(s=JSON.parse(y),l=!1,s.answer!==undefined)){for(e=0;e<s.answer.length;e++)for(h=0;h<c.length;h++)$.trim(s.answer[e].toUpperCase())===$.trim($(this).parents("table").find("input[value='"+c[h]+"']").parent().text().toUpperCase())&&($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),l=!0);l||($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,$(o).find(".js-violation-date").val(""),n.violationDeterminedDate=null)}i!==undefined&&i!==null&&i!=="null"?u(n,i):u(n,0)})}else{for(nr.hide(),l="<option><\/option>",e=0,e=0;e<i.options.length;e++)l+=i.options[e].score!==undefined?'<option value="'+i.options[e].text+" score='"+i.options[e].score+"' \">"+i.options[e].text+"<\/option>":i.options[e].text!==undefined?'<option value="'+i.options[e].text+"' \">"+i.options[e].text+"<\/option>":'<option value="'+i.options[e]+'">'+i.options[e]+"<\/option>";if(ft.html(l),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),ft.val(s.answer)}catch(dr){b||(alert("Error rendering an answer in this section.  (Form Control Type is Multi-Select.)"),b=!0)}ft.on("change",function(){for(var l="",y=$(this),a=$(this).val(),h,e,s,r,i,t=0;t<a.length;t++)t>0&&(l+=","),l+=a[t];var c={answer:$(this).val()},v=$(this).parents("li").data("formcontrol-id"),n=f(v);if(n.plainTextValue=l,n.controlValue=JSON.stringify(c),n.isDirty=!0,h=$(this).parents("li").find(".js-control-value-violation").val(),h!==""&&(e=JSON.parse(h),s=!1,e.answer!==undefined)){for(r=0;r<e.answer.length;r++)for(i=0;i<c.answer.length;i++)e.answer[r].toUpperCase()===c.answer[i].toUpperCase()&&($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY")),s=!0);s||($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null,$(o).find(".js-violation-date").val(""))}u(n,0)})}break;case"formattedtext.html":if(ri=$(".js-formatted-text-answer",o),app.convertToAutoSize(ri),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),ri.val(s.answer)}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Text Paragraph.)")}ri.on("change",function(){var e={answer:$.trim($(this).val())},s=$(this).parents("li").data("formcontrol-id"),n=f(s),i,r,t;n.plainTextValue=$.trim($(this).val()),n.controlValue=JSON.stringify(e),i=$(this).parents("li").find(".js-control-value-violation").val(),i!==""&&(r=JSON.parse(i),e.answer.toUpperCase().indexOf(r.answer.toUpperCase())>=0?($(this).parents("li").find(".ui-icon-violation-set").show(),$(this).parents("li").find(".violation-section").removeClass("hide-control"),n.isAnswerViolation=!0,n.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(o).find(".js-violation-date").val(moment(n.violationDeterminedDate).format("M/D/YYYY"))):($(this).parents("li").find(".ui-icon-violation-set").hide(),$(this).parents("li").find(".violation-section").addClass("hide-control"),n.isAnswerViolation=!1,n.violationDeterminedDate=null,$(o).find(".js-violation-date").val(""))),n.isDirty=!0,n.plainTextValue.length>0?(t=$.trim($($(this).parents("li")[0]).data("score")),t!==undefined&&t!==null&&t!=="null"&&t!==""?u(n,t):u(n,0)):u(n,0)});$(ri).resize(),$(window).resize();break;case"table.html":tt=$(".js-table-answer",o),i.canAddRows!==!1&&ct||$(".js-add-row-button",o).hide(),ti=$(".js-add-row-button",$(tt).parent()),ti.button({text:!0,icons:{primary:"ui-icon-add"}});var lr=$(tt).find("tr"),pt=$(tt).find("tbody"),h=0;for(i.collumns!==undefined&&i.collumns!==null&&(i.columns=i.collumns),h=0;h<i.columns.length;h++)nt="",nt=i.columns[h].name!==undefined&&i.columns[h]!==null?i.columns[h].name:i.columns[h],i.columns[h].isRequired&&(nt+=" <span style='color:red;'>*<\/span>"),et="",et=i.columns[h].justification==="Left"?i.columns[h].width!==undefined&&i.columns[h].width!==null&&i.columns[h].width.length>0?"<th class='js-table-justify-left' style='width:"+i.columns[h].width+"%'>"+nt+"<\/th>":"<th class='js-table-justify-left'>"+nt+"<\/th>":i.columns[h].justification==="Center"?i.columns[h].width!==undefined&&i.columns[h].width!==null&&i.columns[h].width.length>0?"<th class='js-table-justify-center' style='width:"+i.columns[h].width+"%'>"+nt+"<\/th>":"<th class='js-table-justify-center'>"+nt+"<\/th>":i.columns[h].justification==="Right"?i.columns[h].width!==undefined&&i.columns[h].width!==null&&i.columns[h].width.length>0?"<th class='js-table-justify-right' style='width:"+i.columns[h].width+"%'>"+nt+"<\/th>":"<th class='js-table-justify-right'>"+nt+"<\/th>":i.columns[h].width!==undefined&&i.columns[h].width!==null&&i.columns[h].width.length>0?"<th class='js-table-justify-left' style='width:"+i.columns[h].width+"%'>"+nt+"<\/th>":"<th class='js-table-justify-left'>"+nt+"<\/th>",$(lr).append(et);if(i.canDeleteRows!==!1&&ct.toUpperCase()!=="FALSE"&&$(lr).append("<th class='table-delete'><\/th>"),kt){t=f(c),kt=!0;var yi="",vi=[],pr=i.options;for(g=0;g<pr.length;g++)if(pr[g].length>0){for(vi[g]=[],h=i.columns.length,vi[g][0]=i.options[g],yi+=i.options[g],si=1;si<h;si++)vi[g][si]="",yi+=",";yi+="\r\n"}wr={answer:vi},t.plainTextValue=yi,t.controlValue=JSON.stringify(wr),u(t,0),$("#Questions").unblock()}if(t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!==""){try{for(s=JSON.parse(t.controlValue),g=0,g=0;g<s.answer.length;g++){for(ii="<tr>",h=0,h=0;h<s.answer[g].length&&h<i.columns.length;h++)ei=s.answer[g][h],ei===null&&(ei=""),ii+=ct.toUpperCase()=="TRUE"?ni(i.columns[h],ei,!0):ni(i.columns[h],ei,!1);i.canDeleteRows!==!1&&ct.toUpperCase()!=="FALSE"&&(ii+="<td class='table-delete'><button class='js-delete-button'>Delete<\/button><\/td>"),ii+="<\/tr>",$(pt).append(ii)}pt.find(".js-col-date").datepicker({buttonImage:app.vroot()+"Content/images/calendar.png",altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0})}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Table.)")}pt.find(".js-delete-button").button({text:!1,icons:{primary:"ui-icon-trash"}})}ti.on("click",function(){var u=$("table",$(this).parent()),i=u.find("tbody"),r=$(".js-control-definition",$(this).parents("li")).val(),n,t;for(r!==""&&(addControlDefinition=JSON.parse(r),addControlDefinition.collumns!==undefined&&addControlDefinition.collumns!==null&&(addControlDefinition.columns=addControlDefinition.collumns)),n="<tr>",t=0;t<addControlDefinition.columns.length;t++)n+=ni(addControlDefinition.columns[t],addControlDefinition.columns[t].defaultValue,!0);return addControlDefinition.canDeleteRows!==!1&&(n+="<td class='table-delete'><button class='js-delete-button'>Delete<\/button><\/td>"),n+="<\/tr>",i.append(n),i.find("tr:last").find(".js-delete-button").button({text:!1,icons:{primary:"ui-icon-trash"}}),i.find("tr:last").find(".js-col-date").datepicker({buttonImage:app.vroot()+"Content/images/calendar.png",altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),i.find("tr:last").find(".js-col-answer:first").focus(),!1});pt.on("click",".js-delete-button",function(){var c=$(this).parents("li").data("formcontrol-id"),h=$(this).parent().parent().parent().parent().parent(),e,i;$($(this).parents("tr")[0]).remove();var o=$(h).parent().find("tr"),r=[],s="",t="";$(o).each(function(){$(this).find("th").not(".table-delete").each(function(n){n>0?t+=", "+$.trim($(this).html()):t=$.trim($(this).html())})}),t!==""&&(t+="\r\n"),$(o).not(":first").each(function(n){r[n]=[],$(this).find("td").not(".table-delete").each(function(i){var f="",u=$(this).find(".js-col-answer"),e,o;u.length===0&&(u=$($(this).children()[0])),f=u.is(".js-col-text")?$.trim(u.val()):u.is(".js-col-comment")?$.trim(u.val()):u.is(".js-col-number")?$.trim(u.val()):u.is(".js-col-date")?$.trim(u.val()):u.is(".js-col-time")?$.trim(u.val()):u.is(".js-col-checkbox")?u.is(":checked")?"true":"false":$.trim(u.text()),r[n][i]=f,e=f.replace(/&quot;/g,'"').replace(/,/g,"&comma;"),o="",e.indexOf('"')>-1&&e+"'"+e+"'",e.indexOf(",")>-1&&e+"'"+e+"'",i>0?o+=", "+e:o=e,t+=o}),t!==""&&(t+="\r\n"),s+=t,t=""}),e={answer:r},i=f(c),i.plainTextValue=s,i.controlValue=JSON.stringify(e),i.isDirty=!0,u(i,0)});pt.on("keypress","textarea",function(n){if(n.keyCode===13)return!1});pt.on("change",".js-col-answer",function(){var o=$(this).parent().parent().parent(),e=$(o).parent().find("tr"),i=[],r="",n="";$(e).each(function(){$(this).find("th").not(".table-delete").each(function(t){t>0?n+=","+$.trim($(this).html()):n=$.trim($(this).html())})}),n!==""&&(n+="\r\n"),$(e).not(":first").each(function(t){i[t]=[],$(this).find("td").not(".table-delete").each(function(r){var f="",u=$(this).find(".js-col-answer"),e,o;u.length===0&&(u=$($(this).children()[0])),f=u.is(".js-col-text")?$.trim(u.val()):u.is(".js-col-comment")?$.trim(u.val()):u.is(".js-col-number")?$.trim(u.val()):u.is(".js-col-date")?$.trim(u.val()):u.is(".js-col-time")?$.trim(u.val()):u.is(".js-col-checkbox")?u.is(":checked")?"true":"false":$.trim(u.text()),i[t][r]=f,e=f.replace(/&quot;/g,'"').replace(/,/g,"&comma;"),o="",e.indexOf('"')>-1&&e+"'"+e+"'",e.indexOf(",")>-1&&e+"'"+e+"'",r>0?o+=", "+e:o=e,n+=o}),n!==""&&(n+="\r\n"),r+=n,n=""});var h={answer:i},s=$(this).parents("li").data("formcontrol-id"),t=f(s);t.plainTextValue=r,t.controlValue=JSON.stringify(h),t.isDirty=!0,u(t,0)});break;case"location.html":if(ur=$(".js-location-latitude-longitude",o),fr=$(".js-location-detect",o),fr.button(),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{s=JSON.parse(t.controlValue),ur.val(s.latitude+","+s.longitude)}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is GPS Location.)")}fr.on("click",function(){if(navigator.geolocation){rt=$(this).parents("li");var n=null;n=navigator.userAgent.toUpperCase().indexOf("ANDROID")>=0&&navigator.userAgent.toUpperCase().indexOf("CHROME")>=0?{enableHighAccuracy:!0,maximumAge:1e3,timeout:6e4}:{enableHighAccuracy:!0,maximumAge:0,timeout:6e4},navigator.geolocation.getCurrentPosition(li,pi,n)}return!1});ur.on("change",function(){var t=$(this).val(),i=null,r,n;t===""?i=null:t.indexOf(",")>0?i={latitude:t.split(",")[0],longitude:t.split(",")[1]}:(alert("Invalid data entered for GPS control"),t=null),r=$(this).parents("li").data("formcontrol-id"),n=f(r),n.plainTextValue=t,n.controlValue=i?JSON.stringify(i):null,n.isDirty=!0,u(n,0)});break;case"signature.html":if(wi=$(".js-signature-capture",o),ki=$(".js-signature-sync",o),wi.signature({guideline:!0,guidelineOffset:25,disabled:!0,syncField:ki,color:"black"}),t!==null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!==""&&t.plainTextValue!=="Mobile Signature")try{s=JSON.parse(t.controlValue),wi.signature("draw",JSON.parse(s.answer)),wi.signature("disable")}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Signature.)")}$(".js-signature-button",o).button({text:!0}),$(".js-signature-button",o).click(function(){var t=$(this).parent().find(".js-signature-capture");if(t.signature("option","disabled"))t.signature("clear"),t.signature("enable"),$(this).find("span").text("Done");else{t.signature("disable");var e=$(this).parents("li").data("formcontrol-id"),n=f(e),r=$(this).parent().find(".js-signature-sync").val(),i={answer:r};n.plainTextValue="Web Signature",n.controlValue=JSON.stringify(i),n.isDirty=!0,u(n,0),$(this).find("span").text("Start Signing")}});break;case"drawing.html":if(gi=$(".js-drawing-capture",o),ki=$(".js-drawing-sync",o),gi.signature({guideline:!1,disabled:!0,syncField:ki,color:"black"}),t!==null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!==""&&t.plainTextValue!=="Mobile Drawing")try{s=JSON.parse(t.controlValue),s.answer.length>0&&gi.signature("draw",JSON.parse(s.answer)),gi.signature("disable")}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is Drawing.)")}$(".js-drawing-button",o).button({text:!0}),$(".js-clear-drawing-button",o).button({text:!0}),$(".js-drawing-button",o).click(function(){var t=$(this).parent().find(".js-drawing-capture");if(t.signature("option","disabled"))t.signature("enable"),$(this).find("span").text("Done");else{t.signature("disable");var e=$(this).parents("li").data("formcontrol-id"),n=f(e),r=$(this).parent().find(".js-drawing-sync").val(),i={answer:r};n.plainTextValue="Web Drawing",n.controlValue=JSON.stringify(i),n.isDirty=!0,u(n,0),$(this).find("span").text("Start Drawing")}}),$(".js-clear-drawing-button",o).click(function(){var n=$(this).parent().find(".js-drawing-capture");n.signature("clear")});break;case"locationtable.html":if(tt=$(".js-location-table-answer",o),ti=$(".js-add-row-button",$(tt).parent()),ti.button({text:!0,icons:{primary:"ui-icon-add"}}),lr=$(tt).find("tr"),pt=$(tt).find("tbody"),t!=null&&t.controlValue!==undefined&&t.controlValue!==null&&t.controlValue!=="")try{for(s=JSON.parse(t.controlValue),k=0;k<s.answer.length;k++){for(or=tt.find("tbody"),o="",o="<tr>",o+="<td>",o+="<select class='js-location-description'>",o+="<option value=''><\/option>",e=0;e<i.options.length;e++)o+="<option value='"+i.options[e]+"' ",i.options[e]===s.answer[k].Description&&(o+="selected='selected'"),o+=">"+i.options[e]+"<\/option>";o+="<\/select>",o+="<\/td>",o+="<td><input type='text' class='js-location-latlong lat-long-textbox' disabled='disabled' ",o+="value='"+s.answer[k].Location+"' ",o+="/><\/td>",o+="<td><button class='js-delete-button'>Delete<\/button><\/td>",o+="<\/tr>",or.append(o),or.find("tr:last").find(".js-delete-button").button({text:!1,icons:{primary:"ui-icon-trash"}})}window.loadMap(t)}catch(dr){alert("Error rendering an answer in this section.  (Form Control Type is GPS Location Table.)")}ti.click(function(){var r=$("table",$(this).parent()),u=r.find("th").length,t=r.find("tbody"),n;for(n="<tr>",n+="<td>",n+="<select class='js-location-description'>",n+="<option value=''><\/option>",e=0;e<i.options.length;e++)n+="<option value='"+i.options[e]+"' ",n+=">"+i.options[e]+"<\/option>";return n+="<\/select>",n+="<\/td>",n+="<td><input type='text' class='js-location-latlong lat-long-textbox' disabled='disabled' /><\/td>",n+="<td><button class='js-delete-button'>Delete<\/button><\/td>",n+="<\/tr>",t.append(n),t.find("tr:last").find(".js-delete-button").button({text:!1,icons:{primary:"ui-icon-trash"}}),navigator.geolocation&&($(this).attr("disabled","disabled"),st=$(this).parents("li"),options=navigator.userAgent.toUpperCase().indexOf("ANDROID")>=0&&navigator.userAgent.toUpperCase().indexOf("CHROME")>=0?{enableHighAccuracy:!0,maximumAge:1e3,timeout:6e4}:{enableHighAccuracy:!0,maximumAge:0,timeout:6e4},navigator.geolocation.getCurrentPosition(ai,ui,options)),!1}),tt.delegate(".js-delete-button","click",function(){var h=$(this).parents("table"),o=$(this).parents("li").data("formcontrol-id");$(this).parents("tr").remove();for(var e=[],n=0,t=$("tr",tt),r="",n=0;n<t.length;n++)n!==0&&(e.push({Description:$(".js-location-description",t[n]).val(),Location:$(".js-location-latlong",t[n]).val()}),n>0&&(r+="\r\n"),r+=$(".js-location-description",t[n]).val()+',"'+$(".js-location-latlong",t[n]).val()+'"');var i=f(o),c=e,s={answer:e};i.plainTextValue=r,i.controlValue=JSON.stringify(s),i.isDirty=!0,u(i,0),window.loadMap(i)}),tt.delegate(".js-location-description","change",function(){for(var s=$(this).parents("tbody"),e=[],n=0,t=$("tr",s),r="",n=0;n<t.length;n++)e.push({Description:$(".js-location-description",t[n]).val(),Location:$(".js-location-latlong",t[n]).val()}),n>0&&(r+="\r\n"),r+=$(".js-location-description",t[n]).val()+',"'+$(".js-location-latlong",t[n]).val()+'"';var h=$(this).parents("li").data("formcontrol-id"),i=f(h),c=r,o={answer:e};i.plainTextValue=r,i.controlValue=JSON.stringify(o),i.isDirty=!0,u(i,0),window.loadMap(i)}),ci||(ci=!0,tr=document.createElement("script"),tr.type="text/javascript",tr.src="https://maps-api-ssl.google.com/maps/api/js?key=AIzaSyCnUTY4LtX5jCkOKrj8fl2fNgffp-BGR-s&sensor=true&callback=initMap",document.body.appendChild(tr))}},yi=function(n){$(rt).find(".js-gps-latlong-answer").val(n.coords.latitude+","+n.coords.longitude);var i=$(rt).parents("li").data("formcontrol-id"),t=f(i);t.latitude=n.coords.latitude.toString(),t.longitude=n.coords.longitude.toString(),t.isDirty=!0,d(t),v()};var ui=function(){alert("Could not determine GPS Location, this can happen if you have GPS disabled on your device or are in airplane mode")},li=function(n){$(rt).find(".js-location-latitude-longitude").val(n.coords.latitude+","+n.coords.longitude);var r=$(rt).data("formcontrol-id"),t=f(r),i={latitude:n.coords.latitude.toString(),longitude:n.coords.longitude.toString()};return t.plainTextValue=n.coords.latitude+","+n.coords.longitude,t.controlValue=JSON.stringify(i),t.isDirty=!0,u(t,0),!1},pi=function(){alert("Could not determine GPS Location, this can happen if you have GPS disabled on your device or are in airplane mode")},w=function(n,t,i){Wndsr.error("Failed getting data, textStatus = "+t+", errorThrown = "+i),$.unblockUI()},gi=function(){var i,t;$.blockUI(),i=Wndsr.getUrlParam("inspectionId"),i===undefined&&(p=!0),t=Wndsr.getUrlParam("formVersionId"),h=Wndsr.getUrlParam("formSectionId"),s=Wndsr.getUrlParam("sectionIndex"),app.persist.getFormVersion(t,function(u){app.persist.getForm(u.formId,function(f){app.persist.getFormSectionsByFormVersionId(t,function(o){app.persist.getFormControlsByFormVersionId(t,function(s){e=u,bt=f,e.sortedFormSections=o.sort(function(n,t){return n.sectionSortOrder-t.sectionSortOrder});for(var h=0;h<e.sortedFormSections.length;h++)e.sortedFormSections[h].sortedFormControls=s.filter(function(n){return n.formSectionId===e.sortedFormSections[h].id}).sort(function(n,t){return n.questionNumber===t.questionNumber?n.questionLetter<t.questionLetter?-1:n.questionNumber>t.questionNumber?1:0:n.questionNumber-t.questionNumber});p?(r={},r.id="0",r.site={},r.siteKey="Preview",r.inspectionForms=[],n=new InspectionForm,n.inspectionId=0,n.New(i,t),r.inspectionForms.push(n),r.isDirty=!0,n.Initialize(function(){hi(function(){fi(),$.unblockUI()},w)},app.getDataFailed)):Inspection.Load(i,function(i){r=i,n=r.inspectionForms.find(function(n){return n.formVersionId===t&&n.isActive&&!n.isDeleted}),hi(function(){fi()},w)},w)},w)},w)},w)},w)},fi=function(){$("title").text(bt.name),$("#InspectionFormActions").menu(),p||app.displayForms(r),p&&($("#RemoveInspectionForm").remove(),$("#ShowViolations").remove(),$(".generateReport").remove(),$("#SlideUpFormsButton").remove(),$("#SlideUpMoreButton").remove());$("#SlideUpFormsButton").on("click",function(){var i,t,f,u;if($(this).is(".ui-active"))$("#FormNavigation").hide(),$("#SlideUpFormsButton").removeClass("ui-active"),$("#Questions").show(),$("#PreviousSectionButton").show(),$("#NextSectionButton").show(),$("#SectionChooser").show(),$("#SlideUpMoreButton").show(),o.repeatingSectionsCount>=0&&($("#RepeatingSectionButton").show(),$("#AddSectionButton").show());else{for($.blockUI(),$("#RepeatingSectionDialog").hide(),i=$("h3[data-formversion-id="+e.id+"]","#CurrentForms"),$("#CurrentForms h3, #AdditionalForms h3").not(i).each(function(){$(this).children("span").removeClass("ui-expanded-accordion").addClass("ui-collapsed-accordion"),$(this).children("a").removeClass("ui-accordion-title-text-expanded").addClass("ui-accordion-title-text-collapsed"),$(this).removeClass("ui-accordion-title-expanded").addClass("ui-accordion-title-collapsed"),$(this).next().hide()}),$(i).children("span").removeClass("ui-collapsed-accordion").addClass("ui-expanded-accordion"),$(i).children("a").removeClass("ui-accordion-title-text-collapsed").addClass("ui-accordion-title-text-expanded"),$(i).removeClass("ui-accordion-title-collapsed").addClass("ui-accordion-title-expanded"),$(i).next().show(),$("h3[data-formversion-id="+e.id+"]").removeClass("invalidForm").next().find(".invalidSection").removeClass("invalidSection"),n.score?$("a[data-formversion-id="+e.id+"]").text(bt.name+" ("+n.score.toFixed(2)+")"):$("a[data-formversion-id="+e.id+"]").text(bt.name),t=[],f=0;f<r.inspectionForms.length;f++)t=t.concat(t,r.inspectionForms[f].inspectionFormSections.filter(function(n){return n.hasMissingAnswer&&n.isVisible}));for(u=0;u<t.length;u++)$("li[data-formsection-id="+t[u].formSectionId+"]").addClass("invalidSection"),$("li[data-formsection-id="+t[u].formSectionId+"]").parent().parent().prev().addClass("invalidForm");app.showRepeatingSectionsWithTableData(n,e,function(n){for(var t,r,i=0;i<n.length;i++){var s=n[i].id,u=n[i].table,o="",f=$("li[data-formsection-id="+s+"]").find("a");for(t=0;t<e.sortedFormSections.length;t++)e.sortedFormSections[t].id===s&&(o=e.sortedFormSections[t].sectionTitle);$(f).text(o),$(f).parent().find("table").remove(),u!==""&&(r=$(document.createElement("table")),$(r).addClass("action-table").html(u),$(r).addClass("action-table").addClass("repeatingSectionTable").html(u),$(f).after(r))}$("#FormNavigation").show(),$("#SlideUpFormsButton").addClass("ui-active"),$("#Questions").hide(),$("#PreviousSectionButton").hide(),$("#NextSectionButton").hide(),$("#SectionChooser").hide(),$("#SlideUpMoreButton").hide(),$("#RepeatingSectionButton").hide(),$("#AddSectionButton").hide(),window.scrollTo(0,0),$.unblockUI()})}return!1});$("#SlideUpMoreButton").on("click",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#InspectionFormActions").hide();else{app.isOnline?$(".generatePDFOption").show():$(".generatePDFOption").hide(),$(this).addClass("ui-active"),$("#InspectionFormActions").show();$("html").on("click",function(){$(this).is("#InspectionFormActions")||$("#InspectionFormActions").has($(this)).length!==0||($("#SlideUpMoreButton").removeClass("ui-active"),$("#InspectionFormActions").hide(),$("html").off("click"))})}return!1});$("#RemoveInspectionForm").on("click",function(){var t=confirm("Delete this Inspection Form?");t&&($.blockUI(),n.isDeleted=!0,n.isDirty=!0,r.isDirty=!0,v(!0,function(){window.location.href=app.vroot()+"FormVersion?inspectionId="+r.id}),$("#SlideUpMoreButton").removeClass("ui-active"),$("#InspectionFormActions").hide())});$("#ShowAllComments").on("click",function(){$("#Questions").find("li").each(function(){var n=$(this).find(".question-comment");n.find("textarea").val()!==""&&g($(this))}),$("#SlideUpMoreButton").removeClass("ui-active"),$("#InspectionFormActions").hide()});$("#ShowViolations").on("click",function(){$("#SlideUpMoreButton").removeClass("ui-active"),$("#InspectionFormActions").hide(),window.location=app.vroot()+"Inspection/ViolationList?inspectionId="+r.id+"&formVersionId="+e.id+"&formSectionId="+h});$(".generateReport").on("click",function(){var i=(new Date).getTimezoneOffset(),t=$(this).data("reportType");window.location.href=app.vroot()+"Report/GetReport?id="+n.id+"&inspectionId="+r.id+"&curDateOffset="+i+"&reportType="+t});$("#FormActions").menu();$("#Questions").on("click",".js-question-toolbar-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#FormActions").hide();else{var n=$(this).parent().parent().data("formcontrol-id");$(".js-question-toolbar-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#FormActions").css("top",$(this).offset().top+$(this).height()),$("#FormActions").data("formcontrol-id",n),$("#FormActions").show();$("html").on("click",function(){$(this).is("#FormActions")||$("#FormActions").has($(this)).length!==0||($(".js-question-toolbar-button").removeClass("ui-active"),$("#FormActions").hide(),$("html").off("click"))})}return!1});$("#FormMarkViolation").on("click",function(){var h=$("#FormActions").data("formcontrol-id"),i=$("li[data-formcontrol-id="+h+"]","#Questions"),c=$(i).find(".js-control-iscreateviolationvalue").val(),l=$(i).find(".js-question-reference").val(),o="false",e,u,s;return c.toLowerCase()==="true"&&(o="true"),o!=="true"&&(o="false"),e=$(i).find(".js-control-value-violation").val(),o.toLowerCase()==="true"&&(e===""||e===undefined||e===null)?(u=f(h),u.isAnswerViolation?(u.isAnswerViolation=!1,u.violationDeterminedDate=null,$(i).find(".js-violation-date").val(""),i.find(".violation-section").addClass("hide-control"),i.find(".ui-icon-violation-set").hide(),t.isDirty=!0,u.isDirty=!0,n.isDirty=!0,r.isDirty=!0,d(u),v()):(u.isAnswerViolation=!0,u.violationDeterminedDate=(new moment).format("M/D/YYYY"),$(i).find(".js-violation-date").val(moment(u.violationDeterminedDate).format("M/D/YYYY")),i.find(".violation-section").removeClass("hide-control"),i.find(".ui-icon-violation-set").show(),t.isDirty=!0,u.isDirty=!0,n.isDirty=!0,r.isDirty=!0,d(u),v()),g(i)):e!==""?(s=confirm("This is marked or unmarked as "+$("#ViolationPhraseSingular").val()+" automatically based on the answer entered"),s&&g(i)):(s=$("#IsDebugMessages").val()==="True"?confirm("A comment may be entered, but this cannot be marked as "+$("#ViolationPhraseSingular").val()+".\r\nFormControlId = "+h+"\r\nIsCreateViolation = "+c+"\r\nQuestionReference = "+l+"\r\nIsCreateViolationValid = "+o+"\r\ncanMarkAsViolation = "+o+"\r\ncontrolValueViolation = "+e):confirm("A comment may be entered, but this cannot be marked as "+$("#ViolationPhraseSingular").val()+"."),s&&g(i)),$(".js-question-toolbar-button",i).removeClass("ui-active"),$("#FormActions").hide(),!1});$("#FormComment").on("click",function(){var t=$("#FormActions").data("formcontrol-id"),n=$("li[data-formcontrol-id="+t+"]","#Questions");return g(n),$("textarea",n).focus(),$(".js-question-toolbar-button",n).removeClass("ui-active"),$("#FormActions").hide(),!1});$("#FormPhoto").on("click",function(){var t=$("#FormActions").data("formcontrol-id"),n=$("li[data-formcontrol-id="+t+"]","#Questions");return g(n),$(".js-question-toolbar-button",n).removeClass("ui-active"),$("#FormActions").hide(),!1});$("#FormGPS").on("click",function(){var t=$("#FormActions").data("formcontrol-id"),n=$("li[data-formcontrol-id="+t+"]","#Questions"),i=navigator.userAgent.toLowerCase();return navigator.geolocation&&(rt=$(n).find(".gps-section"),options=navigator.userAgent.toUpperCase().indexOf("ANDROID")>=0&&navigator.userAgent.toUpperCase().indexOf("CHROME")>=0?{enableHighAccuracy:!0,maximumAge:1e3,timeout:6e4}:{enableHighAccuracy:!0,maximumAge:0,timeout:6e4},navigator.geolocation.getCurrentPosition(yi,ui,options)),$(n).find(".ui-icon-gps-set").removeClass("hide-control"),$(n).find(".gps-section").removeClass("hide-control"),g(n),$(".js-question-toolbar-button",n).removeClass("ui-active"),$("#FormActions").hide(),!1});$("#FormAudio").on("click",function(){return alert("Record audio is currently not supported"),$(".js-question-toolbar-button",row).removeClass("ui-active"),$("#FormActions").hide(),!1});$("#Questions").on("change",".js-answer-comment",function(){var e=$(this).parents("li").data("formcontrol-id"),r=$(this).val(),t=$(this).parent().parent().parent().find(".js-answer-recommendation-comment").val(),n=f(e),i=$(this).parents(".question-thread").prev().find(".ui-icon-comment-set").removeClass("hideControl");n.answerComment=r,r.length>0||t!==undefined&&t!==null&&t.length>0?i.show():i.hide(),n.isDirty=!0,u(n,n.score)});$("#Questions").on("change",".js-answer-recommendation-comment",function(){var r=$(this).parents("li").data("formcontrol-id"),t=$(this).val(),e=$(this).parent().parent().parent().find(".js-answer-comment").val(),n=f(r),i=$(this).parents(".question-thread").prev().find(".ui-icon-comment-set").removeClass("hideControl");n.recommendationComment=t,e.length>0||t!==undefined&&t!==null&&t.length>0?i.show():i.hide(),n.isDirty=!0,u(n,n.score)});$("#Questions").on("change",".js-image-capture",function(t){var o,s,u,r,e,h;try{for(o=$(this).parents("li").data("formcontrol-id"),s=t.target.files,u=0;r=s[u];u++)if(r.type.match("image.*")){if(r.size>ri*1048576){alert("Images cannot exceed "+ri+"MB in size, please retry with a lower image resolution."),$(this).val("");return}return $.blockUI({message:"<h1>Please Wait<\/h1>"}),e=f(o),$(this).parents("li").find(".ui-icon-photo-set").removeClass("hide-control"),EXIF.getData(r,function(){var c=new FileReader,w=null,t=EXIF.getTag(this,"GPSLatitude"),v=EXIF.getTag(this,"GPSLatitudeRef"),a,s,f,h;t!==undefined&&t!==null&&t.length==3&&v!==undefined&&v!==null&&(w=app.convertDMSToDD(t[0].numerator/t[0].denominator,t[1].numerator/t[1].denominator,t[2].numerator/t[2].denominator,v));var b=null,u=EXIF.getTag(this,"GPSLongitude"),y=EXIF.getTag(this,"GPSLongitudeRef");u!==undefined&&u!==null&&u.length==3&&y!==undefined&&y!==null&&(b=app.convertDMSToDD(u[0].numerator/u[0].denominator,u[1].numerator/u[1].denominator,u[2].numerator/u[2].denominator,y));var p=null,o=EXIF.getTag(this,"GPSAltitude"),l=EXIF.getTag(this,"GPSAltitudeRef");o!==undefined&&o!==null&&l!==undefined&&l!==null&&(p=l===1?o.numerator/o.denominator*-1:o.numerator/o.denominator),a=null,s=EXIF.getTag(this,"GPSImgDirection"),s!==undefined&&s!==null&&(a=s.numerator/s.denominator),f=null,h=EXIF.getTag(this,"DateTimeOriginal"),f=h!==undefined&&h!==null?h:r.lastModified!==undefined&&r.lastModified!==null&&r.lastModified!==""?new moment(r.lastModified).format("YYYY:MM:DD HH:mm:ss"):r.lastModifiedDate!==undefined&&r.lastModifiedDate!==null&&r.lastModifiedDate!==""?new moment(r.lastModifiedDate).format("YYYY:MM:DD HH:mm:ss"):(new moment).format("YYYY:MM:DD HH:mm:ss"),c.onerror=function(n){Wndsr.error("ERROR - reader -"+n.target.error)},c.onload=function(){return function(t){var u=t.target.result.substring(t.target.result.indexOf(",")+1),r=t.target.result.substring(0,t.target.result.indexOf(",")+1);app.rotateImage(u,r,0).then(function(t){u=t[0].src.substring(t[0].src.indexOf(",")+1),r=t[0].src.substring(0,t[0].src.indexOf(",")+1),i(n,e,r,u,w,b,p,a,null,f)})}}(r),c.readAsDataURL(r),$.unblockUI()}),wt=$(this).parents("li").find(".js-image-output"),$.unblockUI(),!1}return h=$(this).parents(".question-thread").prev().find(".ui-icon-image-set").removeClass("hideControl"),$.unblockUI(),!1}catch(c){Wndsr.error("ERROR - reader -"+c)}});var i=function(n,i,u,f,e,o,s,h,l,a){var v,y,w;return p||(v={},v.id=app.createUUID(),v.inspectionFormId=n.id,v.inspectionFormAnswerId=i.id,v.mediaPath="",v.mediaObject=f,v.mimeType=u,v.metadataComment="",v.metaDataTags="",v.imageCapturedTime=a,v.gpsLatitude=e,v.gpsLongitude=o,v.gpsAltitude=s,v.gpsAzimuth=h,v.gpsOrientation=l,v.isDirty=!0,v.isNew=!0,v.isDeleted=!1,i.inspectionFormMedia||(i.inspectionFormMedia=[]),i.inspectionFormMedia.push(v),i.isDirty=!0,t.isDirty=!0,c&&(c.isDirty=!0),n.isDirty=!0,r.isDirty=!0,y=document.createElement("li"),w='<img class="thumbnail" id="image_'+v.id+'" title="Image" /><div><button class="js-image-info">Info<\/button><button class="js-image-delete">Delete<\/button><\/div>',y.innerHTML=w,wt[0].insertBefore(y,null),app.resizeBase64Img(f,u,100,null).then(function(n){$("#image_"+v.id).attr("src",n[0].src)}),$.data(y,"inspectionformanswer-id",i.id),$.data(y,"inspectionformmedia-id",v.id),$(".js-image-info",y).button({text:!1,icons:{primary:"ui-icon-info"}}),$(".js-image-delete",y).button({text:!1,icons:{primary:"ui-icon-close"}})),$.unblockUI(),!1};$("#Questions").on("click",".thumbnail",function(){$.blockUI({message:"<h1>Please Wait<\/h1>"}),ct=$($(this).parents("li")[0]).data("inspectionformmedia-id"),ht=$(this).parents("li").parents("li").data("formcontrol-id");var t=f(ht),n=t.inspectionFormMedia.find(function(n){return n.id===ct});app.persist.getFile(n.id,function(n,t){n&&n.data&&n.data.length>0?($("#InspectionImage").attr("src",t.mimeType+n.data),$("#ViewMediaImage").dialog("open"),$.unblockUI()):(n&&n.data==undefined&&$.unblockUI(),n&&n.id?($("#image_"+n.id).attr("src",$("#OfflineImage").attr("src")),$("#ViewMediaImage").dialog("open")):$.unblockUI())},w,n)});$("#Questions").on("click",".js-image-info",function(){$.blockUI({message:"<h1>Please Wait<\/h1>"}),ct=$($(this).parents("li")[0]).data("inspectionformmedia-id"),ht=$(this).parents("li").parents("li").data("formcontrol-id");var t=f(ht),n=t.inspectionFormMedia.find(function(n){return n.id===ct});$("#ImageDateTime").text(""),$("#ImageLatitude").text(""),$("#ImageLongitude").text(""),$("#ImageAltitude").text(""),$("#ImageAzimuth").text(""),$("#ImageOrientation").text(""),$("#ImageComments").val(""),n.imageCapturedTime!==undefined&&n.imageCapturedTime!==null&&$("#ImageDateTime").text(n.imageCapturedTime),n.gpsLatitude!==undefined&&n.gpsLatitude!==null&&$("#ImageLatitude").text(n.gpsLatitude),n.gpsLongitude!==undefined&&n.gpsLongitude!==null&&$("#ImageLongitude").text(n.gpsLongitude),n.gpsAltitude!==undefined&&n.gpsAltitude!==null&&$("#ImageAltitude").text(n.gpsAltitude+" meters"),n.gpsAzimuth!==undefined&&n.gpsAzimuth!==null&&$("#ImageAzimuth").text(n.gpsAzimuth),n.gpsOrientation!==undefined&&n.gpsOrientation!==null&&$("#ImageOrientation").text(n.gpsOrientation+" degrees"),n.metadataComment!==undefined&&n.metadataComment!==null&&$("#ImageComments").val(n.metadataComment),$("#ImageInfo").dialog("open"),$.unblockUI()});$("#Questions").on("click",".js-image-delete",function(){var i;if(confirm("Are you sure you want to delete this image?")){$.blockUI({message:"<h1>Please Wait<\/h1>"});var s=$($(this).parents("li")[0]).data("inspectionformmedia-id"),o=$($(this).parents(".js-question-item")[0]).data("formcontrol-id"),u=f(o),e=0;for(i=0;i<u.inspectionFormMedia.length;i++)u.inspectionFormMedia[i].id===s?(u.inspectionFormMedia[i].isDeleted=!0,u.inspectionFormMedia[i].isDirty=!0,u.isDirty=!0,c&&(c.isDirty=!0),t.isDirty=!0,n.isDirty=!0,r.isDirty=!0):u.inspectionFormMedia[i].isDeleted||e++;$($(this).parents("li")[0]).remove(),e===0&&$("li[data-formcontrol-id='"+o+"']").find(".ui-icon-photo-set").addClass("hide-control"),$.unblockUI()}});$("#Questions").on("click",".js-web-camera",function(){var n,i,t;return dt=$(this),n="",n='<video id="video" width="640" height="480" autoplay><\/video>',n+='<br/><button id="snap">Take Photo<\/button>',$("#TakeWebPicture").html(n),lt=$("#video")[0],i={video:!0},t=function(){$("#TakeWebPicture").dialog("close"),alert("No camera found")},navigator.getUserMedia?navigator.getUserMedia(i,function(n){lt.src=n,vt=n},t):navigator.webkitGetUserMedia&&navigator.webkitGetUserMedia(i,function(n){lt.src=window.webkitURL.createObjectURL(n),vt=n},t),$("#TakeWebPicture").dialog("open"),!1});$("html").on("click","#snap",function(){var i,o,u,e,r,s;$.blockUI({message:"<h1>Please Wait<\/h1>"}),i=document.getElementById("ghostCanvas"),o=i.getContext("2d"),o.drawImage(lt,0,0,640,480);var t=i.toDataURL(),c=$(dt).parents("li").data("formcontrol-id"),h=f(c);$(dt).parents("li").find(".ui-icon-photo-set").removeClass("hide-control"),u=t.substring(t.indexOf(",")+1),e=t.substring(0,t.indexOf(",")+1),p||app.updateInspectionFormMedia(n,h,e,u,function(){$.unblockUI()},w),r=document.createElement("li"),s='<img class="thumbnail" title="'+escape(file.name)+'" src="'+t+'"/><div><button>Info<\/button><button>Delete<\/button><\/div>',r.innerHTML=s,wt=$(dt).parents("li").find(".js-image-output"),wt[0].insertBefore(r,null),$("#TakeWebPicture").dialog("close"),$.unblockUI()});$("#Questions").on("click",".question-toolbar",function(){var n=$(this).parent().find(".question-thread"),t;n.hasClass("hide-control")?(n.removeClass("hide-control"),$(this).addClass("ui-active"),t=n.find(".question-comment").find("textarea"),app.convertToAutoSize(t),$(t).resize(),$(window).resize()):(n.addClass("hide-control"),n.removeClass("ui-active"),$(this).removeClass("ui-active")),$(window).resize()});$("#NextSectionButton").on("click",function(){for(var f,t,i,u=0;u<e.sortedFormSections.length;u++)if(e.sortedFormSections[u].id===h){if(u===e.sortedFormSections.length-1){if(gt){for(f=null,t=0;t<r.inspectionFormInfoList.length;t++)if(r.inspectionFormInfoList[t].formVersionId===e.id){t<r.inspectionFormInfoList.length-1&&(f=r.inspectionFormInfoList[t+1].formVersionId);break}f!==null&&(window.location=app.vroot()+"InspectionForm?inspectionId="+r.id+"&formVersionId="+f+"&formSectionId=FIRST")}}else for(t=u+1;t<e.sortedFormSections.length;t++)for(i=0;i<n.inspectionFormSections.length;i++)if(n.inspectionFormSections[i].formSection){if(e.sortedFormSections[t].id===n.inspectionFormSections[i].formSection.id){if(n.inspectionFormSections[i].isVisible){h=n.inspectionFormSections[i].formSection.id,y(h);return}break}}else if(e.sortedFormSections[t].id===n.inspectionFormSections[i].formSectionId){if(n.inspectionFormSections[i].isVisible){h=n.inspectionFormSections[i].formSectionId,y(h);return}break}break}});$("#PreviousSectionButton").on("click",function(){for(var f,t,i,u=0;u<e.sortedFormSections.length;u++)if(e.sortedFormSections[u].id===h){if(u===0){if(gt){for(f=null,t=0;t<r.inspectionFormInfoList.length;t++)if(r.inspectionFormInfoList[t].formVersionId===e.id){t>0&&(f=r.inspectionFormInfoList[t-1].formVersionId);break}f!==null&&(window.location=app.vroot()+"InspectionForm?inspectionId="+r.id+"&formVersionId="+f+"&formSectionId=LAST")}}else for(t=u-1;t>=0;t--)for(i=0;i<n.inspectionFormSections.length;i++)if(n.inspectionFormSections[i].formSection){if(e.sortedFormSections[t].id===n.inspectionFormSections[i].formSection.id){if(n.inspectionFormSections[i].isVisible){h=n.inspectionFormSections[i].formSection.id,y(h);return}break}}else if(e.sortedFormSections[t].id===n.inspectionFormSections[i].formSectionId){if(n.inspectionFormSections[i].isVisible){h=n.inspectionFormSections[i].formSectionId,y(h);return}break}break}});$("#CurrentForms").on("click","li",function(){var t=$(this).data("formversion-id"),n=$(this).data("formsection-id"),i=$(this).data("inspection-id");return t===e.id?(y(n),$("#FormNavigation").hide(),$("#SlideUpFormsButton").removeClass("ui-active"),$("#Questions").show(),$("#PreviousSectionButton").show(),$("#NextSectionButton").show(),$("#SectionChooser").show(),$("#SlideUpMoreButton").show()):window.location=app.vroot()+"InspectionForm?inspectionId="+i+"&formVersionId="+t+"&formSectionId="+n,!1});$("#CurrentForms").on("click",".js-repeating-row",function(){var i=$($(this).parents("li")[0]).data("formversion-id"),t=$($(this).parents("li")[0]).data("formsection-id"),r=$($(this).parents("li")[0]).data("inspection-id"),n=$(this).data("index");return i===e.id?(y(t,n),$("#FormNavigation").hide(),$("#SlideUpFormsButton").removeClass("ui-active"),$("#Questions").show(),$("#PreviousSectionButton").show(),$("#NextSectionButton").show(),$("#SectionChooser").show(),$("#SlideUpMoreButton").show()):window.location=app.vroot()+"InspectionForm?inspectionId="+r+"&formVersionId="+i+"&formSectionId="+t+"&sectionIndex="+n,!1});$("#CloseSectionDialogButton").button(),$("#RepeatingSectionButton").button({icons:{primary:"ui-icon-down"}}),$("#AddSectionButton").button({icons:{primary:"ui-icon-add"},text:!1}),$("#AddSectionButton").click(function(){var h,i,e,u,f;if($.blockUI(),indexes=ft(o),h=indexes.length,h>=o.repeatingSectionsCount&&o.repeatingSectionsCount>0){alert("This section can only be repeated "+o.repeatingSectionsCount+" times.");return}for(indexes!==undefined&&(ut=indexes.length===0?1:indexes[indexes.length-1]+1),s=ut,et=h+1,i={},i.id=app.createUUID(),i.inspectionFormSectionId=t.id,i.sectionIndex=s,i.hasMissingAnswer=!1,i.score=0,i.isDirty=!0,i.isNew=!0,i.isDeleted=!1,i.changedOn=moment(new Date).format(),i.inspectionFormAnswers=[],t.inspectionFormRepeatingSections||(t.inspectionFormRepeatingSections=[]),t.inspectionFormRepeatingSections.push(i),t.isDirty=!0,n.isDirty=!0,r.isDirty=!0,e=0;e<o.sortedFormControls.length;e++)inspectionFormAnswer={},inspectionFormAnswer.id=app.createUUID(),inspectionFormAnswer.inspectionId=r.id,inspectionFormAnswer.inspectionFormId=n.id,inspectionFormAnswer.formControlId=o.sortedFormControls[e].id,inspectionFormAnswer.inspectionFormMedia=[],inspectionFormAnswer.answerComment="",inspectionFormAnswer.isAnswerViolation=!1,inspectionFormAnswer.latitude="",inspectionFormAnswer.longitude="",inspectionFormAnswer.isNew=!0,inspectionFormAnswer.isDirty=!0,inspectionFormAnswer.isDeleted=!1,inspectionFormAnswer.violationDeterminedDate=null,inspectionFormAnswer.repeatingSection=s,inspectionFormAnswer.createdOn=(new moment).format(),inspectionFormAnswer.score=0,inspectionFormAnswer.inspectionFormRepeatingSectionId=i.id,inspectionFormAnswer.isVisible=o.sortedFormControls[e].visibilityFormula?!1:!0,o.sortedFormControls[e].isRequiredInput?(inspectionFormAnswer.hasMissingAnswer=!0,i.hasMissingAnswer=!0,t.hasMissingAnswer=!0,n.hasMissingAnswer=!0,r.hasMissingAnswer=!0):inspectionFormAnswer.hasMissingAnswer=!1,inspectionFormAnswer.inspectionFormSectionId=t.id,inspectionFormAnswer.inspectionFormRepeatingSectionId=i.id,inspectionFormAnswer.inspectionFormMedia=[],i.inspectionFormAnswers.push(inspectionFormAnswer);for(u=0;u<i.inspectionFormAnswers.length;u++)f=o.sortedFormControls.find(function(n){return n.id===i.inspectionFormAnswers[u].formControlId}),f.tag&&nt.set(o.tag+"|"+f.tag+"|"+i.inspectionFormAnswers[u].repeatingSection,{value:i.inspectionFormAnswers[u]}),f.visibilityFormula&&a.push({inspectionFormAnswer:i.inspectionFormAnswers[u],tagList:at(f.visibilityFormula),visibilityFormula:f.visibilityFormula});y(o.id,s,!0),v(!0,function(){$.unblockUI()})}),$("#RepeatingSectionButton").click(function(){$("#RepeatingSectionDialog").is(":visible")?($("#RepeatingSectionDialog").hide(),$("#Questions").unblock()):ti(o)});$("#RepeatingTable").on("click",".js-copy-section",function(){var c,p,a,l,f,e,i,u;if(confirm("Are you sure you want to copy this section?")){for(c=$(this).parents("tr").data("index"),p=c-1,s=c,a=t.inspectionFormRepeatingSections.find(function(n){return n.sectionIndex===p}),l=t.inspectionFormRepeatingSections.find(function(n){return n.sectionIndex===s}),f=0;f<o.sortedFormControls.length;f++)if(e=o.sortedFormControls[f],e.isAllowedInput)if(i=a.inspectionFormAnswers.find(function(n){return n.formControlId===e.id}),i.plainTextValue===undefined||i.plainTextValue===null||i.plainTextValue==="")break;else{u=l.inspectionFormAnswers.find(function(n){return n.formControlId===e.id}),u.controlValue=i.controlValue,u.plainTextValue=i.plainTextValue,u.isVisible=i.isVisible,u.score=i.score,u.isDirty=!0,pt(u,u.score);break}l.isDirty=!0,t.isDirty=!0,n.isDirty=!0,r.isDirty=!0,v(),y(h,c,!1)}return!1});$("#RepeatingTable").on("click","tbody tr td:not(.section-action-down, .section-action-up, .section-action-delete, .section-action-copy)",function(){var n=$(this).parents("tr").data("index");return y(h,n),$("#RepeatingSectionDialog").closest(".ui-dialog-content").dialog("close"),!1});$("#RepeatingTable").on("click",".js-delete-section",function(){var h,u,i,f,s,e;if(confirm("Are you sure you want to delete this section?")){for($.blockUI(),h=$(this).data("index"),u=0,i=0;i<t.inspectionFormRepeatingSections.length;i++){if(t.inspectionFormRepeatingSections[i].sectionIndex===h)for(t.inspectionFormRepeatingSections[i].isDeleted=!0,t.inspectionFormRepeatingSections[i].isDirty=!0,t.isDirty=!0,n.isDirty=!0,r.isDirty=!0,f=0;f<t.inspectionFormRepeatingSections[i].inspectionFormAnswers.length;f++)t.inspectionFormRepeatingSections[i].inspectionFormAnswers[f].isDeleted=!0,t.inspectionFormRepeatingSections[i].inspectionFormAnswers[f].isDirty=!0;t.inspectionFormRepeatingSections[i].isDeleted||(u+=t.inspectionFormRepeatingSections[i].score)}for(t.score=u,u=0,s=0;s<n.inspectionFormSections.length;s++)u+=n.inspectionFormSections[s].score;for(u=0,e=0;e<r.inspectionForms.length;e++)r.inspectionForms[e].isDeleted||(u+=r.inspectionForms[e].score);r.score=u,v(!0,function(){$("#RepeatingSectionDialog").hide(),y(o.id,null,!1),$.unblockUI()})}return!1});$("#RepeatingTable").on("click",".js-up-section",function(){var i,u;$.blockUI();var h=ft(o),e=$(this).data("index"),f=null;for(i=0;i<h.length;i++)if(h[i]===e){f=h[i-1];break}for(s===e?s=f:s===f&&(s=e),i=0;i<t.inspectionFormRepeatingSections.length;i++)if(t.inspectionFormRepeatingSections[i].sectionIndex!==e||t.inspectionFormRepeatingSections[i].isDeleted){if(t.inspectionFormRepeatingSections[i].sectionIndex===f&&!t.inspectionFormRepeatingSections[i].isDeleted)for(t.inspectionFormRepeatingSections[i].isDirty=!0,t.inspectionFormRepeatingSections[i].sectionIndex=e,u=0;u<t.inspectionFormRepeatingSections[i].inspectionFormAnswers.length;u++)t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].repeatingSection=e,t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].isDirty=!0}else for(t.inspectionFormRepeatingSections[i].isDirty=!0,t.inspectionFormRepeatingSections[i].sectionIndex=f,u=0;u<t.inspectionFormRepeatingSections[i].inspectionFormAnswers.length;u++)t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].repeatingSection=f,t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].isDirty=!0;return t.isDirty=!0,n.isDirty=!0,r.isDirty=!0,v(!0,function(){ti(o)}),!1});$("#CloseSectionDialogButton").on("click",function(){$("#RepeatingSectionDialog").dialog("close")});$("#RepeatingTable").on("click",".js-down-section",function(){var i,u;$.blockUI();var h=ft(o),e=$(this).data("index"),f=null;for(i=0;i<h.length;i++)if(h[i]===e){f=h[i+1];break}for(s===e?s=f:s===f&&(s=e),i=0;i<t.inspectionFormRepeatingSections.length;i++)if(t.inspectionFormRepeatingSections[i].sectionIndex!==e||t.inspectionFormRepeatingSections[i].isDeleted){if(t.inspectionFormRepeatingSections[i].sectionIndex===f&&!t.inspectionFormRepeatingSections[i].isDeleted)for(t.inspectionFormRepeatingSections[i].isDirty=!0,t.inspectionFormRepeatingSections[i].sectionIndex=e,u=0;u<t.inspectionFormRepeatingSections[i].inspectionFormAnswers.length;u++)t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].repeatingSection=e,t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].isDirty=!0}else for(t.inspectionFormRepeatingSections[i].isDirty=!0,t.inspectionFormRepeatingSections[i].sectionIndex=f,u=0;u<t.inspectionFormRepeatingSections[i].inspectionFormAnswers.length;u++)t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].repeatingSection=f,t.inspectionFormRepeatingSections[i].inspectionFormAnswers[u].isDirty=!0;return t.isDirty=!0,n.isDirty=!0,r.isDirty=!0,v(!0,function(){ti(o)}),!1});$("#ViewMediaImage").dialog({autoOpen:!1,modal:!0,resizable:!1,autoResize:!0,width:600,height:600,buttons:[{text:"Close",click:function(){$(this).dialog("close")}}]}),$("#ImageInfo").dialog({title:"Image Metadata",autoOpen:!1,modal:!0,resizable:!1,autoResize:!0,width:"auto",buttons:[{text:"OK",click:function(){$.blockUI({message:"<h1>Please Wait<\/h1>"}),$(this).dialog("close");var u=f(ht),i=u.inspectionFormMedia.find(function(n){return n.id===ct});i.metadataComment=$("#ImageComments").val(),i.isDirty=!0,u.isDirty=!0,c&&(c.isDirty=!0),t.isDirty=!0,n.isDirty=!0,r.isDirty=!0,$.unblockUI()}}]}),$("#TakeWebPicture").dialog({autoOpen:!1,modal:!0,resizable:!1,autoResize:!0,width:690,height:570,open:function(){$(this).parent().css("position","fixed").css("top","5px")},close:function(){lt.pause(),vt!==null&&vt.stop()}}),y(h,s),setInterval(v,5e3);$("html").on("FormsMenuLoaded",function(){var t=$("h3[data-formversion-id="+e.id+"]","#CurrentForms"),n=$("li[data-formsection-id="+h+"]",t.next());$(".section-selected").removeClass("section-selected"),n.addClass("section-selected")})},ni=function(n,t,i){var r,u,f;return(t===undefined||t===null)&&(t=""),r="",u="",r+="<td ",n.justification==="Left"?(r+="class='js-table-justify-left' ",u="table-cell-justify-left"):n.justification==="Center"?(r+="class='js-table-justify-center' ",u="table-cell-justify-center"):n.justification==="Right"?(r+="class='js-table-justify-right' ",u="table-cell-justify-right"):(r+="class='js-table-justify-left' ",u="table-cell-justify-left"),n.width!==undefined&&n.width!==null&&n.width.length>0&&(r+="style = 'width:"+n.width+"%'"),r+=">",n.type==="Text"?r+=n.isReadOnly||!i?"<label class='"+u+"'>"+t+"<\/label>":"<input type='text' class='js-col-text js-col-answer "+u+"' value='"+tt(t)+"' />":n.type==="Comment"?r+=n.isReadOnly||!i?"<label class='"+u+"'>"+t+"<\/label>":"<textarea class='js-col-comment js-col-answer "+u+"' >"+tt(t)+"<\/textarea>":n.type==="Number"?r+=n.isReadOnly||!i?"<label class='"+u+"'>"+t+"<\/label>":"<input type='number' class='js-col-number js-col-answer "+u+"'  value='"+tt(t)+"' />":n.type==="Date"?n.isReadOnly||!i?r+="<label class='"+u+"'>"+t+"<\/label>":(f="",t!==null&&t!==undefined&&$.trim(t)!==""&&(f=moment(t).format("MM/DD/YYYY")),r+="<input type='text' class='js-col-date js-col-answer "+u+"' value='"+tt(f)+"' />"):r+=n.type==="Time"?n.isReadOnly||!i?"<label class='"+u+"'>"+t+"<\/label>":"<input type='time' class='js-col-time js-col-answer "+u+"' value='"+tt(t)+"' />":n.type==="Checkbox"?t.toUpperCase()==="TRUE"||t.toUpperCase()==="CHECKED"?n.isReadOnly||!i?"<input type='checkbox' class='js-col-checkbox js-col-answer "+u+"' checked='checked' disabled='disabled' />":"<input type='checkbox' class='js-col-checkbox js-col-answer "+u+"' checked='checked' />":n.isReadOnly||!i?"<input type='checkbox' class='js-col-checkbox js-col-answer "+u+"' disabled='disabled' />":"<input type='checkbox' class='js-col-checkbox js-col-answer "+u+"' />":n.isReadOnly||!i?"<label class='"+u+"'>"+t+"<\/label>":"<textarea class='js-col-comment js-col-answer "+u+"' >"+tt(t)+"<\/textarea>",r+="<\/td>"};$(function(){System.import("formula-editor-js").then(function(n){yt||(yt=new n.FormulaRunner({}))}),System.import("lodash").then(function(n){_||(_=new n.lodash({}))}),app.principal.isSensitiveEdit?$("#CompleteInspection").parent().show():$("#CompleteInspection").parent().hide(),ri=$("#MaxImageSize").val(),ei=Handlebars.compile($("#questions-template").html()),gt=$("#NavigateBetweenForms").val().toUpperCase()==="TRUE",$("#Container").css("padding-top",$("#QuestionsHeader").outerHeight()),gi();$(window).on("beforeunload",function(n){var t;return r&&r.isDirty?(v(),t="Cannot close window, data is saving",(n||window.event).returnValue=t,t):it?(t="Cannot close window, data is saving",(n||window.event).returnValue=t,t):void 0})})}}(),function(){if($("#Content").data("currentView")==="Inspection/ViolationList"){var o=null,f=null,i=null,s=null,n=null,r=[],t=0,u=function(){Wndsr.error("Failed getting data")},e=function(){var f,i;t<n.inspectionFormInfoList.length?app.getInspectionForm(n.inspectionFormInfoList[t].id,function(i){i!==null&&i.isActive?app.getFormVersion(i.formVersionId,function(u){for(var f,c,s,h,o=0;o<i.inspectionFormAnswers.length;o++)if(i.inspectionFormAnswers[o].isAnswerViolation){for(f={},f.formVersionName=u.name,i.inspectionFormAnswers[o].answerComment!==undefined&&i.inspectionFormAnswers[o].answerComment!==null&&i.inspectionFormAnswers[o].answerComment.length>0&&(f.answerComment=i.inspectionFormAnswers[o].answerComment),f.repeatingSection=i.inspectionFormAnswers[o].repeatingSection,i.inspectionFormAnswers[o].violationDeterminedDate!==undefined&&i.inspectionFormAnswers[o].violationDeterminedDate!==null?f.violationDate=i.inspectionFormAnswers[o].violationDeterminedDate:i.inspectionFormAnswers[o].violationCreatedDate!==undefined&&i.inspectionFormAnswers[o].violationCreatedDate!==null&&(f.violationDate=i.inspectionFormAnswers[o].violationCreatedDate),f.violationDate.indexOf("T")>=0&&(f.violationDate=f.violationDate.substring(0,f.violationDate.indexOf("T"))),f.inspectionId=n.id,f.formVersionId=i.formVersionId,c=!1,s=0;s<u.sortedFormSections.length;s++){if(c)break;for(h=0;h<u.sortedFormSections[s].sortedFormControls.length;h++)if(u.sortedFormSections[s].sortedFormControls[h].id===i.inspectionFormAnswers[o].formControlId){f.citation=u.sortedFormSections[s].sortedFormControls[h].questionReference,f.citationDescription=u.sortedFormSections[s].sortedFormControls[h].questionReferenceDescription,f.formSectionId=u.sortedFormSections[s].id,f.formSectionSortOrder=s,f.formControlSortOrder=h,f.questionText=u.sortedFormSections[s].sortedFormControls[h].questionText,c=!0;break}}f.inspectionUrl=app.vroot()+"InspectionForm?inspectionId="+f.inspectionId+"&formVersionId="+f.formVersionId+"&formSectionId="+f.formSectionId,r.push(f)}t++,e()},u):(t++,e())},u):(r.sort(function(n,t){return n.formVersionName===t.formVersionName?n.formSectionSortOrder===t.formSectionSortOrder?n.formControlSortOrder<t.formControlSortOrder?-1:n.formControlSortOrder>t.formControlSortOrder?1:n.repeatingSection<t.repeatingSection?-1:n.repeatingSection>t.repeatingSection?1:0:n.formSectionSortOrder<t.formSectionSortOrder?-1:1:n.formVersionName<t.formVersionName?-1:1;var r,i}),$("#ViolationsTable").find("tbody").html(""),f={violations:r},app.resetViolationSeqNum(),i=o(f),$("#ViolationsTable").find("tbody").html(i),$.unblockUI())};$(function(){$.blockUI({message:"<h1>Please Wait<\/h1>"}),o=Handlebars.compile($("#violation-row-template").html()),f=Wndsr.getUrlParam("inspectionId"),i=Wndsr.getUrlParam("formVersionId"),s=Wndsr.getUrlParam("formSectionId"),app.getInspection(f,function(t){n=t;var i=n.site.siteName;$("#ViolationListTitle").text(i),e()},u),i!==undefined&&i!==null&&$("#ViolationsListBack").show();$("#ViolationsListBack").on("click",function(){window.location=app.vroot()+"InspectionForm?inspectionId="+f+"&formVersionId="+i+"&formSectionId="+s})})}}(),function(){$("#Content").data("currentView")==="Inspection/MediaList"&&$(function(){var n=null,t=$("#InspectionId").val();$("#UploadFileDialog").dialog({autoOpen:!1,modal:!0,resizable:!1,title:"Choose file to upload",height:185,minHeight:185,width:500,minWidth:500,buttons:{Cancel:function(){n=null;var t=$("#UploadFile");t.wrap("<form>").closest("form").get(0).reset(),t.unwrap(),$("#UploadFileDialog").dialog("close")},OK:function(){if(n==null){alert("No file was selected");return}$.blockUI();var i=new FileReader;i.onload=function(){return function(i){var f=i.target.result.substring(i.target.result.indexOf(",")+1),u=n.type,r=n.name;app.post(app.vroot()+"Synchronize/AddInspectionMedia/",{inspectionId:t,mimeType:u,fileData:f,fileName:r},function(){window.location.reload()},function(){n=null;var t=$("#UploadFile");t.wrap("<form>").closest("form").get(0).reset(),t.unwrap(),$("#UploadFileDialog").dialog("close"),alert("Failed uploading file")})}}(n),i.readAsDataURL(n)}}});$("#InspectionMediaTable").on("click",".js-inspectionMedia-link",function(){var n=$(this).parents("tr").data("id");window.location=app.vroot()+"Inspection/InspectionMediaFile/"+n});$("#NewDocumentButton").button();$("#NewDocumentButton").on("click",function(){$("#UploadFileDialog").dialog("open")});$("#UploadFile").on("change",function(t){var i=t.target.files;i.length>0&&(n=i[0])})})}(),function(){$("#Content").data("currentView")==="Inspection/ReviewList"&&$(function(){var n;app.applyTheme($("#Content")),$("#ReviewButton").addClass("ui-active"),$("#InspectionActions").menu();$("#ReviewTable").on("click",".js-options-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#InspectionActions").hide();else{$(".generatePDFOption").show(),$(".generateReport").show(),$(".downlaodImages").show();var n=$(this).data("inspection-id");$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#InspectionActions").css("top",$(this).offset().top+$(this).height()),$("#InspectionActions").data("inspection-id",n),$("#InspectionActions").show();$("html").on("click",function(){$(this).is("#InspectionActions")||$("#InspectionActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),$("html").off("click"))})}return!1});$("#InspectorReviewSelect").on("change",function(){$(this).val()==="ALL"?$("tbody tr","#ReviewTable").removeClass("hide-control"):$(this).val()==="UNASSIGNED"?($("tbody tr","#ReviewTable").addClass("hide-control"),$("tbody tr[data-principal-id='']","#ReviewTable").removeClass("hide-control")):($("tbody tr","#ReviewTable").addClass("hide-control"),$("tbody tr[data-principal-id='"+$(this).val()+"']","#ReviewTable").removeClass("hide-control"))});$("#ShowViolations").on("click",function(){var n=$("#InspectionActions").data("inspection-id");window.location=app.vroot()+"Inspection/ViolationList?inspectionId="+n});$(".generateReport").on("click",function(){var i=(new Date).getTimezoneOffset(),n=$("#InspectionActions").data("inspection-id"),t=$(this).data("reportType");return app.getInspection(n,function(r){for(var f=!1,u=0;u<r.inspectionFormInfoList.length;u++)if(!r.inspectionFormInfoList[u].isDeleted){f=!0;break}f?window.location.href=app.vroot()+"Report/GetReport?inspectionId="+n+"&curDateOffset="+i+"&reportType="+t:alert("There are no forms for this inspection, the report cannot be generated")},function(){alert("Failed getting inspection for report")}),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#MarkInspectionComplete").on("click",function(){if(!app.isOnline)return alert("Must be connected to nSpect server to complete an inspection."),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1;$.blockUI({message:"<h1>Please Wait...<\/h1>"});var n=$("#InspectionActions").data("inspection-id");app.persist.getInspection(n,function(n){if(console.log(n),n.isConflict){alert("This inspection has a conflict, you must resolve the conflict and synchronize before completing the inspection");return}n.hasMissingAnswer?(alert("There are missing required questions on this inspection, cannot complete."),$.unblockUI()):(n.completed=moment(new Date).format(),n.isInProgress=!1,n.isComplete=!0,n.isDirty=!0,app.persist.putInspection(n,function(){app.persist.syncChanges(function(){window.location.reload()})}))},function(){alert("Failed getting inspection to complete"),$.unblockUI()})});var f=function(n){if(n.length>0){alert("This inspection has a conflict, you must resolve the conflict and synchronize before completing the inspection"),$.unblockUI();return}var t=$("#InspectionActions").data("inspection-id");confirm("Mark Inspection as complete?")?app.getInspection(t,u,r):$.unblockUI()},e=function(){alert("Failed updating inspection"),$.unblockUI(),Wndsr.error("UpdateInspection Failed")},u=function(n){if(!n){showMapFailed();return}Wndsr.info("Request inspection Success - complete"),n.completed=moment(new Date).format(),n.isInProgress=!1,app.updateInspection(n,t,i)},r=function(){alert("Failed getting inspection to complete"),$.unblockUI(),Wndsr.error("GetInspection Failed - complete")},t=function(n){Wndsr.info("Update inspection Success"),n!==undefined&&n.message!==null&&n.message!==undefined&&alert(n.message),window.location.reload()},i=function(){alert("Failed updating inspection"),$.unblockUI(),Wndsr.error("UpdateInspection Failed")};$("#AddSiteDialog").dialog({title:"Edit Inspection",autoOpen:!1,modal:!0,resizable:!1,height:575,minHeight:575,width:575,minWidth:575,buttons:{OK:function(){var i=$.trim($(".js-date-answer").val()),n=$.trim($(".js-inspection-date-answer").val()),u=$.trim($(".js-inspection-review-date-answer").val()),t,r,o,e,f;if(i.length===0){alert("Inspection Date is required");return}if(!Wndsr.isValidDate(i)){alert(i+" is an invalid date"),$(".js-date-answer").val("");return}if(n.length>0&&!Wndsr.isValidDate(n)){alert(n+" is an invalid date"),$(".js-inspection-date-answer").val("");return}if(u.length>0){if(t=new moment(u),t=t.startOf("day"),r=new moment,r=r.startOf("day"),o=r.add("d",30),t>o){alert("request review date cannot be more than 30 days in the future"),$(".js-inspection-review-date-answer").val("");return}if(n.length>0){if(e=new moment(n),t<e.startOf("day")){alert("request review date cannot be before the Evaluation Date"),$(".js-inspection-review-date-answer").val("");return}}else if(f=new moment(i),t<f.startOf("day")){alert("request review date cannot be before the Scheduled Date"),$(".js-inspection-review-date-answer").val("");return}}if(editInspection.siteKey!==null&&editInspection.siteKey!==undefined&&editInspection.siteKey!==""&&$("#SiteKeyTextBox").is(":visible")&&$("#SiteKeyTextBox").val()==="")return alert($("#SiteKeyLabel").val()+" is required"),!1;$.blockUI(),editInspection.scheduledStart=moment(i).format(),editInspection.principalId=$("#InspectorSelect").val(),editInspection.reviewPrincipalId=$("#ReviewerSelect").val()!==""?$("#ReviewerSelect").val():null,editInspection.inspectionTypeCode=$("#InspectionTypeSelect").val(),editInspection.actualStart=n.length>0?moment(n).format():null,$("#SiteKeyTextBox").is(":visible")&&(editInspection.siteKey=$("#SiteKeyTextBox").val()),u.length>0?editInspection.reviewRequestDate=moment(u).format():(editInspection.reviewRequestDate=null,editInspection.reviewPrincipalId=null),editInspection.isDirty=!0,app.persist.updateReviewInspection(editInspection,function(){window.location=app.vroot()+"Inspection/ReviewList?inspector="+$("#InspectorSelect").val(),$("#AddSiteDialog").dialog("close")},function(){alert("Update Inspection Failed"),$.unblockUI()},!0)},Cancel:function(){$("#AddSiteDialog").dialog("close")}}});$("#InspectionDetails").on("click",function(){var t=$("#InspectionActions").data("inspection-id");app.persist.getReviewInspection(t,function(n){editInspection=n,$("#SiteDisplayName").text(n.siteName),$("#SiteKeyLabel").text(n.siteKey),$("#SiteKeyTextBox").val(n.siteKey),$("#InspectorSelect").val(n.principalId),$("#InspectionTypeSelect").val(n.inspectionTypeCode),n.scheduledStart!==undefined&&n.scheduledStart!==null?$(".js-date-answer").val(moment(n.scheduledStart).format("M/D/YYYY")):$(".js-date-answer").val(""),n.actualStart!==undefined&&n.actualStart!==null?$(".js-inspection-date-answer").val(moment(n.actualStart).format("M/D/YYYY")):$(".js-inspection-date-answer").val(""),n.reviewRequestDate!==undefined&&n.reviewRequestDate!==null?$(".js-inspection-review-date-answer").val(moment(n.reviewRequestDate).format("M/D/YYYY")):$(".js-inspection-review-date-answer").val(""),n.reviewPrincipalId!==undefined&&n.reviewPrincipalId!==null?$("#ReviewerSelect").val(n.reviewPrincipalId):$("#ReviewerSelect").val(""),n.siteKey!==undefined&&n.siteKey!==null&&n.siteKey!==""?($("#SiteKeyLabel").hide(),$("#SiteKeyTextBox").show()):n.siteKey===undefined||n.siteKey===null||n.siteKey===""?($("#SiteKeyLabel").hide(),$("#SiteKeyTextBox").show()):($("#SiteKeyLabel").show(),$("#SiteKeyTextBox").hide()),$("#AddSiteDialog").dialog("open")},n)});n=function(n){n.statusText==="Retry with authentication"?alert("Your session has expired, please log in again."):alert("Failed getting inspection list"),$.unblockUI(),Wndsr.error("GetInspectionList Failed")}})}(),function(){var n;$("#Content").data("currentView")==="Inspection/UnassignedInspections"&&$(function(){var r,u,t,i;app.principal.isAdmin&&$(".delete-inspection").show(),app.getPrincipalList(function(n){var u,r;for(Wndsr.info("Request principal list Success"),principalList=n===null?[]:n,u="<option><\/option>",r=0;r<principalList.length;r++)u+='<option value="'+principalList[r].id+'">'+principalList[r].displayName+"<\/option>";$("#InspectorSelect").html(u)},function(){alert("Failed getting Principal List")},!0),r=$(".js-date-answer"),u=$(".js-date-hidden"),u.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:r,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),t=$(".js-inspection-date-answer"),i=$(".js-inspection-date-hidden"),i.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:t,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0});$("#InspectionsTable").on("click",".js-delete-inspection",function(){return confirm("Are you sure you want to delete this inspection?")&&($.blockUI({message:"<h1>Please Wait...<\/h1>"}),app.deleteInspection($(this).data("inspection-id"),function(){window.location.reload()},function(){$.unblockUI(),alert("Failed Deleting Inspection")},!0)),!1});$("#AddSiteDialog").dialog({title:"Assign Inspection",autoOpen:!1,modal:!0,resizable:!1,height:400,minHeight:400,width:550,minWidth:550,buttons:{OK:function(){var i=$.trim($(".js-date-answer").val()),t=$.trim($(".js-inspection-date-answer").val()),r=new moment;if($("#InspectorSelect").val()===""){alert("Inspector is required");return}if(i.length==0){alert("Scheduled Date is required");return}if(!Wndsr.isValidDate(i)){alert(i+" is an invalid date"),$(".js-date-answer").val("");return}if(t.length>0&&!Wndsr.isValidDate(t)){alert(t+" is an invalid date"),$(".js-inspection-date-answer").val("");return}if(i.length>0&&moment(i).add("days",120)<r){alert("Scheduled Date cannot be more than 120 days old");return}if(t.length>0&&moment(t).add("days",120)<r){alert("Evaluation Date cannot be more than 120 days old");return}$("#AddSiteDialog").dialog("close"),$.blockUI(),n.scheduledStart=moment(i).format(),n.principalId=$("#InspectorSelect").val(),n.principalId===""&&(n.principalId=null),n.inspectionTypeCode=$("#InspectionTypeSelect").val(),n.actualStart=t.length>0?moment(t).format():null,app.persist.updateUnassignedInspection(n,function(){$("#AddSiteDialog").dialog("close"),window.location.reload()},function(){alert("Assigning Inspection Failed"),$.unblockUI()},!0)},Cancel:function(){$("#AddSiteDialog").dialog("close")}}});$("#InspectionsTable").on("click",".js-assign-inspection",function(){$.blockUI({message:"<h1>Please Wait...<\/h1>"});var t=$(this).data("inspection-id");app.persist.getUnassignedInspection(t,function(t){n=t,$("#SiteDisplayName").text(t.siteName),app.principal.isAdmin?$("#InspectorSelect").val(""):$("#InspectorSelect").val(app.principal.id),$("#InspectionTypeSelect").val(t.inspectionTypeCode),t.scheduledStart!==undefined&&t.scheduledStart!==null?$(".js-date-answer").val(moment(t.scheduledStart).format("M/D/YYYY")):$(".js-date-answer").val(""),t.actualStart!==undefined&&t.actualStart!==null?$(".js-inspection-date-answer").val(moment(t.actualStart).format("M/D/YYYY")):$(".js-inspection-date-answer").val(""),$("#AddSiteDialog").dialog("open"),$.unblockUI()},function(){alert("Get Inspection Failed")},!0)})})}(),function(){$("#Content").data("currentView")==="Inspection/InspectionImport"&&$(function(){var n,i,t;$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});i=$(".js-date-answer"),t=$(".js-date-hidden"),t.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:i,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),$("#ImportButton").button({icons:{primary:null,secondary:null}});$("#ImportButton").on("click",function(){$.blockUI();var r=$("#ProjectSelect").val(),u=$("#InspectorSelect").val(),t=$("#InspectionTypeSelect").val(),i=$("#ScheduleDate").val();if(n===null||n===undefined||n===""){alert("You must provide an import file."),$.unblockUI();return}app.post(app.vroot()+"Inspection/Import/0",{project:r,inspector:u,inspectionType:t,scheduledDate:i,documentData:n},function(t){$("#ProjectSelect").val(""),$("#InspectorSelect").val(""),$("#InspectionTypeSelect").val(""),$("#ScheduleDate").val(""),$("#ImportFile").val(""),n=null,alert(t.message),$.unblockUI()},function(){alert("Failed uploading inspections"),$.unblockUI()})});$("#ImportFile").on("change",function(t){for(var f=t.target.files,i,r,u=0;i=f[u];u++)r=new FileReader,r.onload=function(){return function(t){n=t.target.result}}(i),r.readAsText(i)})})}(),function(){if($("#Content").data("currentView")==="Site/Index"){var e=null,r=!0,p=null,a=0,l=0,i=[],h=null,n="0",v=!1,w=null,o=null,f=[],u=[],t=[],k=function(){var t=$.trim($("#SiteSearchText").val());t.length!==0&&(Wndsr.info("Searching sites - "+t),$.blockUI(),n==="2"?app.post(app.vroot()+"Site/SearchSites/0",{siteSearchText:t},function(n){g(n)},SearchSitesFailed):app.post(app.vroot()+"Mobile/SearchSites/",{siteSearchText:t},function(n){d(n)},SearchSitesFailed))},c=function(n){var t=n;if(t==="")return!0;if(Wndsr.isValidDate(t)){if(dtNow=new moment,dtScheduled=new moment(t),timeDiff=dtScheduled.diff(dtNow,"days",!0),timeDiff<a*-1)return alert("Scheduled Date cannot be more than "+a+" days in the past"),!1;if(timeDiff>l)return alert("Scheduled Date cannot be more than "+l+" days in the future"),!1}else return alert(t+" is an invalid date"),!1;return!0},d=function(t){var s,o,f;Wndsr.info("Search sites success, "+t.sites.length+" results"),$("#SiteCount").text($("#SiteLabel").val()+"s Found: "+t.sites.length).show(),t.sites.map(function(n){var i=t.siteAddresses.find(function(t){return t.siteId===n.id});i&&(n.addressId=i.id,n.state=i.state,n.county=i.county,n.districtCode=i.districtCode,n.addressLineOne=i.addressLineOne,n.city=i.city,n.zipCode=i.zipCode)}),$("#SiteSearchResultsTable").find("tbody").html(""),s={sites:t.sites,isAddSite:r,mode:n},o=e(s),$("#SiteSearchResultsTable").find("tbody").html(o),f=$(".js-date-scheduled"),f.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0,onSelect:function(){$(this).parent().find(".js-date-scheduled").focus()}}),$(".js-edit-site").button({icons:{primary:"ui-icon-pencil"},text:!1}),app.principal.isInternalEdit&&app.isOnline?$(".js-edit-site-toggle").show():$(".js-edit-site-toggle").hide(),$.unblockUI()},g=function(t){var s,o,f;$("#SiteSearchResultsTable").find("tbody").html(""),s={sites:t.items,isAddSite:r,mode:n},o=e(s),$("#SiteSearchResultsTable").find("tbody").html(o),f=$(".js-date-scheduled"),f.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0,onSelect:function(){$(this).parent().find(".js-date-scheduled").focus()}}),$(".js-edit-site").button({icons:{primary:"ui-icon-pencil"},text:!1}),app.principal.isInternalEdit&&app.isOnline?$(".js-edit-site-toggle").show():$(".js-edit-site-toggle").hide(),$.unblockUI()};SearchSitesFailed=function(){alert("Search Failed"),$.unblockUI(),Wndsr.error("Search Sites Failed")};var y=function(){if(i.length===0)window.location=app.vroot()+"Inspection";else{var t=i.pop();t.Save(function(){n==="0"?window.location=app.vroot()+"Inspection":($("#AddSiteDialog").dialog("close"),$("#SiteSearchResultsTable").find("tbody").html(""),$("#SiteSearchText").val("").focus(),$("#SiteCount").text("Inspection Added for site: "+$(".js-siteLink",h).text()),i=[],$.unblockUI())},s)}},s=function(){Wndsr.error("Failed adding inspection"),alert("Failed adding inspection")},b=function(){var t,n;$.blockUI();var u=$("#SiteName").val(),f=$("#SiteKey").val(),o=$("#SiteCity").val(),e=$("#SiteZipCode").val(),r=$("#OfflineScheduledDate").val();if(u===""&&f===""){alert("Either "+$("#SiteNameLabel").val()+" or "+$("#SiteKeyLabel").val()+" must be entered"),$.unblockUI();return}if(r===""){alert("Scheduled Date must be entered"),$.unblockUI();return}t={},t.id=app.createUUID(),t.isSiteClosed=!1,t.siteKey=f,t.siteName=u,t.changedOn=moment(new Date).format(),t.isDirty=!0,t.isNew=!0,t.isDeleted=!1,n={},n.id=app.createUUID(),n.siteId=t.id,n.addressLineOne="",n.addressLineTwo="",n.changedOn=moment(new Date).format(),n.city=o,n.county="",n.isPrimary=!0,n.state="",n.zipCode=e,n.isDirty=!0,n.isNew=!0,n.isDeleted=!1,app.persist.putSite(t,function(){app.persist.putSiteAddress(n,function(){app.persist.syncChanges(function(){var f=$("#InspectionTypeOffline").val(),e=p.id,o=t.id,u=null,n;$("#ProjectSelectOffline").is(":visible")&&(u=$("#ProjectSelectOffline").val()),n=new Inspection,n.New(f,e,r,null,o,u),n.AutoAttachForms(function(){i.push(n),y()},s)})})})};$(function(){var tt,nt,g,d;$.blockUI(),app.principal.isInternalEdit&&app.isOnline?$(".js-edit-site-toggle").show():$(".js-edit-site-toggle").hide();$("html").on("applicationOnline",function(){app.principal.isInternalEdit&&app.isOnline?$(".js-edit-site-toggle").show():$(".js-edit-site-toggle").hide()});$("html").on("applicationOffline",function(){$(".js-edit-site-toggle").hide()});app.persist.getPrincipals(function(n){var r,i;for(Wndsr.info("Request principals Success"),f=n===null?[]:n,r="",r="<option><\/option>",i=0;i<f.length;i++)r+='<option value="'+f[i].id+'">'+f[i].displayName+"<\/option>";$("#InspectorSelect").html(r),app.persist.getProjects(function(n){var r,i;for(u=n===null?[]:n,u.sort(function(n,t){return n.projectTitle.localeCompare(t.projectTitle)}),r="<option><\/option>",i=0;i<u.length;i++)r+='<option value="'+u[i].id+'">'+u[i].projectTitle+"<\/option>";$("#ProjectSelectOffline").html(r),$("#ProjectSelect").html(r),app.persist.getInspectionTypes(function(n){var r,i;for(t=n?n:[],t.sort(function(n,t){return n.name.localeCompare(t.name)}),r="",i=0;i<t.length;i++)r+="<option value='"+t[i].id+"'>"+t[i].name+"<\/option>";$("#InspectionTypeOffline").html(r),$("#InspectionTypeSelect").html(r),$.unblockUI()})})}),n=Wndsr.getUrlParam("mode"),n==="0"?($.blockUI(),$("#AddSiteOnline").hide(),$("#AddSiteOffline").show(),$("h2","#PageHeaderInline").html("Add Inspection"),$("title").text("Add Inspection"),$(".ui-icon-top").addClass("ui-icon-inspection-list")):n==="1"?($("#AddSiteOffline").hide(),$("#AddSiteOnline").show(),$("h2","#PageHeaderInline").html("Add Inspection"),$("title").text($("#ApplicationName").val()+" - Add Inspection"),$(".ui-icon-top").addClass("ui-icon-inspection-list")):n==="2"?(r=!1,$("#AddSiteOffline").hide(),$("#AddSiteOnline").show(),$("h2","#PageHeaderInline").html($("#SiteLabel").val()+" Search"),$("#CheckBoxHeader").hide(),$("title").text($("#ApplicationName").val()+" - "+$("#SiteLabel").val()+" Search"),$("#SlideUpSitesButton").addClass("ui-active"),$("#AddSiteDone").hide(),$(".ui-icon-top").addClass("ui-icon-site")):n==="3"?($("#AddSiteOffline").hide(),$("#AddSiteOnline").show(),$("h2","#PageHeaderInline").html("Add Inspection"),$("title").text($("#ApplicationName").val()+" - Add Inspection"),$(".otto-field").show(),$(".ui-icon-top").addClass("ui-icon-projects"),$("#ProjectSelect").parent().hide(),o=Wndsr.getUrlParam("projectId"),app.persist.getProject(o,function(n){$("h2","#PageHeaderInline").html("Add Inspection for "+n.projectTitle+" project"),$("title").text($("#ApplicationName").val()+" - Add Inspection for "+n.projectTitle+" project"),$("#ProjectTitle").text(n.projectTitle)},function(){alert("Failed getting project")},!0)):($("#AddSiteOnline").hide(),$("#AddSiteOffline").show(),$("h2","#PageHeaderInline").html("Add Inspection"),$("title").text($("#ApplicationName").val()+" - Add Inspection")),p=Wndsr.getLocalStorage("principal"),a=parseInt($("#MyInspectionsBackDays").val()),l=parseInt($("#MyInspectionsForwardDays").val()),$("#AddSiteOk").button(),$("#AddSiteCancel").button();$("#SiteSearchText").on("keyup",function(n){n.keyCode===13&&$("#AddSiteSearch").click()});$("#AddSiteSearch").on("click",k);e=Handlebars.compile($("#site-row-template").html());$("#SiteSearchResultsTable").on("click",".js-siteLink",function(){var u=$(this).parents("tr"),t,i;return $.blockUI(),r?(t=$(this).text(),$("#SiteDisplayName").text(t),$("#InspectorSelect").val(app.principal.id),h=$(this).parents("tr"),o===null?$(".js-date-answer","#AddSiteDialog").val((new moment).format("M/D/YYYY")):app.persist.getProject(o,function(n){$(".js-date-answer","#AddSiteDialog").val(moment(n.startDate).format("M/D/YYYY"))},function(){alert("Failed getting project date")},!0),$("#AddSiteDialog").dialog("open"),$.unblockUI()):(i=u.data("id"),window.location.href=app.vroot()+"SiteHistory/"+i),!1});$("#AddSiteOk").on("click",b);d=$("#OfflineScheduledDate"),d.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0,onSelect:function(){$(this).parent().find("#OfflineScheduledDate").focus()}});$("#AddSiteDialog").on("blur",".js-date-answer",function(){return c($.trim($(this).val()))?!0:($(this).focus(),$(this).val(""),!1)});$(".js-offline-date-scheduled").on("blur",function(){return c($.trim($(this).val()))?!0:($(this).focus(),$(this).val(""),!1)});$("#AddSiteCancel").on("click",function(){window.location=app.vroot()+"Inspection"});$("#AddEditSiteDialog").dialog({title:"Add "+$("#SiteLabel").val(),autoOpen:!1,modal:!0,resizable:!1,height:700,minHeight:700,width:700,minWidth:700,dialogClass:"js-add-edit-site-dialog",buttons:{Add:function(){var i,t;$.blockUI();var u=$.trim($("#AddEditSiteName").val()),f=$.trim($("#AddEditSiteKey").val()),b=$("#AddEditSiteClosed").is(":checked"),y=$.trim($("#AddEditAddressLineOne").val()),a=$.trim($("#AddEditAddressLineTwo").val()),c=$.trim($("#AddEditCity").val()),p=$.trim($("#AddEditState").val()),l=$.trim($("#AddEditZipCode").val()),o=$.trim($("#AddEditCounty").val()),s=$.trim($("#AddEditDistrictCode").val());if(u===""){alert($("#SiteNameLabel").val()+" is required."),$.unblockUI();return}if($("#AddEditSiteKey").prev().is(".question-required")&&f===""){alert($("#SiteKeyLabel").val()+" is required."),$.unblockUI();return}v?(i={},i.id=app.createUUID(),i.isSiteClosed=b,i.siteKey=f,i.siteName=u,i.changedOn=moment(new Date).format(),i.isDirty=!0,i.isNew=!0,i.isDeleted=!1,t={},t.id=app.createUUID(),t.siteId=i.id,t.addressLineOne=y,t.addressLineTwo=a,t.changedOn=moment(new Date).format(),t.city=c,t.county=o,t.districtCode=s,t.isPrimary=!0,t.state=p,t.zipCode=l,t.isDirty=!0,t.isNew=!0,t.isDeleted=!1,app.persist.putSite(i,function(){app.persist.putSiteAddress(t,function(){app.persist.syncChanges(function(){var u,o,f;$("#SiteCount").text("Site Added").show(),$("#SiteSearchResultsTable").find("tbody").html(""),t&&(i.addressId=t.id,i.state=t.state,i.county=t.county,i.districtCode=t.districtCode,i.addressLineOne=t.addressLineOne,i.city=t.city,i.zipCode=t.zipCode),u=[],u.push(i),o={sites:u,isAddSite:r,mode:n},f=e(o),$("#SiteSearchResultsTable").find("tbody").html(f),$("#SiteSearchText").val(""),$("#AddEditSiteDialog").dialog("close"),$(".js-edit-site").button({icons:{primary:"ui-icon-pencil"},text:!1}),app.principal.isInternalEdit&&app.isOnline?$(".js-edit-site-toggle").show():$(".js-edit-site-toggle").hide(),(n==="1"||n==="3")&&($("#SiteDisplayName").text(i.siteName),$("#InspectorSelect").val(app.principal.id),h=$("tr[data-id="+i.id+"]"),$(".js-date-answer","#AddSiteDialog").val((new moment).format("M/D/YYYY")),$("#AddEditSiteDialog").dialog("close"),$.unblockUI(),$("#AddSiteDialog").dialog("open")),$("#AddEditSiteDialog").dialog("close"),$.unblockUI()})})})):$.ajax({type:"POST",url:app.vroot()+"Site/EditSite/0",data:JSON.stringify({siteId:w,siteName:u,siteKey:f,isSiteClosed:b,addressLineOne:y,addressLineTwo:a,city:c,state:p,zipCode:l,county:o,districtCode:s}),contentType:"application/json; charset=utf-8",success:function(t){var i,f,u;t.success?($("#SiteCount").text("Site Edited").show(),$("#SiteSearchResultsTable").find("tbody").html(""),i=[],i.push(t.site),f={sites:i,isAddSite:r,mode:n},u=e(f),$("#SiteSearchResultsTable").find("tbody").html(u),$("#SiteSearchText").val(""),$("#AddEditSiteDialog").dialog("close"),$(".js-edit-site").button({icons:{primary:"ui-icon-pencil"},text:!1}),app.principal.isInternalEdit&&app.isOnline?$(".js-edit-site-toggle").show():$(".js-edit-site-toggle").hide(),$("#AddEditSiteDialog").dialog("close"),$.unblockUI()):(alert(t.message),$.unblockUI())},error:function(){alert("Failed adding "+$("#SiteLabel").val()+" Information"),$.unblockUI()}})},Cancel:function(){$("#AddEditSiteDialog").dialog("close")}}});$("#AddSiteButton").on("click",function(){$.blockUI(),v=!0,$("#AddEditSiteName").val(""),$("#AddEditSiteKey").val(""),$("#AddEditSiteClosed").attr("checked",!1),$("#AddEditAddressLineOne").val(""),$("#AddEditAddressLineTwo").val(""),$("#AddEditCity").val(""),$("#AddEditState").val(""),$("#AddEditZipCode").val(""),$("#AddEditCounty").val(""),$("#AddEditDistrictCode").val(""),$("#InspectionDescription").val(""),$(".js-add-edit-site-dialog .ui-button-text:contains(Save)").text("Add"),$("#AddEditSiteDialog").dialog("option","title","Add "+$("#SiteLabel").val()),$("#AddEditSiteDialog").dialog("open"),$.unblockUI()});$("#SiteSearchResultsTable").on("click",".js-edit-site",function(){$.blockUI(),v=!1,w=$(this).parents("tr").data("id"),$("#AddEditSiteName").val(""),$("#AddEditSiteKey").val(""),$("#AddEditSiteClosed").attr("checked",!1),$("#AddEditAddressLineOne").val(""),$("#AddEditAddressLineTwo").val(""),$("#AddEditCity").val(""),$("#AddEditState").val(""),$("#AddEditZipCode").val(""),$("#AddEditCounty").val(""),$("#AddEditDistrictCode").val(""),$(".js-add-edit-site-dialog .ui-button-text:contains(Add)").text("Save"),$("#AddEditSiteDialog").dialog("option","title","Edit "+$("#SiteLabel").val());var n=$(this).parents("tr").data("id");$.ajax({type:"POST",url:app.vroot()+"Site/GetEditSite/"+n,data:JSON.stringify({id:n}),contentType:"application/json; charset=utf-8",success:function(n){$("#AddEditSiteName").val(n.siteName),$("#AddEditSiteKey").val(n.siteKey),n.isSiteClosed&&$("#AddEditSiteClosed").attr("checked",!0),$("#AddEditAddressLineOne").val(n.addressLineOne),$("#AddEditAddressLineTwo").val(n.addressLineTwo),$("#AddEditCity").val(n.city),$("#AddEditState").val(n.state),$("#AddEditZipCode").val(n.zipCode),$("#AddEditCounty").val(n.county),$("#AddEditDistrictCode").val(n.districtCode),$("#AddEditSiteDialog").dialog("open"),$.unblockUI()},error:function(){alert("Failed getting "+$("#SiteLabel").val()+" Information"),$.unblockUI()}})});$("#BackButton").on("click",function(){var n=null;window.location.href.indexOf("returnUrl")>=0&&(n=window.location.href.substring(window.location.href.indexOf("returnUrl")+10)),n!==undefined&&n!==null&&n!==""?window.location.href=n:window.location=app.vroot()+"Inspection"});$("#AddSiteDialog").dialog({title:"Add Inspection",autoOpen:!1,modal:!0,resizable:!1,height:650,minHeight:650,width:550,minWidth:550,buttons:{Add:function(){var e,t;i=[];var r=$.trim($(".js-date-answer").val()),u=$.trim($(".js-inspection-date-answer").val()),o=new moment;if(r.length===0){alert("Inspection Date is required");return}if(!Wndsr.isValidDate(r)){alert(r+" is an invalid date"),$(".js-date-answer").val("");return}if(u.length>0&&!Wndsr.isValidDate(u)){alert(u+" is an invalid date"),$(".js-inspection-date-answer").val("");return}if(c(r)){if(r.length>0&&moment(r).add("days",120)<o){alert("Scheduled Date cannot be more than 120 days old");return}if(u.length>0&&moment(u).add("days",120)<o){e=$(".evaulationDateLabel").text().replace(":",""),alert(e+" cannot be more than 120 days old");return}$.blockUI();var l=$("#InspectionTypeSelect").val(),a=$("#InspectorSelect").val(),v=h.data("id"),f=null;$("#ProjectSelect").is(":visible")&&(f=$("#ProjectSelect").val()),t=new Inspection,t.New(l,a,r,u,v,f),t.AutoAttachForms(function(){if($("#AddSiteDialog").dialog("close"),n==="3"){var u=$("#InspectionDescription").val().trim(),r="";$(".formCheckBox:checked").each(function(){r.length>0&&(r+="|"),r+=$(this).val()}),t.description=u,app.post(app.vroot()+"Synchronize/NewInspectionForProject",{inspection:t,projectId:f,inspectionFormIds:r},function(){$("#AddSiteDialog").dialog("close"),$("#SiteSearchResultsTable").find("tbody").html(""),$("#SiteSearchText").val("").focus(),$("#SiteCount").text("Inspection Added for site: "+t.site.siteName),$.unblockUI()},s)}else i.push(t),y()},s)}},Cancel:function(){$("#AddSiteDialog").dialog("close")}}}),tt=$(".js-date-answer"),nt=$(".js-date-hidden"),nt.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:tt,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),g=$(".js-inspection-date-answer"),d=$(".js-inspection-date-hidden"),d.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:g,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0})})}}(),function(){function n(n){var t=null;return t=typeof n=="object"?moment.utc(n._d):moment.utc(n),t.format("M/D/YYYY")}if($("#Content").data("currentView")==="Site/Show"){var i=function(n){n!==undefined&&n===!0&&Wndsr.info("Uncomplete inspection Success"),n!==undefined&&n.message!==null&&n.message!==undefined&&alert(n.message),app.isMobile()&&app.synchronize.checkSync(),n!==undefined&&n===!0?location.reload():t()},t=function(){alert("Failed uncompleting inspection"),$.unblockUI(),Wndsr.error("UncompleteInspection Failed")};$(function(){$("#InfoSiteDialog").dialog({title:"Inspection Info",autoOpen:!1,modal:!0,resizable:!1,height:575,minHeight:575,width:575,minWidth:575,buttons:{OK:function(){$("#InfoSiteDialog").dialog("close")}}}),$("#InspectionActions").menu();$("#InspectionHistroyTable").on("click",".js-options-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#InspectionActions").hide();else{var n=$(this).data("inspection-id");$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#InspectionActions").css("top",$(this).offset().top+$(this).height()),$("#InspectionActions").data("inspection-id",n),$("#InspectionActions").show();$("html").on("click",function(){$(this).is("#InspectionActions")||$("#InspectionActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),$("html").off("click"))})}return!1});$("table").on("click",".inspection-info",function(){$.blockUI({message:"<h1>Please Wait<\/h1>"});var t=$(this).parents("tr").data("id");app.post(app.vroot()+"Synchronize/GetInspection/",{id:t},function(t){$("#SiteDisplayName").text(t.site.siteName),$("#SiteKeyLabel").text(t.site.siteKey),t.principal!==undefined&&t.principal!==null?$("#InspectorLabel").text(t.principal.displayName):$("#InspectorLabel").text(""),$("#InspectionTypeLabel").text(t.inspectionTypeCode),t.scheduledStart!==undefined&&$("#InspectionDateLabel").text(n(t.scheduledStart)),t.actualStart!==undefined&&$("#EvaluationDateLabel").text(n(t.actualStart)),t.reviewRequestDate!==undefined&&$("#RequestReviewDateLabel").text(n(t.reviewRequestDate)),t.reviewPrincipal!==undefined&&$("#ReviewerLabel").text(t.reviewPrincipal.displayName),t.completed!==undefined&&$("#InspectionCompletedDateLabel").text(n(t.completed)),t.cmeDataMigrated!==undefined&&$("#CmeDataMigrationDateLabel").text(n(t.cmeDataMigrated)),t.inspectionKey!==undefined&&$("#InspectionKeyLabel").text(t.inspectionKey),t.inspectionSource!==undefined&&t.inspectionSource!==null&&t.inspectionSource!==""?$("#InspectionSource").text(t.inspectionSource):$("#InspectionSource").text($("#ApplicationName").val()),$("#InfoSiteDialog").dialog("open"),$.unblockUI()},function(){$.unblockUI(),alert("Failed Getting Inspection Info")})});$("#InspectionHistroyTable").on("click",".js-document-download",function(){var n=$(this).data("inspection-id");window.location=app.vroot()+"MediaList/"+n});$("#InspectionHistroyTable").on("click",".js-inspection-link",function(){return $("#AdminButton").is(":visible")?!0:(alert("You have insufficient rights to view/edit this active inspection"),!1)});$("#UncompleteInspection").on("click",function(){if(!app.isOnline)return alert("Must be connected to nSpect server to uncomplete an inspection."),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1;if(confirm("Uncomplete Inspection?")){$.blockUI({message:"<h1>Please Wait...<\/h1>"});var n=$("#InspectionActions").data("inspection-id");app.post(app.vroot()+"Synchronize/UncompleteInspection/",{id:n},i,t)}$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide()});app.principal!==null?app.principal.isUncompleteInspection?$("#UncompleteInspection").parent().show():$("#UncompleteInspection").parent().remove():$("#UncompleteInspection").parent().remove(),$("#InspectionActions").children().size()==0&&$(".js-options-button").remove(),$(".js-options-button").size()==0&&$("#InspectionHistroyTable th:last-child, #InspectionHistroyTable td:last-child").hide()})}}(),function(){$("#Content").data("currentView")==="Principal/Index"&&$(function(){$("#NewPrincipalButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#NewPrincipalButton").on("click",function(){window.location=app.vroot()+"Principal/New"});$("#SearchUsers").on("input",function(){var n=$(this).val().toUpperCase();$("tr","tbody").each(function(){n==""||$(this).find("a").text().toUpperCase().indexOf(n.trim())>=0?$(this).show():$(this).hide().next().hide()})})})}(),function(){$("#Content").data("currentView")==="Principal/Edit"&&$(function(){$("#CancelButton").button(),$("#DeleteButton").button(),$("#SaveButton").button(),$("#ResetPasswordButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Principal/"});$("#ResetPasswordButton").on("click",function(){app.post(app.vroot()+"AuthenticationToken/ResetPassword/0",{login:$("#UserName").val()},function(){alert("Password has been reset and an email has been sent to the user")},function(){alert("Reset Password Failed")})});$("#DeleteButton").on("click",function(){if(confirm("Are you sure you want to Delete this Principal?")){$.blockUI();var n=$("#PrincipalIdHidden").val();app.post(app.vroot()+"Principal/Delete/"+n,null,function(){window.location=app.vroot()+"Principal/"},function(){alert("Delete Failed"),$.unblockUI()})}});$("#SaveButton").on("click",function(){var i,t,n;if($.trim($("#UserName").val())===""){alert("User Name is required");return}if($.trim($("#FirstName").val())===""){alert("First Name is required");return}if($.trim($("#LastName").val())===""){alert("Last Name is required");return}if($.trim($("#EmailAddress").val())===""){alert("Email is required");return}var f=$("#PrincipalIdHidden").val(),r=$.trim($("#UserName").val()),h=$.trim($("#Password").val()),e=$.trim($("#FirstName").val()),o=$.trim($("#LastName").val()),s=$.trim($("#EmailAddress").val()),u=!1;for($("#ActiveStatus").is(":checked")&&(u=!0),i=[],t=$(".js-group-checkbox:checked"),n=0;n<t.length;n++)i.push($(t[n]).val());app.post(app.vroot()+"Principal/SaveEdit/0",{id:f,userName:r,firstName:e,lastName:o,email:s,isActive:u,orgGroups:i},function(){app.principal.login.toUpperCase()===r.toUpperCase()?app.post(app.vroot()+"Synchronize/GetPrincipal/0",{id:app.principal.id},function(n){app.principal.displayName=n.displayName,app.principal.firstName=n.firstName,app.principal.fullName=n.fullName,app.principal.isAdmin=n.isAdmin,app.principal.isInternalEdit=n.isInternalEdit,app.principal.isSensitiveEdit=n.isSensitiveEdit,app.isUncompleteInspection=n.isUncompleteInspection,app.principal.lastName=n.lastName,app.principal.login=n.login,app.principal.middleName=n.middleName,app.principal.organizationList=n.organizationList,app.principal.primaryEmail=n.primaryEmail,app.principal.salutation=n.salutation,app.principal.title=n.title,Wndsr.setLocalStorage("principal",app.principal),window.location=app.vroot()+"Principal/"},function(){window.location=app.vroot()+"Principal/"}):window.location=app.vroot()+"Principal/"},function(){alert("Save Failed"),$.unblockUI()})});$("#PrincipalOrganizations").on("change",function(){$("span","#Groups").hide(),$("#GroupsLabel").html(""),$("#PrincipalOrganizations").val()!==""&&($("#GroupsLabel").text("Groups for "+$("option:selected","#PrincipalOrganizations").text()+":"),$("span[data-org-id="+$("#PrincipalOrganizations").val()+"]").show().css("display","block"))});$("#UserName").focus()})}(),function(){$("#Content").data("currentView")==="Principal/New"&&$(function(){$("#CancelButton").button(),$("#DeleteButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Principal/"});$("#SaveButton").on("click",function(){var i,t,n;if($.trim($("#UserName").val())===""){alert("User Name is required");return}if($.trim($("#Password").val())===""){alert("Password is required");return}if($.trim($("#FirstName").val())===""){alert("First Name is required");return}if($.trim($("#LastName").val())===""){alert("Last Name is required");return}if($.trim($("#EmailAddress").val())===""){alert("Email is required");return}if($("#Password").val()!==$("#PasswordConfirm").val()){alert("Passwords do not match");return}var f=$.trim($("#UserName").val()),r=$.trim($("#Password").val()),e=$.trim($("#FirstName").val()),o=$.trim($("#LastName").val()),s=$.trim($("#EmailAddress").val()),u=!1;for($("#ActiveStatus").is(":checked")&&(u=!0),i=[],t=$(".js-group-checkbox:checked"),n=0;n<t.length;n++)i.push($(t[n]).val());app.post(app.vroot()+"Synchronize/ValidatePassword",{password:r},function(n){n.successful?app.post(app.vroot()+"Principal/SaveNew/0",{userName:f,password:r,firstName:e,lastName:o,email:s,isActive:u,orgGroups:i},function(){window.location=app.vroot()+"Principal/"},function(){alert("Save Failed"),$.unblockUI()}):(alert(n.message),$.unblockUI())},function(){alert("Failed saving new user")})});$("#PrincipalOrganizations").on("change",function(){$("span","#Groups").hide(),$("#GroupsLabel").html(""),$("#PrincipalOrganizations").val()!==""&&($("#GroupsLabel").text("Groups for "+$("option:selected","#PrincipalOrganizations").text()+":"),$("span[data-org-id="+$("#PrincipalOrganizations").val()+"]").show().css("display","block"))});$("#UserName").focus()})}(),function(){$("#Content").data("currentView")==="Principal/Logon"&&$(function(){app.openLogonDialog()})}(),function(){$("#Content").data("currentView")==="Group/Index"&&$(function(){$("#ResetTabletsButton").button(),$("#NewGroupButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#NewGroupButton").on("click",function(){window.location=app.vroot()+"Group/New"})})}(),function(){$("#Content").data("currentView")==="Group/New"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Group/"});$("#SaveButton").on("click",function(){var n;if($.trim($("#GroupName").val())===""){alert("Name is required");return}if($.trim($("#GroupDescription").val())===""){alert("Description is required");return}$.blockUI();var r=$.trim($("#GroupName").val()),u=$.trim($("#GroupDescription").val()),i=[],t=$(".js-role-checkbox:checked");for(n=0;n<t.length;n++)i.push($(t[n]).val());app.post(app.vroot()+"Group/SaveNew/0",{name:r,description:u,roles:i},function(){window.location=app.vroot()+"Group/"},function(){alert("Save Failed"),$.unblockUI()})});$("#GroupName").focus()})}(),function(){$("#Content").data("currentView")==="Group/Edit"&&$(function(){$("#CancelButton").button(),$("#DeleteButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Group/"});$("#DeleteButton").on("click",function(){if(confirm("Are you sure you want to Delete this Group?")){$.blockUI();var n=$("#GroupIdHidden").val();app.post(app.vroot()+"Group/Delete/"+n,null,function(){window.location=app.vroot()+"Group/"},function(){alert("Delete Failed"),$.unblockUI()})}});$("#SaveButton").on("click",function(){var n;if($.trim($("#GroupName").val())===""){alert("Name is required");return}if($.trim($("#GroupDescription").val())===""){alert("Description is required");return}$.blockUI();var r=$("#GroupIdHidden").val(),f=$.trim($("#GroupName").val()),u=$.trim($("#GroupDescription").val()),t=[],i=$(".js-role-checkbox:checked");for(n=0;n<i.length;n++)t.push($(i[n]).val());app.post(app.vroot()+"Group/SaveEdit/"+r,{id:r,name:f,description:u,roles:t},function(){window.location=app.vroot()+"Group/"},function(){alert("Save Failed"),$.unblockUI()})});$("#GroupName").focus()})}(),function(){$("#Content").data("currentView")==="Organization/Index"&&$(function(){$("#ResetTabletsButton").button(),$("#NewOrganizationButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#NewOrganizationButton").on("click",function(){window.location=app.vroot()+"Organization/New"})})}(),function(){$("#Content").data("currentView")==="Organization/New"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#OrganizationImageInput").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)if(t.type.match("image.*"))return $.blockUI({message:"<h1>Please Wait<\/h1>"}),i=new FileReader,i.onload=function(){return function(n){var i=n.target.result.substring(n.target.result.indexOf(",")+1),t=n.target.result.substring(0,n.target.result.indexOf(",")+1);$("<img/>").attr("src",t+i).load(function(){var r=this.width,n=this.height,u=!0;return r>300||n>150?confirm("Warning: This image is too large.  The image you uploaded is "+r+"px x "+n+"px.  We recommend a maximum size of 300px x 150px.  Are you sure you want to use this image?")||(u=!1):(r<96||n<48)&&(confirm("Warning: This image is too small.  The image you uploaded is "+r+"px x "+n+"px.  We recommend a minimum size of 96px x 48px.  Are you sure you want to use this image?")||(u=!1)),u&&$("#OrganizationImage").attr("src",t+i).show(),$.unblockUI(),!1})}}(t),i.readAsDataURL(t),!1;return!1});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Organization/"});$("#SaveButton").on("click",function(){var f,i,u,r,n;if($.trim($("#OrganizationName").val())===""){alert("Name is required");return}if($(".js-group-checkbox:checked").length===0){alert("You must select at least one group");return}$.blockUI();var h=$.trim($("#OrganizationName").val()),c=$("#ParentOrganization").val(),s=!1;for($("#ActiveStatus").is(":checked")&&(s=!0),f=[],i=$(".js-group-checkbox:checked"),n=0;n<i.length;n++)f.push($(i[n]).val());for(u=[],r=$(".js-type-checkbox:checked"),n=0;n<r.length;n++)u.push($(r[n]).val());var o=null,e=null,t=$("#OrganizationImage").attr("src");t!==null&&t!==undefined&&t!==""&&(o=t.substring(t.indexOf(",")+1),e=t.substring(0,t.indexOf(",")+1)),app.post(app.vroot()+"Organization/SaveNew/0",{name:h,parentOrganization:c,isActive:s,groupString:f.join(","),inspectionTypes:u,mimeType:e,imageData:o},function(){window.location=app.vroot()+"Organization/"},function(){alert("Save Failed"),$.unblockUI()})});$("#OrganizationName").focus()})}(),function(){$("#Content").data("currentView")==="Organization/Edit"&&$(function(){$("#CancelButton").button(),$("#DeleteButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#OrganizationImageInput").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)if(t.type.match("image.*"))return $.blockUI({message:"<h1>Please Wait<\/h1>"}),i=new FileReader,i.onload=function(){return function(n){var i=n.target.result.substring(n.target.result.indexOf(",")+1),t=n.target.result.substring(0,n.target.result.indexOf(",")+1);$("<img/>").attr("src",t+i).load(function(){var r=this.width,n=this.height,u=!0;return r>300||n>150?confirm("Warning: This image is too large.  The image you uploaded is "+r+"px x "+n+"px.  We recommend a maximum size of 300px x 150px.  Are you sure you want to use this image?")||(u=!1):(r<96||n<48)&&(confirm("Warning: This image is too small.  The image you uploaded is "+r+"px x "+n+"px.  We recommend a minimum size of 96px x 48px.  Are you sure you want to use this image?")||(u=!1)),u&&$("#OrganizationImage").attr("src",t+i).show(),$.unblockUI(),!1})}}(t),i.readAsDataURL(t),!1;return!1});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Organization/"});$("#DeleteButton").on("click",function(){if(confirm("Are you sure you want to Delete this Organization?")){$.blockUI();var n=$("#OrganizationIdHidden").val();app.post(app.vroot()+"Organization/Delete/"+n,null,function(){window.location=app.vroot()+"Organization/"},function(){alert("Delete Failed"),$.unblockUI()})}});$("#SaveButton").on("click",function(){var f,i,u,r,n;if($.trim($("#OrganizationName").val())===""){alert("Name is required");return}if($(".js-group-checkbox:checked").length===0){alert("You must select at least one group");return}$.blockUI();var s=$("#OrganizationIdHidden").val(),c=$.trim($("#OrganizationName").val()),l=$("#ParentOrganization").val(),h=!1;for($("#ActiveStatus").is(":checked")&&(h=!0),f=[],i=$(".js-group-checkbox:checked"),n=0;n<i.length;n++)f.push($(i[n]).val());for(u=[],r=$(".js-type-checkbox:checked"),n=0;n<r.length;n++)u.push($(r[n]).val());var e=null,o=null,t=$("#OrganizationImage").attr("src");t!==null&&t!==undefined&&t!==""&&(e=t.substring(t.indexOf(",")+1),o=t.substring(0,t.indexOf(",")+1)),app.post(app.vroot()+"Organization/SaveEdit/"+s,{id:s,name:c,parentOrganization:l,isActive:h,groupString:f.join(","),inspectionTypes:u,mimeType:o,imageData:e},function(){window.location=app.vroot()+"Organization/"},function(){alert("Save Failed"),$.unblockUI()})});$("#OrganizationName").focus()})}(),function(){$("#Content").data("currentView")==="Form/Index"&&$(function(){$("#NewFormButton").button(),$("#AdminButton").addClass("ui-active");$("#SearchForms").on("input",function(){var n=$(this).val().toUpperCase();$("tr","tbody").each(function(){n==""||$(this).find("a").text().toUpperCase().indexOf(n.trim())>=0||$(this).children()[3].textContent.toUpperCase().indexOf(n.trim())>=0?$(this).show():$(this).hide().next().hide()})});$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#NewFormButton").on("click",function(){window.location=app.vroot()+"Form/New"});$(".js-up-form").button({text:!1,icons:{primary:"ui-icon-admin-up"}}),$(".js-down-form").button({text:!1,icons:{primary:"ui-icon-admin-down"}});$("#AdminTable").on("click",".js-up-form",function(){var n=$(this).data("id");$.ajax({type:"POST",url:app.vroot()+"Form/MoveUp/"+n,data:JSON.stringify({id:n,showInactive:$("#ShowInactiveForms").is(":checked")}),contentType:"application/json; charset=utf-8",success:function(){var t=$("#ShowInactiveForms").is(":checked");window.location=app.vroot()+"Form?showInactive="+t+"&formId="+n},error:function(){alert("Move Up Failed")}})});$("#AdminTable").on("click",".js-down-form",function(){var n=$(this).data("id");$.ajax({type:"POST",url:app.vroot()+"Form/MoveDown/"+n,data:JSON.stringify({id:n,showInactive:$("#ShowInactiveForms").is(":checked")}),contentType:"application/json; charset=utf-8",success:function(){var t=$("#ShowInactiveForms").is(":checked");window.location=app.vroot()+"Form?showInactive="+t+"&formId="+n},error:function(){alert("Move Up Failed")}})});$("#ShowInactiveForms").on("change",function(){var n=$(this).is(":checked");window.location=app.vroot()+"Form?showInactive="+n});var n=Wndsr.getUrlParam("formId");n!==null&&n!==undefined&&n!==""&&$("button[data-id="+n+"]").parent().parent()[0].scrollIntoView()})}(),function(){$("#Content").data("currentView")==="Form/New"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active"),$("#SelectTemplateExamples").button();$("#SelectTemplateExamples").on("click",function(){$("#TemplateDialog").dialog("open")});$("#TemplateDialog").dialog({title:"Select Report Template",autoOpen:!1,modal:!0,resizable:!1,width:"auto",open:function(){var n=$("#FormReportTemplate").val();$(".js-report-template").prop("checked",!1),$(".js-report-template[value='"+n+"']").attr("checked","checked")},buttons:{Select:function(){var n=$(".js-report-template:checked").val();if(n===""||n===undefined||n===null)return alert("You must select a template."),!1;$("#FormReportTemplate").val(n),$("#TemplateDialog").dialog("close")},Cancel:function(){$("#TemplateDialog").dialog("close")}}});$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Form/"});$("#SaveButton").on("click",function(){var t,n;if($.trim($("#FormName").val())===""){alert("Name is required.");return}if($.trim($("#FormOrganization").val())===""){alert("Organization Owning Form is required.");return}$.blockUI();var o=$.trim($("#FormName").val()),h=$("#FormOrganization").val(),f=!1,a=!1,e=!1,s=$("#FormReportTemplate").val(),l=$("#BlankFormReportTemplate").val(),c=$("#FormDisplayAfter").val(),i="",u=!1,r=!1;for($("#ActiveStatus").is(":checked")&&(f=!0),$("#ReferenceDescriptionTrue").is(":checked")&&(e=!0),$("#IsShowViolationsYes").is(":checked")&&(u=!0),$("#IsShowScoresYes").is(":checked")&&(r=!0),t=$(".js-type-checkbox:checked"),n=0;n<t.length;n++)n>0&&(i+=","),i+=$(t[n]).val();app.post(app.vroot()+"Form/SaveNew/0",{formName:o,owningOrganization:h,isActive:f,isShowReferenceDesc:e,reportTemplate:s,blankReportTemplate:l,displayAfter:c,inspectionTypes:i,isShowViolations:u,isShowScores:r},function(n){n.error!==undefined?(alert(n.error),$.unblockUI()):window.location=app.vroot()+"Form"},function(){alert("Save Failed"),$.unblockUI()})});$("#FormName").focus()})}(),function(){$("#Content").data("currentView")==="Form/Edit"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active"),$("#ImportButton").button(),$("#SelectTemplateExamples").button();$("#SelectTemplateExamples").on("click",function(){$("#TemplateDialog").dialog("open")});$("#TemplateDialog").dialog({title:"Select Report Template",autoOpen:!1,modal:!0,resizable:!1,width:"auto",open:function(){var n=$("#FormReportTemplate").val();$(".js-report-template").prop("checked",!1),$(".js-report-template[value='"+n+"']").attr("checked","checked")},buttons:{Select:function(){var n=$(".js-report-template:checked").val();if(n===""||n===undefined||n===null)return alert("You must select a template."),!1;$("#FormReportTemplate").val(n),$("#TemplateDialog").dialog("close")},Cancel:function(){$("#TemplateDialog").dialog("close")}}}),$("#ImportDialog").dialog({title:"Select File to Import",autoOpen:!1,modal:!0,resizable:!1,height:200,minHeight:200,width:450,minWidth:450,buttons:{OK:function(){if($("#ImportUpload").val()==="")alert("Please choose a file to import");else if($("#ImportUpload").val().match(/.xml$/)){var n=$("#FormIdHidden").val();$.blockUI(),file=$("#ImportUpload")[0].files[0],fileReader=new FileReader,fileReader.onload=function(){app.post(app.vroot()+"Form/Import/"+n,{id:n,importData:fileReader.result},function(n){n.success?($("#ImportDialog").dialog("close"),window.location.reload()):(alert(n.errorMessage),$("#ImportDialog").dialog("close"),$.unblockUI())},function(){alert("Unable to import file, cannot access file."),$("#ImportDialog").dialog("close"),$.unblockUI()})},fileReader.onerror=function(){alert("Unable to import file, cannot read file."),$.unblockUI()},fileReader.readAsText(file)}else alert("Unable to import file, must be an XML file.")},Cancel:function(){$("#ImportDialog").dialog("close")}}});$("#ImportButton").on("click",function(){var n=!0;$("#FormIsDraft").val()==="True"&&(n=confirm("Importing a new version will inactivate your current draft version, do you want to continue?")),n&&($("#ImportUpload").val(""),$("#ImportDialog").dialog("open"))});$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"Form/"});$("#SaveButton").on("click",function(){var i,n;if($.trim($("#FormName").val())===""){alert("Name is required.");return}if($.trim($("#FormOrganization").val())===""){alert("Organization Owning Form is required.");return}$.blockUI();var r=$("#FormIdHidden").val(),s=$.trim($("#FormName").val()),c=$("#FormOrganization").val(),e=!1,l=!1,o=!1,h=$("#FormReportTemplate").val(),a=$("#BlankFormReportTemplate").val(),t="",f=!1,u=!1;for($("#ActiveStatus").is(":checked")&&(e=!0),$("#DraftStatus").is(":checked")&&(l=!0),$("#ReferenceDescriptionTrue").is(":checked")&&(o=!0),$("#IsShowViolationsYes").is(":checked")&&(f=!0),$("#IsShowScoresYes").is(":checked")&&(u=!0),i=$(".js-type-checkbox:checked"),n=0;n<i.length;n++)n>0&&(t+=","),t+=$(i[n]).val();app.post(app.vroot()+"Form/SaveEdit/"+r,{id:r,formName:s,owningOrganization:c,isActive:e,isShowReferenceDesc:o,reportTemplate:h,blankReportTemplate:a,inspectionTypes:t,isShowViolations:f,isShowScores:u},function(n){n.error!==undefined?(alert(n.error),$.unblockUI()):window.location=app.vroot()+"Form"},function(){alert("Save Failed"),$.unblockUI()})});$("#FormName").focus()})}(),function(){var f=!1,t=!1,i=!1,u=!1,r=null,n;$("#Content").data("currentView")==="FormControl/New"&&(app.setupFormulaBuilder=function(n,t){return $(n).removeClass("invalid-formula"),System.import("global-adapter-js").then(function(n){return n.default.compile=function(n){var t=$(n)[0];return function(){return t}},System.import("formula-editor-js")}).then(function(i){var e=t?t.validationEnabled:!0,u,f;if(n&&!n.tagName){if($(n).size()==0)return;n=n[0]}return u=[],t&&t.values&&Object.keys(t.values).forEach(function(n){var f='Value of control "'+t.values[n].control.label+'" from "'+t.values[n].sectionName+'" section',r=new i.TemplateHint(n,f);u.push(r)}),f={buttonContainer:n.nextElementSibling.firstElementChild,templateHints:u,templateParser:function(n,i,r){var e,u;if(n=n.replace(/`/g,""),e="`"+n+"`",t&&t.values&&Object.keys(t.values).indexOf(n)==-1)return new Error("Invalid Tag: "+n);if(i&&r!=null){var o=undefined,f=i[r+1],s=t.values[n].control;if(f&&f.type==="StaticIndexer"&&f.value=="."&&(u=i[r+2],u))if(u.type==="Identifier")o=u.value;else return new Error("Invalid Tag: "+e+f.value+u.value)}},onChange:function(t,i){if(t.errors&&t.errors.length){var r=t.errors.length==1?t.errors[0].message:"<ul>"+t.errors.map(function(n){return"<li>"+n.message+"<\/li>"}).join("")+"<\/ul>";$.validator.addMethod("invalid-formula",function(){return!t.errors||!t.errors.length},r),$(n).removeClass("invalid-formula").addClass("invalid-formula")}$(n).val(i),n.form&&$(n).valid()}},r=new i.FormulaEditor(n,f)})},n=function(){$(".js-control-option").hide();var n=$("#ContentType").val();switch(n){case"instructions.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").hide(),$("#ReferenceCitationSpan").hide(),$("#ReferenceCitationDescriptionSpan").hide(),$("#QuestionHelpSpan").hide(),$("#ViolationSpan").hide(),$("#TagsSpan").hide(),$("#IntegrationContextSpan").hide(),$("#UserInputAllowedSpan").hide(),$("#ShowOnReportSpan").hide(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"number.html":$("#AutoMarkSpan").show(),$("#AutoMarkSpanLessThan").show(),$("#AutoMarkSpanGreaterThan").show(),$("#AutoMarkViolationLabel").text("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value equals:"),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"date.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"time.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"url.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"location.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"signature.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"drawing.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"text.html":$("#AutoMarkSpan").show(),$("#OptionUseMaxLength").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkViolationLabel").text("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value contains:"),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"yesno.html":$("#AutoMarkSpan").hide(),$("#OptionIncludeNA").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").show(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"singleselect.html":$("#AutoMarkSpan").hide(),$("#OptionUseRadioButtons").show(),$("#OptionList").show(),$("#OptionListLabel").text("Options:").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").show(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"categorysingleselect.html":$("#AutoMarkSpan").hide(),$("#OptionUseRadioButtons").hide(),$("#OptionList").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").show(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").show(),$("#CategoryOptionList").show(),$("#OptionHasScore").hide();break;case"multiselect.html":$("#AutoMarkSpan").hide(),$("#OptionUseCheckboxes").show(),$("#OptionList").show(),$("#OptionListLabel").text("Options:").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").show(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"formattedtext.html":$("#AutoMarkSpan").show(),$("#OptionUseMaxLength").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#AutoMarkViolationLabel").text("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value contains:"),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"table.html":$("#AutoMarkSpan").hide(),$("#OptionListLabel").text("Columns:"),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#OptionCanAddRows").show(),$("#OptionCanDeleteRows").show(),$("#ColumnList").show(),$("#OptionList").show(),$("#OptionListLabel").text("Default Value for first column:"),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"locationtable.html":$("#AutoMarkSpan").hide(),$("#OptionList").show(),$("#OptionListLabel").text("Columns:"),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide()}},$(function(){var e,f,r;$("#CancelButton").button(),$("#SaveButton").button(),$("#AddOption").button(),$("#EditOption").button({disabled:!0}),$("#RemoveOption").button({disabled:!0}),$("#MoveUpOption").button({disabled:!0}),$("#MoveDownOption").button({disabled:!0}),$("#AddColumn").button(),$("#EditColumn").button({disabled:!0}),$("#RemoveColumn").button({disabled:!0}),$("#MoveUpColumn").button({disabled:!0}),$("#MoveDownColumn").button({disabled:!0}),$("#AddCategory").button(),$("#EditCategory").button({disabled:!0}),$("#RemoveCategory").button({disabled:!0}),$("#AddCategoryOption").button({disabled:!0}),$("#EditCategoryOption").button({disabled:!0}),$("#RemoveCategoryOption").button({disabled:!0}),u||(e=$("#FormVersionIdHidden").val(),f={},f.values={},app.post(app.vroot()+"FormVersion/GetAllTags/"+$("#FormVersionId").val(),{id:$("#FormVersionId").val()},function(n){for(var t=0;t<n.items.length;t++)f.values[n.items[t].tag]={sectionName:n.items[t].sectionName,control:n.items[t].control};app.setupFormulaBuilder($("#VisibilityFormula"),f),u=!0},function(){alert("Failed getting tags")})),$("#ColumnDialog").dialog({title:"Enter Column Details",autoOpen:!1,modal:!0,resizable:!1,height:500,minHeight:500,width:500,minWidth:500,dialogClass:"js-column-dialog",buttons:{Save:function(){var e=$.trim($("#ColumnName").val()),f=$("#ColumnType").val(),c=$("#ColumnJustification").val(),u=$.trim($("#ColumnWidth").val()),s=!0,h=!1,i,o,r,n;if($("#ColumnReadOnly").is(":checked")&&(s=!1),$("#ColumnRequired").is(":checked")&&(h=!0),i=$.trim($("#ColumnDefaultValue").val()),e.length===0){alert("Name is required.");return}if(u.length>0){if(!Wndsr.isNumericInteger(u)){alert("Width must be a whole number or blank.");return}if(o=parseFloat(u),o>100){alert("Width must be less than 100.");return}if(o<=0){alert("Width must be greater than 0.");return}}if(i.length>0){if(f==="Number"&&!Wndsr.isNumeric(i)){alert("Default Value must be a number or blank.");return}if(f==="Date"&&!Wndsr.isValidDate(i)){alert("Default Value must be a valid date or blank.");return}if(f==="Time"&&!Wndsr.isValidTime(i.toLocaleLowerCase())){alert("Default Value must be a valid time or blank.");return}if(f==="Checkbox"&&i.toUpperCase()!=="CHECKED"&&i.toUpperCase()!=="UNCHECKED"){alert("Default Value must be checked, unchecked, or blank.");return}}r={},r.name=e,r.type=f,r.justification=c,r.width=u,r.isReadOnly=s,r.isRequired=h,r.defaultValue=i,n="",n+="<td>"+e+"<\/td>",n+="<td>"+f+"<\/td>",n+="<td>"+c+"<\/td>",n+=u.length>0?"<td>"+u+"%<\/td>":"<td>"+u+"<\/td>",n+=s?"<td>No<\/td>":"<td>Yes<\/td>",n+=h?"<td>Yes<\/td>":"<td>No<\/td>",n+=i.length>10?"<td>"+i.substring(0,10)+"...<\/td>":"<td>"+i+"<\/td>",t?(n="<tr>"+n+"<\/tr>",$("tbody","#ColumnTable").append(n),$("tr","#ColumnTable tbody").last().data("columnDefinition",r)):($(".selectedColumnRow","#ColumnTable").html(n),$(".selectedColumnRow","#ColumnTable").data("columnDefinition",r)),$("#ColumnDialog").dialog("close")},Cancel:function(){$("#ColumnDialog").dialog("close")}}}),$("#CategoryOptionDialog").dialog({title:"Enter Option Details",autoOpen:!1,modal:!0,resizable:!1,height:310,minHeight:310,width:500,minWidth:500,dialogClass:"js-category-dialog",buttons:{Save:function(){var t=$("#CategoryOptionCategory").val(),n=$("#CategoryOptionText").val().trim(),f=$("#CategoryOptionScore").val().trim(),u,s,e,o,h;if(t===undefined||t===null||t===""){alert("Category is required");return}if(n===undefined||n===null||n===""){alert("Text is required");return}for(u=t+" - "+n,f!==undefined&&f!==null&&f!==""&&(u+=" ("+f+")"),s=$("#CategoryOptionListSelect option"),e=0;e<s.length;e++)if($(s[e]).text()===u){alert("This option already exists");return}i?(o=$("<option/>",{text:u}).attr("category",t).attr("text",n).attr("score",f),$("#CategoryOptionListSelect").append(o),$("#AutoMarkViolationSelect").append(o.clone())):(h=$("#CategoryOptionListSelect option:selected").index(),$("#CategoryOptionListSelect option:selected").text(u).attr("category",t).attr("text",n).attr("score",f),$($("#AutoMarkViolationSelect").children()[h]).text(u).attr("category",t).attr("text",n)),r("#CategoryOptionListSelect"),r("#AutoMarkViolationSelect"),$("#CategoryOptionDialog").dialog("close")},Cancel:function(){$("#CategoryOptionDialog").dialog("close")}}}),$("#OptionDialog").dialog({title:"Enter Option Details",autoOpen:!1,modal:!0,resizable:!1,height:250,minHeight:250,width:500,minWidth:500,dialogClass:"js-category-dialog",buttons:{Save:function(){var i=$("#SelectedOptionIndex").val(),n=$("#OptionText").val().trim(),t=$("#OptionScore").val().trim();if(n===""){alert("Text is required");return}i==""?t!==""?($("#OptionListSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+" ("+t+")<\/option>"),$("#AutoMarkViolationSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+" ("+t+")<\/option > ")):($("#OptionListSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+"<\/option>"),$("#AutoMarkViolationSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+"<\/option > ")):t!==""?($("#OptionListSelect option:selected").text(n+" ("+t+")"),$("#OptionListSelect option:selected").data("score",t),$("#OptionListSelect option:selected").data("text",n),$($("#AutoMarkViolationSelect").children()[i]).text(n+" ("+t+")"),$($("#AutoMarkViolationSelect").children()[i]).data("score",t),$($("#AutoMarkViolationSelect").children()[i]).data("text",n)):($("#OptionListSelect option:selected").text(n),$("#OptionListSelect option:selected").data("score",t),$("#OptionListSelect option:selected").data("text",n),$($("#AutoMarkViolationSelect").children()[i]).text(n),$($("#AutoMarkViolationSelect").children()[i]).data("score",t),$($("#AutoMarkViolationSelect").children()[i]).data("text",n)),$("#OptionDialog").dialog("close")},Cancel:function(){$("#OptionDialog").dialog("close")}}});$("#AddOption").on("click",function(){$("#SelectedOptionIndex").val(""),$("#OptionText").val(""),$("#OptionScore").val(""),$("#OptionDialog").dialog("open")});$("#EditOption").on("click",function(){var i=$("#OptionListSelect option:selected").data("text"),t=$("#OptionListSelect option:selected").data("score"),n=$("#OptionListSelect option:selected").index();$("#SelectedOptionIndex").val(n),$("#OptionText").val(i),$("#OptionScore").val(t),$("#OptionDialog").dialog("open")});$("#MoveUpOption").on("click",function(){var i=$("#OptionListSelect option:selected").index(),t=$("#OptionListSelect option:selected"),n;t.first().prev().before(t),n=$($("#AutoMarkViolationSelect").children()[i]),n.first().prev().before(n),$("#OptionListSelect").trigger("change")});$("#MoveDownOption").on("click",function(){var i=$("#OptionListSelect option:selected").index(),t=$("#OptionListSelect option:selected"),n;t.last().next().after(t),n=$($("#AutoMarkViolationSelect").children()[i]),n.last().next().after(n),$("#OptionListSelect").trigger("change")});$("#RemoveOption").on("click",function(){var n=$("#OptionListSelect option:selected").index();$("#OptionListSelect option:selected").remove(),$($("#AutoMarkViolationSelect").children()[n]).remove(),$("#EditOption").button("disable"),$("#RemoveOption").button("disable"),$("#MoveUpOption").button("disable"),$("#MoveDownOption").button("disable")});$("#OptionListSelect").on("change",function(){var n=$("#OptionListSelect").prop("selectedIndex"),t=$("option","#OptionListSelect").length;n===0?$("#MoveUpOption").button("disable"):$("#MoveUpOption").button("enable"),n==t-1?$("#MoveDownOption").button("disable"):$("#MoveDownOption").button("enable"),$("#EditOption").button("enable"),$("#RemoveOption").button("enable"),n===-1&&($("#EditOption").button("disable"),$("#RemoveOption").button("disable"),$("#MoveUpOption").button("disable"),$("#MoveDownOption").button("disable"))});$("#MoveUpColumn").on("click",function(){var t=$("#ColumnTable tbody tr.selectedColumnRow").index(),n=$("#ColumnTable tbody tr.selectedColumnRow");n.first().prev().before(n),$(n).trigger("click")});$("#MoveDownColumn").on("click",function(){var t=$("#ColumnTable tbody tr.selectedColumnRow").index(),n=$("#ColumnTable tbody tr.selectedColumnRow");n.last().next().after(n),$(n).trigger("click")});$("#RemoveColumn").on("click",function(){var n=$("#ColumnTable tbody tr.selectedColumnRow").index();$("#ColumnTable tbody tr.selectedColumnRow").remove(),$("#EditColumn").button("disable"),$("#RemoveColumn").button("disable"),$("#MoveUpColumn").button("disable"),$("#MoveDownColumn").button("disable")});$("#AddColumn").on("click",function(){t=!0,$(".selectedColumnRow","#ColumnTable").removeClass("selectedColumnRow"),$("#EditColumn").button("disable"),$("#RemoveColumn").button("disable"),$("#MoveUpColumn").button("disable"),$("#MoveDownColumn").button("disable"),$("#ColumnName").val(""),$("#ColumnType").val("Text"),$("#ColumnJustification").val("Left"),$("#ColumnWidth").val(""),$("#ColumnReadOnly").prop("checked",!0),$("#ColumnRequired").prop("checked",!1),$("#ColumnDefaultValue").val(""),$(".js-column-dialog .ui-button-text:contains(Save)").text("Add"),$("#ColumnDialog").dialog("option","title","Add Column"),$("#ColumnDialog").dialog("open")});$("#EditColumn").on("click",function(){t=!1;var n=$(".selectedColumnRow","#ColumnTable").data("columnDefinition");$("#ColumnName").val(n.name),$("#ColumnType").val(n.type),$("#ColumnJustification").val(n.justification),$("#ColumnWidth").val(n.width),n.isReadOnly?$("#ColumnReadOnly").prop("checked",!1):$("#ColumnReadOnly").prop("checked",!0),n.isRequired?$("#ColumnRequired").prop("checked",!0):$("#ColumnRequired").prop("checked",!1),$("#ColumnDefaultValue").val(n.defaultValue),$(".js-column-dialog .ui-button-text:contains(Add)").text("Save"),$("#ColumnDialog").dialog("option","title","Edit Column"),$("#ColumnDialog").dialog("open")});$("#ColumnTable tbody").on("click","tr",function(){$("tr","#ColumnTable tbody").removeClass("selectedColumnRow"),$(this).addClass("selectedColumnRow"),$(this).is(":first-child")?$("#MoveUpColumn").button("disable"):$("#MoveUpColumn").button("enable"),$(this).is(":last-child")?$("#MoveDownColumn").button("disable"):$("#MoveDownColumn").button("enable"),$("#EditColumn").button("enable"),$("#RemoveColumn").button("enable")});$("#AddCategory").on("click",function(){var n=prompt("Enter Category:"),i,t;if(n!==null&&n!==""&&n.trim().length>0){for(n=n.trim(),i=$("#CategoryListSelect option"),t=0;t<i.length;t++)if($(i[t]).text()===n){alert("This category already exists");return}$("#CategoryListSelect").append("<option>"+n+"<\/option>"),r("#CategoryListSelect"),$("#CategoryOptionCategory").children().remove(),$("#CategoryOptionCategory").append('<option value="" selected="selected"><\/option>'),$("#CategoryOptionCategory").append($("#CategoryListSelect option").clone()),$("#AddCategoryOption").button("enable")}});$("#EditCategory").on("click",function(){var o=$("#CategoryListSelect option:selected").text(),t=prompt("Enter Category:",o),e,s,i,f,n,u;if(t!==null&&t!==""&&t.trim().length>0&&o!==t){for(t=t.trim(),e=$("#CategoryListSelect option"),n=0;n<e.length;n++)if($(e[n]).text()===t){alert("This category already exists");return}for(s=$("#OptionListSelect option:selected").index(),$("#CategoryListSelect option:selected").text(t),r("#CategoryListSelect"),$("#CategoryOptionCategory").children().remove(),$("#CategoryOptionCategory").append('<option value="" selected="selected"><\/option>'),$("#CategoryOptionCategory").append($("#CategoryListSelect option").clone()),i=$("#CategoryOptionListSelect option"),f=$("#AutoMarkViolationSelect option"),n=0;n<i.length;n++)$(i[n]).attr("category")===o&&(u=$(i[n]).attr("text"),$(i[n]).attr("category",t),$(i[n]).text(t+" - "+u),$(f[n]).attr("category",t),$(f[n]).text(t+" - "+u))}});$("#RemoveCategory").on("click",function(){for(var r=$("#CategoryListSelect option:selected").text(),t=$("#CategoryOptionListSelect option"),u=$("#AutoMarkViolationSelect option"),i=!1,n=0;n<t.length;n++)$(t[n]).attr("category")===r&&(i=!0);if(i)if(confirm("Removing this category will result in options assigned to this category being removed, do you want to continue?"))for(n=t.length-1;n>=0;n--)$(t[n]).attr("category")===r&&($(t[n]).remove(),$(u[n]).remove());else return;$("#CategoryListSelect option:selected").remove(),$("#CategoryOptionCategory").children().remove(),$("#CategoryOptionCategory").append('<option value="" selected="selected"><\/option>'),$("#CategoryOptionCategory").append($("#CategoryListSelect option").clone()),$("#EditCategory").button("disable"),$("#RemoveCategory").button("disable"),$("#CategoryListSelect option").length===0&&$("#AddCategoryOption").button("disable")});$("#CategoryListSelect").on("change",function(){var n=$("#CategoryListSelect").prop("selectedIndex");$("#EditCategory").button("enable"),$("#RemoveCategory").button("enable"),n===-1&&($("#EditCategory").button("disable"),$("#RemoveCategory").button("disable"))});$("#AddCategoryOption").on("click",function(){i=!0,$("#EditCategoryOption").button("disable"),$("#RemoveCategoryOption").button("disable"),$("#CategoryOptionCategory").val(""),$("#CategoryOptionText").val(""),$("#CategoryOptionScore").val(""),$(".js-category-dialog .ui-button-text:contains(Save)").text("Add"),$("#CategoryOptionDialog").dialog("option","title","Add Option"),$("#CategoryOptionDialog").dialog("open")});$("#EditCategoryOption").on("click",function(){i=!1;var t=$("#CategoryOptionListSelect option:selected").attr("category"),r=$("#CategoryOptionListSelect option:selected").attr("text"),n=$("#CategoryOptionListSelect option:selected").attr("score");$("#CategoryOptionCategory").val(t),$("#CategoryOptionText").val(r),n!==undefined&&n!==null&&n!==""?$("#CategoryOptionScore").val(n):$("#CategoryOptionScore").val(""),$(".js-category-dialog .ui-button-text:contains(Add)").text("Save"),$("#CategoryOptionDialog").dialog("option","title","Edit Option"),$("#CategoryOptionDialog").dialog("open")});$("#RemoveCategoryOption").on("click",function(){var n=$("#CategoryOptionListSelect option:selected").index();$($("#AutoMarkViolationSelect").children()[n]).remove(),$("#CategoryOptionListSelect option:selected").remove(),$("#EditCategoryOption").button("disable"),$("#RemoveCategoryOption").button("disable")});$("#CategoryOptionListSelect").on("change",function(){var n=$("#CategoryOptionListSelect").prop("selectedIndex");$("#EditCategoryOption").button("enable"),$("#RemoveCategoryOption").button("enable"),n===-1&&($("#EditCategoryOption").button("disable"),$("#RemoveCategoryOption").button("disable"))});r=function(n){var t=$(n+" option");t.sort(function(n,t){return n.text.toUpperCase()<t.text.toUpperCase()?-1:n.text.toUpperCase()===t.text.toUpperCase()?0:1}),$(t).remove(),$(n).append($(t))},n(),$("#ContentType").change(n);$("#CancelButton").on("click",function(){window.location=app.vroot()+"FormVersion/Edit/"+$("#FormVersionId").val()+"?selectedFormSection="+$("#FormSectionId").val()+"&selectedFormControl="+$("#FormControlId").val()});$("#SaveButton").on("click",function(){var f=$("#ContentType").val(),h=$("#MaxLength").val(),n=null,r=null,i=$("#QuestionScore").val(),y,s,e,o,c,l,it,ut,u,t,d,b,et;try{if(f==="text.html"){if(h==="")return alert("Text controls require a maxLength property"),!1;if(!Wndsr.isNumericInteger(h))return alert("Text controls require an integer maxLength property"),!1;n={},n.maxLength=parseInt(h),i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i)),c=$("#AutoViolation").val().trim(),c.length>0&&(r={},r.answer=c)}else if(f==="date.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(f==="location.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(f==="time.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(f==="url.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(f==="number.html"){var g=$("#AutoViolation").val(),nt=$("#AutoViolationLessThan").val(),tt=$("#AutoViolationGreaterThan").val();if(g!==""){if(!Wndsr.isNumericInteger(g))return alert("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value equals must be an interger"),!1;r===null&&(r={}),r.equals=parseInt(g)}if(nt!==""){if(!Wndsr.isNumericInteger(nt))return alert("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value is less than must be an interger"),!1;r===null&&(r={}),r.lessThan=parseInt(nt)}if(tt!==""){if(!Wndsr.isNumericInteger(tt))return alert("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value is greater than must be an interger"),!1;r===null&&(r={}),r.greaterThan=parseInt(tt)}n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i))}else if(f==="yesno.html")$("#IncludeNAYes").is(":checked")?(n={},n.includeNA=!0):(n={},n.includeNA=!1),$("#AutoMarkYesNo").val()==="AutoMarkViolationYes"?(r={},r.answer="YES"):$("#AutoMarkYesNo").val()==="AutoMarkViolationNo"?(r={},r.answer="NO"):$("#AutoMarkYesNo").val()==="AutoMarkViolationNA"&&(r={},r.answer="NA");else if(f==="singleselect.html"){if(u=$("#OptionListSelect option"),u.length===0)return alert("single select controls require at least one option"),!1;for(n={},$("#UseRadioButtonsYes").is(":checked")?(n.useRadioButtons=!0,n.useFilterSelect=!1,n.useHorizontal=!1):$("#UseFilterSelect").is(":checked")?(n.useRadioButtons=!1,n.useFilterSelect=!0,n.useHorizontal=!1):$("#UseHorizontal").is(":checked")?(n.useRadioButtons=!1,n.useFilterSelect=!1,n.useHorizontal=!0):(n.useRadioButtons=!1,n.useFilterSelect=!1,n.useHorizontal=!1),n.options=[],t=0;t<u.length;t++)i=$(u[t]).data("score"),s=$(u[t]).data("text"),i===""?n.options.push({text:s}):n.options.push({score:i,text:s});if(e=$("#AutoMarkViolationSelect").children(":selected"),e.length>0){for(o=[],r={},t=0;t<e.length;t++)o.push($(e[t]).text());r.answer=o}}else if(f==="categorysingleselect.html"){if(y=$("#CategoryListSelect option"),u=$("#CategoryOptionListSelect option"),y.length===0)return alert("category single select controls require at least one category"),!1;if(u.length===0)return alert("category single select controls require at least one option"),!1;for(n={},n.categories=[],t=0;t<y.length;t++)n.categories.push($(y[t]).text());for(n.options=[],t=0;t<u.length;t++)i=$(u[t]).attr("score"),s=$(u[t]).attr("text"),i===""?n.options.push({text:s,category:$(u[t]).attr("category")}):n.options.push({score:i,text:s,category:$(u[t]).attr("category")});if(e=$("#AutoMarkViolationSelect").children(":selected"),e.length>0){for(o=[],r={},t=0;t<e.length;t++)o.push({category:$(e[t]).attr("category"),text:$(e[t]).attr("text")});r.answer=o}}else if(f==="multiselect.html"){if(u=$("#OptionListSelect option"),u.length===0)return alert("multi select controls require at least one option"),!1;for(n={},n.useCheckboxes=$("#UseCheckBoxesYes").is(":checked")?!0:!1,n.options=[],t=0;t<u.length;t++)i=$(u[t]).data("score"),s=$(u[t]).data("text"),i===""?n.options.push({text:s}):n.options.push({score:i,text:s});if(e=$("#AutoMarkViolationSelect").children(":selected"),e.length>0){for(o=[],r={},t=0;t<e.length;t++)o.push($(e[t]).text());r.answer=o}}else if(f==="formattedtext.html"){if(h==="")return alert("text paragraph control require a maxLength property"),!1;if(!Wndsr.isNumericInteger(h))return alert("text paragraph control require an integer maxLength property"),!1;n={},n.maxLength=parseInt(h),i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i)),c=$("#AutoViolation").val().trim(),c.length>0&&(r={},r.answer=c)}else if(f==="table.html"){if(l=$("tbody tr","#ColumnTable"),l.length===0)return alert("table controls require at least one column"),!1;if(l.length>10)return alert("table controls can have a maximum of 10 columns"),!1;for(n={},n.columns=[],it=!1,t=0;t<l.length;t++)ut=$(l[t]).data(),ut.columnDefinition.isReadOnly||(it=!0),n.columns.push(ut.columnDefinition);if(!it&&$.trim($("#Tags").val())==="")return alert("If none of the table columns allow input, then a Data Integration Tag must be entered."),!1;if(n.canAddRows=$("#CanAddRowsYes").is(":checked")?!0:!1,n.canDeleteRows=$("#CanDeleteRowsYes").is(":checked")?!0:!1,!n.canAddRows&&$.trim($("#Tags").val())==="")return alert("If Can Add Rows is No, then a Data Integration Tag must be entered"),!1;for(u=$("#OptionListSelect option"),n.options=[],t=0;t<u.length;t++)n.options.push($(u[t]).text())}else if(f==="locationtable.html"){if(u=$("#OptionListSelect option"),u.length===0)return alert("location table controls require at least one column"),!1;for(n={},n.options=[],t=0;t<u.length;t++)n.options.push($(u[t]).text())}if(f!=="instructions.html"){if($("#RequireReferenceForViolation").val().toUpperCase()==="TRUE"&&$("#ViolationAllowed").is(":checked")&&$.trim($("#ReferenceCitation").val())==="")return alert("If marking an answer as "+$("#ViolationPhraseSingular").val()+" is allowed, then Reference / Citation is required"),!1;if($("#UserInputNotAllowed").is(":checked")&&$.trim($("#Tags").val())==="")return alert("If user input is not allowed, then Data Integration Tags is required"),!1}}catch(yt){return alert("There was an error validing the form"),!1}var at=$("#FormSectionId").val(),rt=$.trim($("#QuestionNumber").val()),vt=$.trim($("#QuestionLetter").val()),ct=$.trim($("#QuestionText").val()),w=!1;$("#RequiredInputType").is(":checked")&&(w=!0);var f=$("#ContentType").val(),lt=$("#ReferenceCitation").val(),ht=$("#ReferenceCitationDescription").val(),st=$("#QuestionHelp").val(),k=!1;$("#ViolationAllowed").is(":checked")&&(k=!0);var a=$("#Tags").val(),v=$("#IntegrationContext").val(),ft=null,ot=null,p=!1;if($("#UserInputAllowed").is(":checked")&&(p=!0),d=!1,$("#IsShowViolation").is(":checked")&&(d=!0),b=!1,$("#ShowOnReportYes").is(":checked")&&(b=!0),et=$("#VisibilityFormula").val(),n!==null&&(ft=JSON.stringify(n)),r!==null&&(ot=JSON.stringify(r)),f==="instructions.html"&&(lt="",ht="",st="",k=!1,w=!1,p=!1,a="",r=""),rt.length===0){alert("Question Number is required");return}if(!Wndsr.isNumericInteger(rt)){alert("Question Number must be a number");return}if(ct.length===0){alert("Question Text is required");return}if(w&&!p){alert("If answer input is required, you must allow user to input an answer.");return}if(v!==null&&v!==undefined&&v!==""&&(a===null||a===undefined||a==="")){alert("If Data Integration Context is entered, then Data Integration Tags is a required field.");return}app.post(app.vroot()+"FormControl/SaveNew/0",{formSectionId:at,questionNumber:rt,questionLetter:vt,questionText:ct,isAnswerRequired:w,contentType:f,referenceCitation:lt,referenceCitationDescription:ht,questionHelp:st,isViolationAllowed:k,questionTag:a,controlDefinition:ft,autoViolation:ot,userInputAllowed:p,isShowOnReport:b,integrationContext:v,isShowViolation:d,visibilityFormula:et},function(n){window.location=app.vroot()+"FormVersion/Edit/"+n.formVersionId+"?selectedFormSection="+n.formSectionId+"&selectedFormControl="+n.formControlId},function(){alert("Save Failed"),$.unblockUI()})});$("#QuestionScore").on("blur",function(){var n=$("#QuestionScore").val();n.indexOf(".")>0&&$("#QuestionScore").val(parseFloat($("#QuestionScore").val(),10).toFixed(2))});$("#OptionScore").on("blur",function(){var n=$("#OptionScore").val();n.indexOf(".")>0&&$("#OptionScore").val(parseFloat($("#OptionScore").val(),10).toFixed(2))});$("#QuestionNumber").focus()}))}(),function(){var e=!1,r=!1,n=!1,i=!1,f=!1,u=null,t;$("#Content").data("currentView")==="FormControl/Edit"&&(app.setupFormulaBuilder=function(n,t){return $(n).removeClass("invalid-formula"),System.import("global-adapter-js").then(function(n){return n.default.compile=function(n){var t=$(n)[0];return function(){return t}},System.import("formula-editor-js")}).then(function(i){var e=t?t.validationEnabled:!0,r,f;if(n&&!n.tagName){if($(n).size()==0)return;n=n[0]}return r=[],t&&t.values&&Object.keys(t.values).forEach(function(n){var f='Value of control "'+t.values[n].control.label+'" from "'+t.values[n].sectionName+'" section',u=new i.TemplateHint(n,f);r.push(u)}),f={buttonContainer:n.nextElementSibling.firstElementChild,templateHints:r,templateParser:function(n,i,r){var e,u;if(n=n.replace(/`/g,""),e="`"+n+"`",t&&t.values&&Object.keys(t.values).indexOf(n)==-1)return new Error("Invalid Tag: "+n);if(i&&r!=null){var o=undefined,f=i[r+1],s=t.values[n].control;if(f&&f.type==="StaticIndexer"&&f.value=="."&&(u=i[r+2],u))if(u.type==="Identifier")o=u.value;else return new Error("Invalid Tag: "+e+f.value+u.value)}},onChange:function(t,i){if(t.errors&&t.errors.length){var r=t.errors.length==1?t.errors[0].message:"<ul>"+t.errors.map(function(n){return"<li>"+n.message+"<\/li>"}).join("")+"<\/ul>";$.validator.addMethod("invalid-formula",function(){return!t.errors||!t.errors.length},r),$(n).removeClass("invalid-formula").addClass("invalid-formula")}$(n).val(i),n.form&&$(n).valid()}},u=new i.FormulaEditor(n,f)})},t=function(){$(".js-control-option").hide();var n=$("#ContentType").val();switch(n){case"instructions.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").hide(),$("#ReferenceCitationSpan").hide(),$("#ReferenceCitationDescriptionSpan").hide(),$("#QuestionHelpSpan").hide(),$("#ViolationSpan").hide(),$("#TagsSpan").hide(),$("#IntegrationContextSpan").hide(),$("#UserInputAllowedSpan").hide(),$("#ShowOnReportSpan").hide(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"number.html":$("#AutoMarkSpan").show(),$("#AutoMarkSpanLessThan").show(),$("#AutoMarkSpanGreaterThan").show(),$("#AutoMarkViolationLabel").text("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value equals:"),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"date.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"time.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"url.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"location.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"signature.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"drawing.html":$("#AutoMarkSpan").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"text.html":$("#AutoMarkSpan").show(),$("#OptionUseMaxLength").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkViolationLabel").text("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value contains:"),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"yesno.html":$("#AutoMarkSpan").hide(),$("#OptionIncludeNA").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").show(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"singleselect.html":$("#AutoMarkSpan").hide(),$("#OptionUseRadioButtons").show(),$("#OptionList").show(),$("#OptionListLabel").text("Options:").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").show(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"categorysingleselect.html":$("#AutoMarkSpan").hide(),$("#OptionUseRadioButtons").hide(),$("#OptionList").hide(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").show(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").show(),$("#CategoryOptionList").show(),$("#OptionHasScore").hide();break;case"multiselect.html":$("#AutoMarkSpan").hide(),$("#OptionUseCheckboxes").show(),$("#OptionList").show(),$("#OptionListLabel").text("Options:").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").show(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"formattedtext.html":$("#AutoMarkSpan").show(),$("#OptionUseMaxLength").show(),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#AutoMarkViolationLabel").text("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value contains:"),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").show();break;case"table.html":$("#AutoMarkSpan").hide(),$("#OptionListLabel").text("Columns:"),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#OptionCanAddRows").show(),$("#OptionCanDeleteRows").show(),$("#ColumnList").show(),$("#OptionList").show(),$("#OptionListLabel").text("Default Value for first column:"),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide();break;case"locationtable.html":$("#AutoMarkSpan").hide(),$("#OptionList").show(),$("#OptionListLabel").text("Columns:"),$("#AutoMarkSpanLessThan").hide(),$("#AutoMarkSpanGreaterThan").hide(),$("#AutoMarkSpanYesNo").hide(),$("#AutoMarkSpanSelect").hide(),$("#IsAnswerRequired").show(),$("#ReferenceCitationSpan").show(),$("#ReferenceCitationDescriptionSpan").show(),$("#QuestionHelpSpan").show(),$("#ViolationSpan").show(),$("#TagsSpan").show(),$("#IntegrationContextSpan").show(),$("#UserInputAllowedSpan").show(),$("#ShowOnReportSpan").show(),$("#CategoryList").hide(),$("#CategoryOptionList").hide(),$("#OptionHasScore").hide()}},$(function(){var ft,g,v,tt,u,y,h,it,o,ut,a,l,e,rt;$("#CancelButton").button(),$("#SaveButton").button(),$("#SaveNextButton").button(),$("#AddOption").button(),$("#EditOption").button({disabled:!0}),$("#RemoveOption").button({disabled:!0}),$("#MoveUpOption").button({disabled:!0}),$("#MoveDownOption").button({disabled:!0}),$("#AddColumn").button(),$("#EditColumn").button({disabled:!0}),$("#RemoveColumn").button({disabled:!0}),$("#MoveUpColumn").button({disabled:!0}),$("#MoveDownColumn").button({disabled:!0}),$("#AddCategory").button(),$("#EditCategory").button({disabled:!0}),$("#RemoveCategory").button({disabled:!0}),$("#AddCategoryOption").button({disabled:!0}),$("#EditCategoryOption").button({disabled:!0}),$("#RemoveCategoryOption").button({disabled:!0}),f||(ft=$("#FormVersionIdHidden").val(),g={},g.values={},app.post(app.vroot()+"FormVersion/GetAllTags/"+$("#FormVersionId").val(),{id:$("#FormVersionId").val()},function(n){for(var t=0;t<n.items.length;t++)g.values[n.items[t].tag]={sectionName:n.items[t].sectionName,control:n.items[t].control};app.setupFormulaBuilder($("#VisibilityFormula"),g),f=!0},function(){alert("Failed getting tags")})),$("#ColumnDialog").dialog({title:"Enter Column Details",autoOpen:!1,modal:!0,resizable:!1,height:500,minHeight:500,width:500,minWidth:500,dialogClass:"js-column-dialog",buttons:{Save:function(){var e=$.trim($("#ColumnName").val()),f=$("#ColumnType").val(),c=$("#ColumnJustification").val(),u=$.trim($("#ColumnWidth").val()),s=!0,h=!1,i,o,r,t;if($("#ColumnReadOnly").is(":checked")&&(s=!1),$("#ColumnRequired").is(":checked")&&(h=!0),i=$.trim($("#ColumnDefaultValue").val()),e.length===0){alert("Name is required.");return}if(u.length>0){if(!Wndsr.isNumericInteger(u)){alert("Width must be a whole number or blank.");return}if(o=parseFloat(u),o>100){alert("Width must be less than 100.");return}if(o<=0){alert("Width must be greater than 0.");return}}if(i.length>0){if(f==="Number"&&!Wndsr.isNumeric(i)){alert("Default Value must be a number or blank.");return}if(f==="Date"&&!Wndsr.isValidDate(i)){alert("Default Value must be a valid date or blank.");return}if(f==="Time"&&!Wndsr.isValidTime(i.toLocaleLowerCase())){alert("Default Value must be a valid time or blank.");return}if(f==="Checkbox"&&i.toUpperCase()!=="CHECKED"&&i.toUpperCase()!=="UNCHECKED"){alert("Default Value must be checked, unchecked, or blank.");return}}r={},r.name=e,r.type=f,r.justification=c,r.width=u,r.isReadOnly=s,r.isRequired=h,r.defaultValue=i,t="",t+="<td>"+e+"<\/td>",t+="<td>"+f+"<\/td>",t+="<td>"+c+"<\/td>",t+=u.length>0?"<td>"+u+"%<\/td>":"<td>"+u+"<\/td>",t+=s?"<td>No<\/td>":"<td>Yes<\/td>",t+=h?"<td>Yes<\/td>":"<td>No<\/td>",t+=i.length>10?"<td>"+i.substring(0,10)+"...<\/td>":"<td>"+i+"<\/td>",n?(t="<tr>"+t+"<\/tr>",$("tbody","#ColumnTable").append(t),$("tr","#ColumnTable tbody").last().data("columnDefinition",r)):($(".selectedColumnRow","#ColumnTable").html(t),$(".selectedColumnRow","#ColumnTable").data("columnDefinition",r)),$("#ColumnDialog").dialog("close")},Cancel:function(){$("#ColumnDialog").dialog("close")}}}),$("#CategoryOptionDialog").dialog({title:"Enter Option Details",autoOpen:!1,modal:!0,resizable:!1,height:310,minHeight:310,width:500,minWidth:500,dialogClass:"js-category-dialog",buttons:{Save:function(){var t=$("#CategoryOptionCategory").val(),n=$("#CategoryOptionText").val().trim(),u=$("#CategoryOptionScore").val().trim(),r,o,f,e,s;if(t===undefined||t===null||t===""){alert("Category is required");return}if(n===undefined||n===null||n===""){alert("Text is required");return}for(r=t+" - "+n,u!==undefined&&u!==null&&u!==""&&(r+=" ("+u+")"),o=$("#CategoryOptionListSelect option"),f=0;f<o.length;f++)if($(o[f]).text()===r){alert("This option already exists");return}i?(e=$("<option/>",{text:r}).attr("category",t).attr("text",n).attr("score",u),$("#CategoryOptionListSelect").append(e),$("#AutoMarkViolationSelect").append(e.clone())):(s=$("#CategoryOptionListSelect option:selected").index(),$("#CategoryOptionListSelect option:selected").text(r).attr("category",t).attr("text",n).attr("score",u),$($("#AutoMarkViolationSelect").children()[s]).text(r).attr("category",t).attr("text",n)),v("#CategoryOptionListSelect"),v("#AutoMarkViolationSelect"),$("#CategoryOptionDialog").dialog("close")},Cancel:function(){$("#CategoryOptionDialog").dialog("close")}}}),$("#OptionDialog").dialog({title:"Enter Option Details",autoOpen:!1,modal:!0,resizable:!1,height:250,minHeight:250,width:500,minWidth:500,dialogClass:"js-category-dialog",buttons:{Save:function(){var i=$("#SelectedOptionIndex").val(),n=$("#OptionText").val().trim(),t=$("#OptionScore").val().trim();if(n===""){alert("Text is required");return}i==""?t!==""?($("#OptionListSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+" ("+t+")<\/option>"),$("#AutoMarkViolationSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+" ("+t+")<\/option > ")):($("#OptionListSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+"<\/option>"),$("#AutoMarkViolationSelect").append('<option data-text="'+n+'" data-score="'+t+' ">'+n+"<\/option > ")):t!==""?($("#OptionListSelect option:selected").text(n+" ("+t+")"),$("#OptionListSelect option:selected").data("score",t),$("#OptionListSelect option:selected").data("text",n),$($("#AutoMarkViolationSelect").children()[i]).text(n+" ("+t+")"),$($("#AutoMarkViolationSelect").children()[i]).data("score",t),$($("#AutoMarkViolationSelect").children()[i]).data("text",n)):($("#OptionListSelect option:selected").text(n),$("#OptionListSelect option:selected").data("score",t),$("#OptionListSelect option:selected").data("text",n),$($("#AutoMarkViolationSelect").children()[i]).text(n),$($("#AutoMarkViolationSelect").children()[i]).data("score",t),$($("#AutoMarkViolationSelect").children()[i]).data("text",n)),$("#OptionDialog").dialog("close")},Cancel:function(){$("#OptionDialog").dialog("close")}}});$("#AddOption").on("click",function(){$("#SelectedOptionIndex").val(""),$("#OptionText").val(""),$("#OptionScore").val(""),$("#OptionDialog").dialog("open")});$("#EditOption").on("click",function(){var i=$("#OptionListSelect option:selected").data("text"),t=$("#OptionListSelect option:selected").data("score"),n=$("#OptionListSelect option:selected").index();$("#SelectedOptionIndex").val(n),$("#OptionText").val(i),$("#OptionScore").val(t),$("#OptionDialog").dialog("open")});$("#MoveUpOption").on("click",function(){var i=$("#OptionListSelect option:selected").index(),t=$("#OptionListSelect option:selected"),n;t.first().prev().before(t),n=$($("#AutoMarkViolationSelect").children()[i]),n.first().prev().before(n),$("#OptionListSelect").trigger("change")});$("#MoveDownOption").on("click",function(){var i=$("#OptionListSelect option:selected").index(),t=$("#OptionListSelect option:selected"),n;t.last().next().after(t),n=$($("#AutoMarkViolationSelect").children()[i]),n.last().next().after(n),$("#OptionListSelect").trigger("change")});$("#RemoveOption").on("click",function(){var n=$("#OptionListSelect option:selected").index();$("#OptionListSelect option:selected").remove(),$($("#AutoMarkViolationSelect").children()[n]).remove(),$("#EditOption").button("disable"),$("#RemoveOption").button("disable"),$("#MoveUpOption").button("disable"),$("#MoveDownOption").button("disable")});$("#OptionListSelect").on("change",function(){var n=$("#OptionListSelect").prop("selectedIndex"),t=$("option","#OptionListSelect").length;n===0?$("#MoveUpOption").button("disable"):$("#MoveUpOption").button("enable"),n==t-1?$("#MoveDownOption").button("disable"):$("#MoveDownOption").button("enable"),$("#EditOption").button("enable"),$("#RemoveOption").button("enable"),n===-1&&($("#EditOption").button("disable"),$("#RemoveOption").button("disable"),$("#MoveUpOption").button("disable"),$("#MoveDownOption").button("disable"))});$("#MoveUpColumn").on("click",function(){var t=$("#ColumnTable tbody tr.selectedColumnRow").index(),n=$("#ColumnTable tbody tr.selectedColumnRow");n.first().prev().before(n),$(n).trigger("click")});$("#MoveDownColumn").on("click",function(){var t=$("#ColumnTable tbody tr.selectedColumnRow").index(),n=$("#ColumnTable tbody tr.selectedColumnRow");n.last().next().after(n),$(n).trigger("click")});$("#RemoveColumn").on("click",function(){var n=$("#ColumnTable tbody tr.selectedColumnRow").index();$("#ColumnTable tbody tr.selectedColumnRow").remove(),$("#EditColumn").button("disable"),$("#RemoveColumn").button("disable"),$("#MoveUpColumn").button("disable"),$("#MoveDownColumn").button("disable")});$("#AddColumn").on("click",function(){n=!0,$(".selectedColumnRow","#ColumnTable").removeClass("selectedColumnRow"),$("#EditColumn").button("disable"),$("#RemoveColumn").button("disable"),$("#MoveUpColumn").button("disable"),$("#MoveDownColumn").button("disable"),$("#ColumnName").val(""),$("#ColumnType").val("Text"),$("#ColumnJustification").val("Left"),$("#ColumnWidth").val(""),$("#ColumnReadOnly").prop("checked",!0),$("#ColumnRequired").prop("checked",!1),$("#ColumnDefaultValue").val(""),$(".js-column-dialog .ui-button-text:contains(Save)").text("Add"),$("#ColumnDialog").dialog("option","title","Add Column"),$("#ColumnDialog").dialog("open")});$("#EditColumn").on("click",function(){n=!1;var t=$(".selectedColumnRow","#ColumnTable").data("columnDefinition");$("#ColumnName").val(t.name),$("#ColumnType").val(t.type),$("#ColumnJustification").val(t.justification),$("#ColumnWidth").val(t.width),t.isReadOnly?$("#ColumnReadOnly").prop("checked",!1):$("#ColumnReadOnly").prop("checked",!0),t.isRequired?$("#ColumnRequired").prop("checked",!0):$("#ColumnRequired").prop("checked",!1),$("#ColumnDefaultValue").val(t.defaultValue),$(".js-column-dialog .ui-button-text:contains(Add)").text("Save"),$("#ColumnDialog").dialog("option","title","Edit Column"),$("#ColumnDialog").dialog("open")});$("#ColumnTable tbody").on("click","tr",function(){$("tr","#ColumnTable tbody").removeClass("selectedColumnRow"),$(this).addClass("selectedColumnRow"),$(this).is(":first-child")?$("#MoveUpColumn").button("disable"):$("#MoveUpColumn").button("enable"),$(this).is(":last-child")?$("#MoveDownColumn").button("disable"):$("#MoveDownColumn").button("enable"),$("#EditColumn").button("enable"),$("#RemoveColumn").button("enable")});$("#AddCategory").on("click",function(){var n=prompt("Enter Category:"),i,t;if(n!==null&&n!==""&&n.trim().length>0){for(n=n.trim(),i=$("#CategoryListSelect option"),t=0;t<i.length;t++)if($(i[t]).text()===n){alert("This category already exists");return}$("#CategoryListSelect").append("<option>"+n+"<\/option>"),v("#CategoryListSelect"),$("#CategoryOptionCategory").children().remove(),$("#CategoryOptionCategory").append('<option value="" selected="selected"><\/option>'),$("#CategoryOptionCategory").append($("#CategoryListSelect option").clone()),$("#AddCategoryOption").button("enable")}});$("#EditCategory").on("click",function(){var e=$("#CategoryListSelect option:selected").text(),t=prompt("Enter Category:",e),f,o,i,u,n,r;if(t!==null&&t!==""&&t.trim().length>0&&e!==t){for(t=t.trim(),f=$("#CategoryListSelect option"),n=0;n<f.length;n++)if($(f[n]).text()===t){alert("This category already exists");return}for(o=$("#OptionListSelect option:selected").index(),$("#CategoryListSelect option:selected").text(t),v("#CategoryListSelect"),$("#CategoryOptionCategory").children().remove(),$("#CategoryOptionCategory").append('<option value="" selected="selected"><\/option>'),$("#CategoryOptionCategory").append($("#CategoryListSelect option").clone()),i=$("#CategoryOptionListSelect option"),u=$("#AutoMarkViolationSelect option"),n=0;n<i.length;n++)$(i[n]).attr("category")===e&&(r=$(i[n]).attr("text"),$(i[n]).attr("category",t),$(i[n]).text(t+" - "+r),$(u[n]).attr("category",t),$(u[n]).text(t+" - "+r))}});$("#RemoveCategory").on("click",function(){for(var r=$("#CategoryListSelect option:selected").text(),t=$("#CategoryOptionListSelect option"),u=$("#AutoMarkViolationSelect option"),i=!1,n=0;n<t.length;n++)$(t[n]).attr("category")===r&&(i=!0);if(i)if(confirm("Removing this category will result in options assigned to this category being removed, do you want to continue?"))for(n=t.length-1;n>=0;n--)$(t[n]).attr("category")===r&&($(t[n]).remove(),$(u[n]).remove());else return;$("#CategoryListSelect option:selected").remove(),$("#CategoryOptionCategory").children().remove(),$("#CategoryOptionCategory").append('<option value="" selected="selected"><\/option>'),$("#CategoryOptionCategory").append($("#CategoryListSelect option").clone()),$("#EditCategory").button("disable"),$("#RemoveCategory").button("disable"),$("#CategoryListSelect option").length===0&&$("#AddCategoryOption").button("disable")});$("#CategoryListSelect").on("change",function(){var n=$("#CategoryListSelect").prop("selectedIndex");$("#EditCategory").button("enable"),$("#RemoveCategory").button("enable"),n===-1&&($("#EditCategory").button("disable"),$("#RemoveCategory").button("disable"))});$("#AddCategoryOption").on("click",function(){i=!0,$("#EditCategoryOption").button("disable"),$("#RemoveCategoryOption").button("disable"),$("#CategoryOptionCategory").val(""),$("#CategoryOptionText").val(""),$("#CategoryOptionScore").val(""),$(".js-category-dialog .ui-button-text:contains(Save)").text("Add"),$("#CategoryOptionDialog").dialog("option","title","Add Option"),$("#CategoryOptionDialog").dialog("open")});$("#EditCategoryOption").on("click",function(){i=!1;var t=$("#CategoryOptionListSelect option:selected").attr("category"),r=$("#CategoryOptionListSelect option:selected").attr("text"),n=$("#CategoryOptionListSelect option:selected").attr("score");$("#CategoryOptionCategory").val(t),$("#CategoryOptionText").val(r),n!==undefined&&n!==null&&n!==""?$("#CategoryOptionScore").val(n):$("#CategoryOptionScore").val(""),$(".js-category-dialog .ui-button-text:contains(Add)").text("Save"),$("#CategoryOptionDialog").dialog("option","title","Edit Option"),$("#CategoryOptionDialog").dialog("open")});$("#RemoveCategoryOption").on("click",function(){var n=$("#CategoryOptionListSelect option:selected").index();$($("#AutoMarkViolationSelect").children()[n]).remove(),$("#CategoryOptionListSelect option:selected").remove(),$("#EditCategoryOption").button("disable"),$("#RemoveCategoryOption").button("disable")});$("#CategoryOptionListSelect").on("change",function(){var n=$("#CategoryOptionListSelect").prop("selectedIndex");$("#EditCategoryOption").button("enable"),$("#RemoveCategoryOption").button("enable"),n===-1&&($("#EditCategoryOption").button("disable"),$("#RemoveCategoryOption").button("disable"))});v=function(n){var t=$(n+" option");t.sort(function(n,t){return n.text.toUpperCase()<t.text.toUpperCase()?-1:n.text.toUpperCase()===t.text.toUpperCase()?0:1}),$(t).remove(),$(n).append($(t))};try{if(tt=$("#ControlDefinition").val(),tt!==""){if(u=JSON.parse(tt),u.maxLength!==undefined&&u.maxLength!==null&&$("#MaxLength").val(u.maxLength),u.score!==undefined&&u.score!==null&&$("#QuestionScore").val(u.score),u.includeNA!==undefined&&u.includeNA!==null&&(u.includeNA?($("#IncludeNAYes").prop("checked",!0),$("#IncludeNANo").prop("checked",!1)):($("#IncludeNANo").prop("checked",!0),$("#IncludeNAYes").prop("checked",!1))),u.useRadioButtons!==undefined&&u.useRadioButtons!==null&&(u.useRadioButtons?($("#UseRadioButtonsYes").prop("checked",!0),$("#UseRadioButtonsNo").prop("checked",!1),$("#UseFilterSelect").prop("checked",!1),$("#UseHorizontal").prop("checked",!1)):u.useFilterSelect?($("#UseRadioButtonsYes").prop("checked",!1),$("#UseRadioButtonsNo").prop("checked",!1),$("#UseFilterSelect").prop("checked",!0),$("#UseHorizontal").prop("checked",!1)):u.useHorizontal?($("#UseRadioButtonsYes").prop("checked",!1),$("#UseRadioButtonsNo").prop("checked",!1),$("#UseFilterSelect").prop("checked",!1),$("#UseHorizontal").prop("checked",!0)):($("#UseRadioButtonsNo").prop("checked",!0),$("#UseRadioButtonsYes").prop("checked",!1),$("#UseFilterSelect").prop("checked",!1),$("#UseHorizontal").prop("checked",!1))),u.useCheckboxes!==undefined&&u.useCheckboxes!==null&&(u.useCheckboxes?($("#UseCheckBoxesYes").prop("checked",!0),$("#UseCheckBoxesNo").prop("checked",!1)):($("#UseCheckBoxesNo").prop("checked",!0),$("#UseCheckBoxesYes").prop("checked",!1))),u.canAddRows!==undefined&&u.canAddRows!==null?u.canAddRows?($("#CanAddRowsYes").prop("checked",!0),$("#CanAddRowsNo").prop("checked",!1)):($("#CanAddRowsYes").prop("checked",!1),$("#CanAddRowsNo").prop("checked",!0)):($("#CanAddRowsYes").prop("checked",!0),$("#CanAddRowsNo").prop("checked",!1)),u.canDeleteRows!==undefined&&u.canDeleteRows!==null?u.canDeleteRows?($("#CanDeleteRowsYes").prop("checked",!0),$("#CanDeleteRowsNo").prop("checked",!1)):($("#CanDeleteRowsYes").prop("checked",!1),$("#CanDeleteRowsNo").prop("checked",!0)):($("#CanDeleteRowsYes").prop("checked",!0),$("#CanDeleteRowsNo").prop("checked",!1)),u.options!==undefined&&u.options!==null&&u.options.length>0&&u.categories!==undefined&&u.categories!==null&&u.categories.length>0)for(e=0;e<u.options.length;e++)y=u.options[e].category+" - "+u.options[e].text,u.options[e].score!==undefined&&u.options[e].score!==null&&u.options[e].score!==""&&(y+=" ("+u.options[e].score.toFixed(2)+")"),u.options[e].score!==undefined&&u.options[e].score!==null&&u.options[e].score!==""?$("#CategoryOptionListSelect").append("<option category='"+u.options[e].category+"' text='"+u.options[e].text+"' score='"+u.options[e].score+"'>"+y+"<\/option>"):$("#CategoryOptionListSelect").append("<option category='"+u.options[e].category+"' text='"+u.options[e].text+"''>"+y+"<\/option>"),$("#AutoMarkViolationSelect").append("<option category='"+u.options[e].category+"' text='"+u.options[e].text+"'>"+y+"<\/option>");else if(u.options!==undefined&&u.options!==null&&u.options.length>0)for(e=0;e<u.options.length;e++)u.options[e].text===undefined?$("#OptionListSelect").append("<option data-text='"+u.options[e]+"' data-score=''>"+u.options[e]+"<\/option>"):u.options[e].score!==undefined?$("#OptionListSelect").append("<option data-text='"+u.options[e].text+"' data-score='"+u.options[e].score+"'>"+u.options[e].text+" ("+u.options[e].score+")<\/option>"):$("#OptionListSelect").append("<option data-text='"+u.options[e].text+"' data-score=''>"+u.options[e].text+"<\/option>"),u.options[e].text===undefined?$("#AutoMarkViolationSelect").append("<option data-text='"+u.options[e]+"' data-score=''>"+u.options[e]+"<\/option>"):u.options[e].score!==undefined?$("#AutoMarkViolationSelect").append("<option data-text='"+u.options[e].text+"' data-score='"+u.options[e].score+"'>"+u.options[e].text+"<\/option>"):$("#AutoMarkViolationSelect").append("<option data-text='"+u.options[e].text+"' data-score=''>"+u.options[e].text+"<\/option>");if(u.categories!==undefined&&u.categories!==null&&u.categories.length>0)for($("#AddCategoryOption").button("enable"),e=0;e<u.categories.length;e++)$("#CategoryListSelect").append("<option>"+u.categories[e]+"<\/option>"),$("#CategoryOptionCategory").append("<option>"+u.categories[e]+"<\/option>");if(u.columns!==undefined&&u.columns!==null&&u.columns.length>0)for(e=0;e<u.columns.length;e++){var p="",w="",b="",d="",k="",nt="",c="",s={};u.columns[e].name===undefined?(p=u.columns[e],s.name=p):(p=u.columns[e].name,s.name=p),u.columns[e].type===undefined?(w="Comment",s.type=w):(w=u.columns[e].type,s.type=w),u.columns[e].justification===undefined?(b="Left",s.justification=b):(b=u.columns[e].justification,s.justification=b),u.columns[e].width===undefined?(d="",s.width=d):(u.columns[e].width!==""&&(d=u.columns[e].width+"%"),s.width=u.columns[e].width),u.columns[e].isReadOnly===undefined?(k="Yes",s.isReadOnly=!1):u.columns[e].isReadOnly?(k="No",s.isReadOnly=!0):(k="Yes",s.isReadOnly=!1),u.columns[e].isRequired===undefined?(nt="No",s.isRequired=!1):u.columns[e].isRequired?(nt="Yes",s.isRequired=!0):(nt="No",s.isRequired=!1),u.columns[e].defaultValue===undefined?(c="",s.defaultValue=c):(c=u.columns[e].defaultValue,s.defaultValue=c),h="<tr>",h+="<td>"+p+"<\/td>",h+="<td>"+w+"<\/td>",h+="<td>"+b+"<\/td>",h+="<td>"+d+"<\/td>",h+="<td>"+k+"<\/td>",h+="<td>"+nt+"<\/td>",h+=c.length>10?"<td>"+c.substring(0,10)+"...<\/td>":"<td>"+c+"<\/td>",h+="<\/tr>",$("tbody","#ColumnTable").append(h),$("tr","#ColumnTable tbody").last().data("columnDefinition",s)}if(u.collumns!==undefined&&u.collumns!==null&&u.collumns.length>0)for(e=0;e<u.collumns.length;e++)$("#OptionListSelect").append("<option>"+u.collumns[e]+"<\/option>")}if(it=$("#AutoViolationDefinition").val(),it!==""){o=JSON.parse(it),ut=$("#ContentType").val();switch(ut){case"text.html":o.answer!==undefined&&o.answer!==null&&$("#AutoViolation").val(o.answer);break;case"number.html":o.equals!==undefined&&o.equals!==null&&$("#AutoViolation").val(o.equals),o.lessThan!==undefined&&o.lessThan!==null&&$("#AutoViolationLessThan").val(o.lessThan),o.greaterThan!==undefined&&o.greaterThan!==null&&$("#AutoViolationGreaterThan").val(o.greaterThan);break;case"yesno.html":o.answer==="YES"?$("#AutoMarkYesNo").val("AutoMarkViolationYes"):o.answer==="NO"?$("#AutoMarkYesNo").val("AutoMarkViolationNo"):o.answer==="NA"?$("#AutoMarkYesNo").val("AutoMarkViolationNA"):$("#AutoMarkYesNo").val("");break;case"singleselect.html":if(o.answer!==undefined&&o.answer!==null&&o.answer.length>0)for(e=0;e<o.answer.length;e++)$("#AutoMarkViolationSelect option:contains("+o.answer[e]+")").prop("selected","selected");break;case"categorysingleselect.html":if(a=$("#AutoMarkViolationSelect option"),o.answer!==undefined&&o.answer!==null&&o.answer.length>0)for(e=0;e<o.answer.length;e++)for(l=0;l<a.length;l++)if($(a[l]).attr("category")===o.answer[e].category&&$(a[l]).attr("text")===o.answer[e].text){$(a[l]).prop("selected","selected");break}break;case"multiselect.html":if(o.answer!==undefined&&o.answer!==null&&o.answer.length>0)for(e=0;e<o.answer.length;e++)$("#AutoMarkViolationSelect").find("option[data-text='"+o.answer[e]+"']").prop("selected","selected");break;case"formattedtext.html":o.answer!==undefined&&o.answer!==null&&$("#AutoViolation").val(o.answer)}}}catch(et){}t(),$("#ContentType").change(t);$("#CancelButton").on("click",function(){window.location=app.vroot()+"FormVersion/Edit/"+$("#FormVersionId").val()+"?selectedFormSection="+$("#FormSectionId").val()+"&selectedFormControl="+$("#FormControlId").val()});$("#SaveButton").on("click",function(){r=!1,rt()});$("#SaveNextButton").on("click",function(){r=!0,rt()});rt=function(){var e=$("#ContentType").val(),c=$("#MaxLength").val(),n=null,u=null,i=$("#QuestionScore").val(),k,s,o,h,v,y,ft,ut,f,t,a,vt;try{if(e==="text.html"){if(c==="")return alert("Text controls require a maxLength property"),!1;if(!Wndsr.isNumericInteger(c))return alert("Text controls require an integer maxLength property"),!1;n={},n.maxLength=parseInt(c),i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i)),v=$("#AutoViolation").val().trim(),v.length>0&&(u={},u.answer=v)}else if(e==="date.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(e==="location.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(e==="time.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(e==="url.html")n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i));else if(e==="number.html"){var tt=$("#AutoViolation").val(),rt=$("#AutoViolationLessThan").val(),it=$("#AutoViolationGreaterThan").val();if(tt!==""){if(!Wndsr.isNumericInteger(tt))return alert("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value equals must be an interger"),!1;u===null&&(u={}),u.equals=parseInt(tt)}if(rt!==""){if(!Wndsr.isNumericInteger(rt))return alert("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value is less than must be an interger"),!1;u===null&&(u={}),u.lessThan=parseInt(rt)}if(it!==""){if(!Wndsr.isNumericInteger(it))return alert("Auto-Mark as "+$("#ViolationPhraseSingular").val()+" if Value is greater than must be an interger"),!1;u===null&&(u={}),u.greaterThan=parseInt(it)}n={},i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i))}else if(e==="yesno.html")$("#IncludeNAYes").is(":checked")?(n={},n.includeNA=!0):(n={},n.includeNA=!1),$("#AutoMarkYesNo").val()==="AutoMarkViolationYes"?(u={},u.answer="YES"):$("#AutoMarkYesNo").val()==="AutoMarkViolationNo"?(u={},u.answer="NO"):$("#AutoMarkYesNo").val()==="AutoMarkViolationNA"&&(u={},u.answer="NA");else if(e==="singleselect.html"){if(f=$("#OptionListSelect option"),f.length===0)return alert("single select controls require at least one option"),!1;for(n={},$("#UseRadioButtonsYes").is(":checked")?(n.useRadioButtons=!0,n.useFilterSelect=!1,n.useHorizontal=!1):$("#UseFilterSelect").is(":checked")?(n.useRadioButtons=!1,n.useFilterSelect=!0,n.useHorizontal=!1):$("#UseHorizontal").is(":checked")?(n.useRadioButtons=!1,n.useFilterSelect=!1,n.useHorizontal=!0):(n.useRadioButtons=!1,n.useFilterSelect=!1,n.useHorizontal=!1),n.options=[],t=0;t<f.length;t++)i=$(f[t]).data("score"),s=$(f[t]).data("text"),i===""?n.options.push({text:s}):n.options.push({score:parseFloat(i),text:s});if(o=$("#AutoMarkViolationSelect").children(":selected"),o.length>0){for(h=[],u={},t=0;t<o.length;t++)h.push($(o[t]).text());u.answer=h}}else if(e==="categorysingleselect.html"){if(k=$("#CategoryListSelect option"),f=$("#CategoryOptionListSelect option"),k.length===0)return alert("category single select controls require at least one category"),!1;if(f.length===0)return alert("category single select controls require at least one option"),!1;for(n={},n.categories=[],t=0;t<k.length;t++)n.categories.push($(k[t]).text());for(n.options=[],t=0;t<f.length;t++)i=$(f[t]).attr("score"),s=$(f[t]).attr("text"),i===""?n.options.push({text:s,category:$(f[t]).attr("category")}):n.options.push({score:parseFloat(i),text:s,category:$(f[t]).attr("category")});if(o=$("#AutoMarkViolationSelect").children(":selected"),o.length>0){for(h=[],u={},t=0;t<o.length;t++)h.push({category:$(o[t]).attr("category"),text:$(o[t]).attr("text")});u.answer=h}}else if(e==="multiselect.html"){if(f=$("#OptionListSelect option"),f.length===0)return alert("multi select controls require at least one option"),!1;for(n={},n.useCheckboxes=$("#UseCheckBoxesYes").is(":checked")?!0:!1,n.options=[],t=0;t<f.length;t++)i=$(f[t]).data("score"),s=$(f[t]).data("text"),i===""?n.options.push({text:s}):n.options.push({score:parseFloat(i),text:s});if(o=$("#AutoMarkViolationSelect").children(":selected"),o.length>0){for(h=[],u={},t=0;t<o.length;t++)h.push($(o[t]).text());u.answer=h}}else if(e==="formattedtext.html"){if(c==="")return alert("text paragraph control require a maxLength property"),!1;if(!Wndsr.isNumericInteger(c))return alert("text paragraph control require an integer maxLength property"),!1;n={},n.maxLength=parseInt(c),i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i)),v=$("#AutoViolation").val().trim(),v.length>0&&(u={},u.answer=v)}else if(e==="table.html"){if(y=$("tbody tr","#ColumnTable"),y.length===0)return alert("table controls require at least one column"),!1;if(y.length>10)return alert("table controls can have a maximum of 10 columns"),!1;for(n={},n.columns=[],ft=!1,t=0;t<y.length;t++)ut=$(y[t]).data(),ut.columnDefinition.isReadOnly||(ft=!0),n.columns.push(ut.columnDefinition);if(!ft&&$.trim($("#Tags").val())==="")return alert("If none of the table columns allow input, then a Data Integration Tag must be entered."),!1;if(n.canAddRows=$("#CanAddRowsYes").is(":checked")?!0:!1,n.canDeleteRows=$("#CanDeleteRowsYes").is(":checked")?!0:!1,!n.canAddRows&&$.trim($("#Tags").val())==="")return alert("If Can Add Rows is No, then a Data Integration Tag must be entered"),!1;for(f=$("#OptionListSelect option"),n.options=[],t=0;t<f.length;t++)n.options.push($(f[t]).text())}else if(e==="locationtable.html"){if(f=$("#OptionListSelect option"),f.length===0)return alert("location table controls require at least one column"),!1;for(n={},n.options=[],t=0;t<f.length;t++)n.options.push($(f[t]).text());i!==undefined&&i!==""&&i!==null&&(n.score=parseFloat(i))}if(e!=="instructions.html"){if($("#RequireReferenceForViolation").val().toUpperCase()==="TRUE"&&$("#ViolationAllowed").is(":checked")&&$.trim($("#ReferenceCitation").val())==="")return alert("If marking an answer as "+$("#ViolationPhraseSingular").val()+" is allowed, then Reference / Citation is required"),!1;if($("#UserInputNotAllowed").is(":checked")&&$.trim($("#Tags").val())==="")return alert("If user input is not allowed, then Data Integration Tags is required"),!1}}catch(pt){return alert("There was an error validing the form"),!1}var wt=$("#FormSectionId").val(),at=$("#FormControlId").val(),et=$.trim($("#QuestionNumber").val()),yt=$.trim($("#QuestionLetter").val()),lt=$.trim($("#QuestionText").val()),p=!1,ct=!1;$("#RequiredInputType").is(":checked")&&(p=!0);var g=$("#ReferenceCitation").val(),nt=$("#ReferenceCitationDescription").val(),d=$("#QuestionHelp").val(),b=!1;$("#ViolationAllowed").is(":checked")&&(b=!0),a=!1,$("#UserInputAllowed").is(":checked")&&(a=!0);var l=$("#Tags").val(),w=$("#IntegrationContext").val(),ot=null,st=null,ht=!1;if($("#ShowOnReportYes").is(":checked")&&(ht=!0),vt=$("#VisibilityFormula").val(),n!==null&&(ot=JSON.stringify(n)),u!==null&&(st=JSON.stringify(u)),$("#IsShowViolationYes").is(":checked")&&(ct=!0),e==="instructions.html"&&(g="",nt="",d="",b=!1,p=!1,a=!1,l="",u=""),et.length===0){alert("Question Number is required");return}if(!Wndsr.isNumericInteger(et)){alert("Question Number must be a number");return}if(lt.length===0){alert("Question Text is required");return}if(p&&!a){alert("If answer input is required, you must allow user to input an answer.");return}if(w!==null&&w!==undefined&&w!==""&&(l===null||l===undefined||l==="")){alert("If Data Integration Context is entered, then Data Integration Tags is a required field.");return}e==="instructions.html"&&(g="",nt="",d="",b=!1,p=!1,a=!1,l="",u=""),app.post(app.vroot()+"FormControl/SaveEdit/"+at,{formControlId:at,questionNumber:et,questionLetter:yt,questionText:lt,isAnswerRequired:p,contentType:e,referenceCitation:g,referenceCitationDescription:nt,questionHelp:d,isViolationAllowed:b,questionTag:l,controlDefinition:ot,autoViolation:st,userInputAllowed:a,isShowOnReport:ht,integrationContext:w,isShowViolation:ct,visibilityFormula:vt},function(n){window.location=r?app.vroot()+"FormControl/EditFormControl/"+n.nextQuestionId:app.vroot()+"FormVersion/Edit/"+n.formVersionId+"?selectedFormSection="+n.formSectionId+"&selectedFormControl="+n.formControlId},function(){alert("Save Failed"),$.unblockUI()})},$("#QuestionNumber").focus();$("#QuestionScore").on("blur",function(){var n=$("#QuestionScore").val();n.indexOf(".")>0&&$("#QuestionScore").val(parseFloat($("#QuestionScore").val(),10).toFixed(2))});$("#OptionScore").on("blur",function(){var n=$("#OptionScore").val();n.indexOf(".")>0&&$("#OptionScore").val(parseFloat($("#OptionScore").val(),10).toFixed(2))})}))}(),function(){$("#Content").data("currentView")==="InspectionSync/Index"&&$(function(){$("#NewInspectionTypeButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#InspectionSyncActions").menu();$("#InspectionSyncTable").on("click",".js-options-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#InspectionSyncActions").hide();else{var r=$(this).data("inspection-sync-id"),t=$(this).data("inspection-id"),n=$(this).data("inspection-sync-status"),i=$(this).data("inspection-sync-iscomplete");$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#InspectionSyncActions").css("top",$(this).offset().top+$(this).height()),$("#InspectionSyncActions").data("inspection-sync-id",r),$("#InspectionSyncActions").data("inspection-id",t),n==="C"||n==="CF"?$("#InspectionSyncResend").parent().show():$("#InspectionSyncResend").parent().hide(),n==="E"||n==="EI"||n==="CF"?$("#MarkResolved").parent().show():$("#MarkResolved").parent().hide(),i==="Y"?$("#InspectionSyncUncomplete").parent().show():$("#InspectionSyncUncomplete").parent().hide(),t!==null&&t!==undefined&&t!==""?$("#InspectionSyncRemove").parent().show():$("#InspectionSyncRemove").parent().hide(),$("#InspectionSyncActions").show();$("html").on("click",function(){$(this).is("#InspectionSyncActions")||$("#InspectionSyncActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#InspectionSyncActions").hide(),$("html").off("click"))})}return!1});$("#InspectionSyncInfoDialog").dialog({title:"Inspecton Sync Status Message",autoOpen:!1,modal:!0,resizable:!1,height:355,minHeight:355,width:575,minWidth:575,buttons:{OK:function(){$("#InspectionSyncInfoDialog").dialog("close")}}}),$("#InspectionSyncHistory").dialog({title:"Integration History",autoOpen:!1,modal:!0,resizable:!0,height:355,minHeight:355,width:675,minWidth:675,buttons:{OK:function(){$("#InspectionSyncHistory").dialog("close")}}});$("#InspectionSyncHidstory").on("click",function(){$("#InspectionSyncInfoDialog").dialog("open")});$(".js-inspection-sync-status").on("click",function(){$("#InspectionSyncInfoMessage").text($(".js-inspection-sync-status-text",$(this).parent()).val()),$("#InspectionSyncInfoDialog").dialog("open");var n=$("td:first",$(this).parent().parent()).text();return $("#InspectionSyncInfoDialog").dialog({title:"Integration Activity Detail for Inspection "+n}),!1});$("#InspectionSyncDateFilter, #InspectionSyncStatusFilter").on("change",function(){var t=$("#InspectionSyncDateFilter").val(),n=$("#InspectionSyncStatusFilter").val();window.open(app.vroot()+"InspectionSync?date="+t+"&status="+n,"_self")});$("#InspectionSyncRemove").on("click",function(){if(confirm("Are you sure you want to remove this inspection and all forms attached to it?")){var n=$("#InspectionSyncActions").data("inspection-sync-id");app.post(app.vroot()+"Synchronize/RemoveInspectionSync/",{id:n},function(){var t=$("#InspectionSyncDateFilter").val(),n=$("#InspectionSyncStatusFilter").val();window.open(app.vroot()+"InspectionSync?date="+t+"&status="+n,"_self")},function(){alert("Failed removing inspection integration.")})}return!1});$("#ViewHistory").on("click",function(){$.blockUI();var n=$("#InspectionSyncActions").data("inspection-sync-id");app.post(app.vroot()+"Synchronize/GetInspectionSyncHistory/",{id:n},function(n){for(var i="",t=0;t<n.items.length;t++)i+="<tr><td class='syncHistoryFirstColumn'>"+n.items[t].date+"<\/td><td class='syncHistorySecondColumn'>",i+=n.items[t].isError?"Error":"Success",i+="<\/td><td>"+n.items[t].message+"<\/td><\/tr>";$("tbody","#HistoryTable").html(i),$("#InspectionSyncHistory").dialog("open"),$.unblockUI()},function(){alert("Failed getting inspection sync history.")})});$("#InspectionSyncUncomplete").on("click",function(){var n=$("#InspectionSyncActions").data("inspection-id");return app.post(app.vroot()+"Synchronize/UncompleteInspection/",{id:n},function(){var t=$("#InspectionSyncDateFilter").val(),n=$("#InspectionSyncStatusFilter").val();window.open(app.vroot()+"InspectionSync?date="+t+"&status="+n,"_self")},function(){alert("Failed removing inspection integration.")}),!1});$("#MarkResolved").on("click",function(){var n=$("#InspectionSyncActions").data("inspection-sync-id");return app.post(app.vroot()+"Synchronize/MarkResolved/",{id:n},function(){var t=$("#InspectionSyncDateFilter").val(),n=$("#InspectionSyncStatusFilter").val();window.open(app.vroot()+"InspectionSync?date="+t+"&status="+n,"_self")},function(){alert("Failed marking inspection error resolved.")}),!1})})}(),function(){$("#Content").data("currentView")==="InspectionType/Index"&&$(function(){$("#NewInspectionTypeButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#NewInspectionTypeButton").on("click",function(){window.location=app.vroot()+"InspectionType/New"})})}(),function(){$("#Content").data("currentView")==="InspectionType/New"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"InspectionType/"});$("#SaveButton").on("click",function(){if($.trim($("#InspectionTypeName").val())===""){alert("Name is required");return}if($.trim($("#InspectionTypeCode").val())===""){alert("Code is required");return}var i=$.trim($("#InspectionTypeName").val()),r=$.trim($("#InspectionTypeCode").val()),u=$("#ActiveStatus").is(":checked"),t=$("#ReportGroups").val(),n=$("#DefaultReportGroup").val();if(t==null&&(t=[]),n!==""&&n!==undefined&&n!==null&&t.indexOf(n)<0){alert("Default report group must be one of the selected report groups");return}$.blockUI(),app.post(app.vroot()+"InspectionType/SaveNew/0",{name:i,code:r,isActive:u,reportGroups:t,defaultReportGroup:n},function(n){n.message===""?window.location=app.vroot()+"InspectionType/":(alert(n.message),$.unblockUI())},function(){alert("Save Failed"),$.unblockUI()})});$("#InspectionTypeName").focus()})}(),function(){$("#Content").data("currentView")==="InspectionType/Edit"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"InspectionType/"});$("#SaveButton").on("click",function(){if($.trim($("#InspectionTypeName").val())===""){alert("Name is required");return}if($.trim($("#InspectionTypeCode").val())===""){alert("Code is required");return}var i=$("#InspectionTypeIdHidden").val(),u=$.trim($("#InspectionTypeName").val()),f=$.trim($("#InspectionTypeCode").val()),r=$("#ActiveStatus").is(":checked"),t=$("#ReportGroups").val(),n=$("#DefaultReportGroup").val();if(t==null&&(t=[]),n!==""&&n!==undefined&&n!==null&&t.indexOf(n)<0){alert("Default report group must be one of the selected report groups");return}$.blockUI(),app.post(app.vroot()+"InspectionType/SaveEdit/"+i,{name:u,code:f,isActive:r,reportGroups:t,defaultReportGroup:n},function(n){n.message===""?window.location=app.vroot()+"InspectionType/":(alert(n.message),$.unblockUI())},function(){alert("Save Failed"),$.unblockUI()})});$("#InspectionTypeName").focus()})}(),function(){$("#Content").data("currentView")==="ReportTemplate/Index"&&$(function(){$("#NewReportTemplateButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#NewReportTemplateButton").on("click",function(){window.location=app.vroot()+"ReportTemplate/New"})})}(),function(){$("#Content").data("currentView")==="ReportTemplate/Edit"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#DeleteButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"ReportTemplate/"});$("#DeleteButton").on("click",function(){if(confirm("Are you sure you want to Delete this Report Template?")){$.blockUI();var n=$("#ReportTemplateIdHidden").val();app.post(app.vroot()+"ReportTemplate/Delete/"+n,null,function(){window.location=app.vroot()+"ReportTemplate/"},function(){alert("Delete Failed"),$.unblockUI()})}});$("#SaveButton").on("click",function(){var t;if($.trim($("#FormReportTemplateTitle").val())===""){alert("Template Title is required");return}if($.trim($("#ReportFormats").val())===""){alert("At least one report format is required");return}$.blockUI();var u=$("#ReportTemplateIdHidden").val(),f=$.trim($("#FormReportTemplateTitle").val()),r=$("#HeaderReports").val(),n=$("#FormReport").val(),i=$("#FooterReports").val(),e=$("#ReportFormats").val();r==null&&(r=[]),i==null&&(i=[]),t=r.concat(i),n!=="USEDEFAULT"&&n!==undefined&&n!==null&&t.push(n),app.post(app.vroot()+"ReportTemplate/SaveEdit/"+u,{id:u,title:f,formReportTemplates:t,reportFormats:e},function(){window.location=app.vroot()+"ReportTemplate/"},function(){alert("Save Failed"),$.unblockUI()})});$("#FormReportTemplateTitle").focus()})}(),function(){$("#Content").data("currentView")==="ReportTemplate/New"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#CancelButton").on("click",function(){window.location=app.vroot()+"ReportTemplate/"});$("#SaveButton").on("click",function(){var i;if($.trim($("#FormReportTemplateTitle").val())===""){alert("Template Title is required");return}if($.trim($("#ReportFormats").val())===""){alert("At least one report format is required");return}$.blockUI();var u=$.trim($("#FormReportTemplateTitle").val()),r=$("#HeaderReports").val(),n=$("#FormReport").val(),t=$("#FooterReports").val(),f=$("#ReportFormats").val();r==null&&(r=[]),t==null&&(t=[]),i=r.concat(t),n!=="USEDEFAULT"&&n!==undefined&&n!==null&&i.push(n),app.post(app.vroot()+"ReportTemplate/SaveNew/0",{title:u,formReportTemplates:i,reportFormats:f},function(){window.location=app.vroot()+"ReportTemplate/"},function(){alert("Save Failed"),$.unblockUI()})});$("#FormReportTemplateTitle").focus()})}(),function(){$("#Content").data("currentView")==="FormReportTemplate/Index"&&$(function(){$("#NewReportTemplateButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#NewReportTemplateButton").on("click",function(){window.location=app.vroot()+"FormReportTemplate/New"})})}(),function(){$("#Content").data("currentView")==="FormReportTemplate/Edit"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#FormReportTemplateUpload").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)i=new FileReader,i.onload=function(n){return function(t){$("#FormReportTemplateFileDownload").attr("download",n.fileName),$("#FormReportTemplateFileDownload").attr("href",t.target.result),$("#FormReportTemplateFileDownload").removeClass("hidden")}}(t),i.readAsDataURL(t)});$("#FormReportTemplateThumbnailUpload").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)i=new FileReader,i.onload=function(){return function(n){var i=n.target.result.substring(n.target.result.indexOf(",")+1),t=n.target.result.substring(0,n.target.result.indexOf(",")+1);if(!(t.toUpperCase().indexOf("PNG")>=0)&&!(t.toUpperCase().indexOf("JPG")>=0)&&!(t.toUpperCase().indexOf("JPEG")>=0)){alert("Only files of type png and jpg are accepted");return}$("<img/>").attr("src",t+i).load(function(){var r=this.width,i=this.height,t=!0;i>128&&(confirm("Warning: This image is too large.  The image you uploaded is "+r+"px x "+i+"px.  We recommend a maximum height of 128px.  Are you sure you want to use this image?")||(t=!1)),t&&$("#FormReportTemplateThumbnail").attr("src",n.target.result).removeClass("hidden")})}}(t),i.readAsDataURL(t)});$("#FormReportTemplateExampleUpload").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)i=new FileReader,i.onload=function(){return function(n){var i=n.target.result.substring(n.target.result.indexOf(",")+1),t=n.target.result.substring(0,n.target.result.indexOf(",")+1);if(t.toUpperCase().indexOf("PNG")>=0)$("#FormReportTemplateExampleDownload").attr("download","example.png");else if(t.toUpperCase().indexOf("PDF")>=0)$("#FormReportTemplateExampleDownload").attr("download","example.pdf");else{alert("Only files of type png and pdf are accepted");return}$("#FormReportTemplateExampleDownload").attr("href",n.target.result),$("#FormReportTemplateExampleDownload").removeClass("hidden")}}(t),i.readAsDataURL(t)});$("#FormReportTemplateTypePre, #FormReportTemplateTypePost").on("change",function(){$(this).is(":checked")&&($(".js-nonFormField").removeClass("hidden"),$(".js-formField").addClass("hidden"))});$("#FormReportTemplateTypeForm").on("change",function(){$(this).is(":checked")&&($(".js-nonFormField").addClass("hidden"),$(".js-formField").removeClass("hidden"))});$("#CancelButton").on("click",function(){window.location=app.vroot()+"FormReportTemplate/"});$("#SaveButton").on("click",function(){var u=$("#FormReportTemplateIdHidden").val(),e=$("#FormReportTemplateFilename").val(),f=$("#FormReportTemplateTitle").val(),l=$("#FormReportTemplateDescription").val(),c=$("#FormReportTemplateThumbnail").attr("src"),a=$("#FormReportTemplateExampleDownload").attr("href"),n=null,r=null,t=null,i=$("#FormReportTemplateIndex").val(),s=$("#FormReportTemplateFileDownload").attr("href"),o=$("#IsInspectionReport").is(":checked"),h=$("#IsProjectReport").is(":checked");if($("#FormReportTemplateTypePre").is(":checked")?n=0:$("#FormReportTemplateTypeForm").is(":checked")?n=1:$("#FormReportTemplateTypePost").is(":checked")&&(n=2),$("#FormReportTemplateStatusActive").is(":checked")?r=!0:$("#FormReportTemplateStatusInactive").is(":checked")&&(r=!1),$("#FormReportTemplateDefaultYes").is(":checked")?t=!0:$("#FormReportTemplateDefaultNo").is(":checked")&&(t=!1),u===undefined||u===null||u==="")return alert("Save Failed, no ID"),!1;if(e.indexOf(".")>=0)return alert("Do Not include the extension in the filename"),!1;if(f===undefined||f===null||f==="")return alert("Template Title is required."),!1;if(n!==0&&n!==1&&n!==2)return alert("Report Type is required."),!1;if(r!==!0&&r!==!1)return alert("Report Template Status is required."),!1;if(n===0||n===2){if(i===null||i===undefined||i===""||!Wndsr.isNumericInteger(i))return alert("Report Index is required, and must be a number from 0 to 999."),!1;t=!1}if(n===1){if(t!==!0&&t!==!1)return alert("Default Report Template is required."),!1;i=0}app.post(app.vroot()+"FormReportTemplate/SaveEdit/"+u,{fileName:e,title:f,description:l,thumbnailData:c,documentData:a,reportType:n,reportStatus:r,reportDefault:t,reportIndex:i,templateData:s,isInspectionReport:o,isProjectReport:h},function(n){n.message===""?window.location=app.vroot()+"FormReportTemplate/":(alert(n.message),$.unblockUI())},function(){alert("Save Failed"),$.unblockUI()})});$("#FormReportTemplateTitle").focus()})}(),function(){$("#Content").data("currentView")==="FormReportTemplate/New"&&$(function(){$("#CancelButton").button(),$("#SaveButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$("#FormReportTemplateThumbnailUpload").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)i=new FileReader,i.onload=function(){return function(n){var i=n.target.result.substring(n.target.result.indexOf(",")+1),t=n.target.result.substring(0,n.target.result.indexOf(",")+1);if(!(t.toUpperCase().indexOf("PNG")>=0)&&!(t.toUpperCase().indexOf("JPG")>=0)&&!(t.toUpperCase().indexOf("JPEG")>=0)){alert("Only files of type png and jpg are accepted");return}$("<img/>").attr("src",t+i).load(function(){var r=this.width,i=this.height,t=!0;i>128&&(confirm("Warning: This image is too large.  The image you uploaded is "+r+"px x "+i+"px.  We recommend a maximum height of 128px.  Are you sure you want to use this image?")||(t=!1)),t&&$("#FormReportTemplateThumbnail").attr("src",n.target.result).removeClass("hidden")})}}(t),i.readAsDataURL(t)});$("#FormReportTemplateExampleUpload").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)i=new FileReader,i.onload=function(){return function(n){var i=n.target.result.substring(n.target.result.indexOf(",")+1),t=n.target.result.substring(0,n.target.result.indexOf(",")+1);if(t.toUpperCase().indexOf("PNG")>=0)$("#FormReportTemplateExampleDownload").attr("download","example.png");else if(t.toUpperCase().indexOf("PDF")>=0)$("#FormReportTemplateExampleDownload").attr("download","example.pdf");else{alert("Only files of type png and pdf are accepted");return}$("#FormReportTemplateExampleDownload").attr("href",n.target.result),$("#FormReportTemplateExampleDownload").removeClass("hidden")}}(t),i.readAsDataURL(t)});$("#FormReportTemplateUpload").on("change",function(n){for(var u=n.target.files,t,i,r=0;t=u[r];r++)i=new FileReader,i.onload=function(n){return function(t){$("#FormReportTemplateFileDownload").attr("download",n.fileName),$("#FormReportTemplateFileDownload").attr("href",t.target.result),$("#FormReportTemplateFileDownload").removeClass("hidden")}}(t),i.readAsDataURL(t)});$("#FormReportTemplateTypePre, #FormReportTemplateTypePost").on("change",function(){$(this).is(":checked")&&($(".js-nonFormField").removeClass("hidden"),$(".js-formField").addClass("hidden"))});$("#FormReportTemplateTypeForm").on("change",function(){$(this).is(":checked")&&($(".js-nonFormField").addClass("hidden"),$(".js-formField").removeClass("hidden"))});$("#CancelButton").on("click",function(){window.location=app.vroot()+"FormReportTemplate/"});$("#SaveButton").on("click",function(){var u=$("#FormReportTemplateTitle").val(),s=$("#FormReportTemplateDescription").val(),f=$("#FormReportTemplateFileDownload").attr("href"),h=$("#FormReportTemplateThumbnail").attr("src"),c=$("#FormReportTemplateExampleDownload").attr("href"),n=null,r=null,t=null,i=$("#FormReportTemplateIndex").val(),e=$("#IsInspectionReport").is(":checked"),o=$("#IsProjectReport").is(":checked");if($("#FormReportTemplateTypePre").is(":checked")?n=0:$("#FormReportTemplateTypeForm").is(":checked")?n=1:$("#FormReportTemplateTypePost").is(":checked")&&(n=2),$("#FormReportTemplateStatusActive").is(":checked")?r=!0:$("#FormReportTemplateStatusInactive").is(":checked")&&(r=!1),$("#FormReportTemplateDefaultYes").is(":checked")?t=!0:$("#FormReportTemplateDefaultNo").is(":checked")&&(t=!1),u===undefined||u===null||u==="")return alert("Template Title is required."),!1;if(f===undefined||f===null||f==="")return alert("Report Template File is required"),!1;if(n!==0&&n!==1&&n!==2)return alert("Report Type is required."),!1;if(r!==!0&&r!==!1)return alert("Report Template Status is required."),!1;if(n===0||n===2){if(i===null||i===undefined||i===""||!Wndsr.isNumericInteger(i))return alert("Report Index is required, and must be a number from 0 to 999."),!1;t=!1}if(n===1){if(t!==!0&&t!==!1)return alert("Default Report Template is required."),!1;i=0}app.post(app.vroot()+"FormReportTemplate/SaveNew/0",{title:u,description:s,templateData:f,thumbnailData:h,documentData:c,reportType:n,reportStatus:r,reportDefault:t,reportIndex:i,isInspectionReport:e,isProjectReport:o},function(n){n.message===""?window.location=app.vroot()+"FormReportTemplate/":(alert(n.message),$.unblockUI())},function(){alert("Save Failed"),$.unblockUI()})});$("#FormReportTemplateTitle").focus()})}(),function(){var o,t;if($("#Content").data("currentView")==="Shared/DumpData"){var c="",u=0,f=0,r=null,s="",n=0,i=0,h=[],e="";$(function(){$("#ValueDialog").dialog({autoOpen:!1,modal:!0,width:500,buttons:{OK:function(){$("#ValueDialog").dialog("close")}}});$("html").on("click",".localStorage",function(){var n=$(this).data("id"),t=localStorage[n];return $("#ValueDialog").dialog("option","title","Local Storage Key "+n),$("#ValueTextArea").val(t),$("#ValueDialog").dialog("open"),!1});$("html").on("click",".webSql",function(){var n=$(this).data("id");return app.getWebSql(n,function(t){$("#ValueDialog").dialog("option","title","Web SQL Key "+n),$("#ValueTextArea").val(JSON.stringify(t)),$("#ValueDialog").dialog("open")}),!1});app.principal===null?($("#InspectorName").text(""),$("#LoggedInUser").text(""),$("#LogoutLink").removeClass("ui-icon-logout"),$("#LogoutLink").addClass("ui-icon-login"),$("#LogoutLink").attr("title","Logon")):($("#InspectorName").text(app.principal.displayName),$("#LoggedInUser").text(app.principal.displayName),$("#LogoutLink").removeClass("ui-icon-login"),$("#LogoutLink").addClass("ui-icon-logout"),$("#LogoutLink").attr("title","Logout"));$("#DumpData").on("click",function(){s="",app.persist.export()});$("#SendData").on("click",function(){e=app.createUUID(),$("#statusText").text("Getting data count"),app.persist.length().then(function(r){$("#statusText").text("Total items = "+r),n=r,$("#statusText").text("Getting Keys"),app.persist.iterate(function(r,u,f){var e="Got Key "+f+" of "+n+"\r\nKey = "+u,e="Getting key "+f+" of "+n+"\r\nKey = "+u;$("#statusText").text(e),h.push(u),f>=n&&($("#statusText").text("Retried all keys"),i=0,t())})})});var t=function(){var r,u;if(i>=n){$("#statusText").text("Done");return}r=h[i],i++,u="Sending to server "+i+" of "+n+"\r\nKey = "+r,$("#statusText").text(u),app.persist.getItem(r,function(n){app.post(app.vroot()+"Synchronize/DumpDataItem",{dataDumpId:e,storageType:"IndexDB",key:r,value:JSON.stringify(n)},function(){t()},function(){alert("Failed!")})})};$("#LoadData").on("click",function(){var t=document.getElementById("fileToLoad").files[0],n=new FileReader;n.onload=function(n){var t=n.target.result;app.persist.import(t)},n.readAsText(t,"UTF-8")})}),o=function(){if(u<localStorage.length){var n=localStorage.key(u),i=localStorage[n];u++,$("#DumpMessages").append("<li>Dumping Local Storage Value <a href='#' class='localStorage' data-id='"+n+"'>"+n+"<\/a><\/li>"),s+="##LOCALSTORAGE##="+i+"\r\n\r\n",o()}else app.getWebSqlKeys(function(n){n===null?$("#DumpMessages").append("<li>WebSQL database is empty<\/li>"):(r=n,$("#DumpMessages").append("<li>WebSql key count = "+r.rows.length+"<\/li>"),t())},function(){$("#DumpMessages").append("<li>WebSQL database is empty<\/li>")})},t=function(){if(f<r.rows.length){var n=r.rows.item(f).Key;f++,app.getWebSql(n,function(i){n.toUpperCase().indexOf("LIST")>0?$("#DumpMessages").append("<li>Dumping WebSql Value <a href='#' class='webSql' data-id='"+n+"'>"+n+"<\/a> count = "+i.length+"<\/li>"):$("#DumpMessages").append("<li>Dumping WebSql Value <a href='#' class='webSql' data-id='"+n+"'>"+n+"<\/a><\/li>"),app.post(app.vroot()+"Synchronize/DumpDataItem",{dataDumpId:c,storageType:"WebSQL",key:n,value:JSON.stringify(i)},function(){t()},function(){t()})},function(){$("#DumpMessages").append("<li>Failed getting WebSql data for key = "+n+"<\/li>"),t()})}else $("#DumpMessages").append("<li>Finished Dumping WebSQL<\/li>"),$("#DumpMessages").append("<li>Dump Complete<\/li>")}}}(),function(){function n(){app.post(app.vroot()+"Synchronize/GetLoadItem",{},function(t){var i,r;t!==null&&t!==undefined&&t.data!==undefined?t.data.indexOf("Local Storage")===0?(i=t.data.substring(14,t.data.indexOf(" = ")),i=i.substring(i.lastIndexOf("/")+1),r=t.data.substring(t.data.indexOf(" = ")+3),$("#LoadMessages").append("<li>Setting Local Storage value = "+i+"<\/li>"),Wndsr.setLocalStorage(i,r),n()):t.data.indexOf("WebSQL")===0&&(i=t.data.substring(7,t.data.indexOf(" = ")),r=t.data.substring(t.data.indexOf(" = ")+3),$("#LoadMessages").append("<li>Setting WebSQL value = "+i+"<\/li>"),app.setWebSql(i,r,function(){n()},function(){$("#LoadMessages").append("<li>Failed loading data<\/li>")})):$("#LoadMessages").append("<li>Load Complete<\/li>")},function(){$("#LoadMessages").append("<li>Failed loading data<\/li>")})}if($("#Content").data("currentView")==="Shared/LoadData"){var t=null;$(function(){t=Wndsr.getUrlParam("id"),t!==undefined&&app.post(app.vroot()+"Synchronize/BeginLoad",{id:t},function(){Wndsr.clearLocalStorage(),n()},function(){$("#LoadMessages").append("<li>Failed loading data<\/li>")})})}}(),function(){var n,t;if($("#Content").data("currentView")==="Shared/PrepIpad"){var f="",u=0,r=0,e=!1;$(function(){for(i=0;i<1048576;i++)f+="1";n()}),n=function(){e?r>=25?alert("Done"):app.persist.deleteItem("PrepData"+r,function(){r++,n()},t):u>=25?(e=!0,n()):app.persist.setItem("PrepData"+u,f,function(){u++,n()},t)},t=function(){alert("Failed")}}}(),function(){$("#Content").data("currentView")==="Project/Index"&&$(function(){var r,u,f,n,t,i;app.applyTheme($("#Content")),$("#ProjectTrackingButton").addClass("ui-active"),r=$(".js-start-date-answer"),u=$(".js-start-date-hidden"),u.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:r,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),f=$(".js-completed-date-answer"),n=$(".js-completed-date-hidden"),n.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:f,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),t=$(".js-on-hold-date-answer"),i=$(".js-on-hold-date-hidden"),i.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:t,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0});$("#ShowOnlyMine").on("change",function(){var t=Wndsr.getUrlParam("searchText"),i=Wndsr.getUrlParam("showCompleted"),n=app.vroot()+"Project";n+=$(this).is(":checked")?"?showOnlyMine=TRUE":"?showOnlyMine=FALSE",t!==undefined&&t!==null&&t!==""&&(n+="&searchText="+t),i!==undefined&&i!==null&&i!==""&&(n+="&showCompleted="+i),window.location=n});$("#ShowCompleted").on("change",function(){var t=Wndsr.getUrlParam("searchText"),i=Wndsr.getUrlParam("showOnlyMine"),n=app.vroot()+"Project";n+=$(this).is(":checked")?"?showCompleted=TRUE":"?showCompleted=FALSE",t!==undefined&&t!==null&&t!==""&&(n+="&searchText="+t),i!==undefined&&i!==null&&i!==""&&(n+="&showOnlyMine="+i),window.location=n});$("#Search").on("click",function(){var r=$("#SearchText").val(),i="FALSE",t="FALSE",n=app.vroot()+"Project";$("#ShowOnlyMine").is(":checked")&&(i="TRUE"),$("#ShowCompleted").is(":checked")&&(t="FALSE"),n+="?searchText="+encodeURI(r),n+="&showOnlyMine="+i,n+="&showCompleted="+t,window.location=n});$("#ProjectActions").menu();$("#ProjectsTable").on("click",".js-options-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#ProjectActions").hide();else{var n=$(this).data("projectId");$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#ProjectActions").css("top",$(this).offset().top+$(this).height()),$("#ProjectActions").data("ProjectId",n),$("#ProjectActions").show();$("html").on("click",function(){$(this).is("#ProjectActions")||$("#ProjectActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click"))})}return!1});$("#ProjectDetails").on("click",function(){var n=$("#ProjectActions").data("ProjectId");$.blockUI(),app.getProject(n,function(n){$("#ProjectId").val(n.id),$("#AddProjectDialog").dialog("option","title","Edit Project"),$("#ProjectTitle").val(n.projectTitle),$("#ClientName").val(n.clientName),n.projectManager===undefined||n.projectManager===null?$("#ProjectManager").val(""):$("#ProjectManager").val(n.projectManager.id),n.startDate!==undefined&&n.startDate!==null?$(".js-start-date-answer").val(moment(n.startDate).format("M/D/YYYY")):$(".js-start-date-answer").val(""),n.completedDate!==undefined&&n.completedDate!==null?$(".js-completed-date-answer").val(moment(n.completedDate).format("M/D/YYYY")):$(".js-completed-date-answer").val(""),n.onHoldDate!==undefined&&n.onHoldDate!==null?$(".js-on-hold-date-answer").val(moment(n.onHoldDate).format("M/D/YYYY")):$(".js-on-hold-date-answer").val(""),$("#AddProjectDialog").dialog("open"),$.unblockUI()},function(){$.unblockUI(),alert("Failed getting project")},!0),$(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click")});$("#MarkComplete").on("click",function(){if(confirm("Are you sure you want to make this project complete?")){var n=$("#ProjectActions").data("ProjectId");$.blockUI(),app.getProject(n,function(t){t.completedDate===undefined||t.completedDate===null?app.post(app.vroot()+"Project/MarkComplete/"+n,{id:t.id},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed marking project complete")}):(alert("This project is already marked complete."),$.unblockUI())},function(){$.unblockUI(),alert("Failed getting project")},!0),$(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click")}});$("#DownloadPhotos").on("click",function(){if(confirm("Are you sure you want to download all photos for this project?")){var n=$("#ProjectActions").data("ProjectId");$.blockUI(),app.getProject(n,function(t){t.completedDate===undefined||t.completedDate===null?app.post(app.vroot()+"Project/MarkComplete/"+n,{id:t.id},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed marking project complete")}):(alert("This project is already marked complete."),$.unblockUI())},function(){$.unblockUI(),alert("Failed getting project")},!0),$(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click")}});$("#RemoveProject").on("click",function(){if(confirm("Are you sure you want to remove this project?")){var n=$("#ProjectActions").data("ProjectId");$.blockUI(),app.getProject(n,function(t){if(t.inspectionCount>0)return alert("You cannot remove a project that has inspections attached"),$.unblockUI(),!1;app.post(app.vroot()+"Project/Remove/"+n,{id:t.id},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed deleting project.")})},function(){$.unblockUI(),alert("Failed getting project")},!0),$(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click")}});$("#AddInspection").on("click",function(){var t=window.location.href,n=$("#ProjectActions").data("ProjectId");window.location=app.vroot()+"Site?mode=3&projectId="+n+"&returnUrl="+t});$("#DownloadImages").on("click",function(){var n=$("#ProjectActions").data("ProjectId");return window.location.href=app.vroot()+"Report/GetProjectImages?projectId="+n,!1});$("#AddProject").on("click",function(){$("#ProjectId").val(""),$("#AddProjectDialog").dialog("option","title","Add Project"),$("#ProjectTitle").val(""),$("#ClientName").val(""),$("#ProjectManager").val(app.principal.id),$(".js-start-date-answer").val(""),$(".js-completed-date-answer").val(""),$(".js-on-hold-date-answer").val(""),$("#AddProjectDialog").dialog("open")});$(".generateReport").on("click",function(){var i=$("#ProjectActions").data("ProjectId"),t=$(this).data("reportType"),n=(new Date).getTimezoneOffset();window.location.href=app.vroot()+"Report/GetProjectReport?projectId="+i+"&curDateOffset="+n+"&reportType="+t});$(".generateIssueLog").on("click",function(){var i=$("#ProjectActions").data("ProjectId"),t=$(this).data("reportType"),n=(new Date).getTimezoneOffset();window.location.href=app.vroot()+"Report/GetEndReport?projectId="+i+"&curDateOffset="+n+"&reportType="+t});$("#AddProjectDialog").dialog({title:"Add Project",autoOpen:!1,modal:!0,resizable:!1,height:490,minHeight:490,width:575,minWidth:575,buttons:{OK:function(){var r=$.trim($("#ProjectTitle").val()),u=$.trim($("#ClientName").val()),e=$("#ProjectManager").val(),i=$.trim($(".js-start-date-answer").val()),n=$.trim($(".js-completed-date-answer").val()),t=$.trim($(".js-on-hold-date-answer").val()),f=$("#ProjectId").val();if(r===undefined||r===null||r==="")return alert("Project Title is required."),!1;if(u===undefined||u===null||u==="")return alert("Client Name is required."),!1;if(i!==undefined&&i!==null&&i!==""&&!Wndsr.isValidDate(i))return alert("Start Date must be a valid date"),!1;if(n!==undefined&&n!==null&&n!==""&&!Wndsr.isValidDate(n))return alert("Completed Date must be a valid date"),!1;if(t!==undefined&&t!==null&&t!==""&&!Wndsr.isValidDate(t))return alert("On Hold Date must be a valid date"),!1;if(t!==undefined&&t!==null&&t!==""&&n!==undefined&&n!==null&&n!=="")return alert("A project cannot have both an On Hold Date and a Completed Date."),!1;$.blockUI(),f===""?app.post(app.vroot()+"Project/SaveNew/0",{projectTitle:r,clientName:u,projectManager:e,startDate:i,completedDate:n,onHoldDate:t},function(){window.location=app.vroot()+"Project/"},function(){$.unblockUI(),alert("Failed saving new project")}):app.post(app.vroot()+"Project/EditExisting/"+f,{id:f,projectTitle:r,clientName:u,projectManager:e,startDate:i,completedDate:n,onHoldDate:t},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed editing project")})},Cancel:function(){$("#AddProjectDialog").dialog("close")}}}),Wndsr.setLocalStorage("backToProjectList",window.location.href)})}(),function(){$("#Content").data("currentView")==="Project/Edit"&&$(function(){var f,e,r,u,n;app.applyTheme($("#Content"));var t=!1,c=$(".js-date-answer"),h=$(".js-date-hidden");h.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:c,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),f=$(".js-inspection-date-answer"),e=$(".js-inspection-date-hidden"),e.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:f,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),r=$(".js-inspection-review-date-answer"),u=$(".js-inspection-review-date-hidden"),u.datepicker({showOn:"button",buttonImage:app.vroot()+"Content/images/calendar.png",buttonImageOnly:!0,altField:r,altFormat:"mm/dd/yy",changeMonth:!0,changeYear:!0,showOtherMonths:!0,selectOtherMonths:!0}),$("#ProjectActions").menu();$("#PageHeaderInline").on("click",".js-options-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#ProjectActions").hide();else{var n=$("#ProjectId").val();$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#ProjectActions").css("top",$(this).offset().top+$(this).height()),$("#ProjectActions").data("ProjectId",n),$("#ProjectActions").show();$("html").on("click",function(){$(this).is("#ProjectActions")||$("#ProjectActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click"))})}return!1});$("#InspectionActions").menu();$("#InspectionsTable").on("click",".js-options-button",function(){if($(this).is(".ui-active"))$(this).removeClass("ui-active"),$("#InspectionActions").hide();else{app.isOnline?($(".generatePDFOption").show(),$(".generateReport").show(),$(".downlaodImages").show()):($(".generatePDFOption").hide(),$(".generateReport").hide(),$(".downlaodImages").hide());var n=$(this).data("inspection-id");$(".js-options-button").removeClass("ui-active"),$(this).addClass("ui-active"),$("#InspectionActions").css("top",$(this).offset().top+$(this).height()),$("#InspectionActions").data("inspection-id",n),$("#InspectionActions").show();$("html").on("click",function(){$(this).is("#InspectionActions")||$("#InspectionActions").has($(this)).length!==0||($(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),$("html").off("click"))})}return!1});$("#ProjectDetails").on("click",function(){var n=$("#ProjectId").val();$.blockUI(),app.getProject(n,function(n){$("#ProjectId").val(n.id),$("#AddProjectDialog").dialog("option","title","Edit Project"),$("#ProjectTitle").val(n.projectTitle),$("#ClientName").val(n.clientName),n.projectManager===undefined||n.projectManager===null?$("#ProjectManager").val(""):$("#ProjectManager").val(n.projectManager.id),n.startDate!==undefined&&n.startDate!==null?$(".js-start-date-answer").val(moment(n.startDate).format("M/D/YYYY")):$(".js-start-date-answer").val(""),n.completedDate!==undefined&&n.completedDate!==null?$(".js-completed-date-answer").val(moment(n.completedDate).format("M/D/YYYY")):$(".js-completed-date-answer").val(""),n.onHoldDate!==undefined&&n.onHoldDate!==null?$(".js-on-hold-date-answer").val(moment(n.onHoldDate).format("M/D/YYYY")):$(".js-on-hold-date-answer").val(""),$("#AddProjectDialog").dialog("open"),$.unblockUI()},function(){$.unblockUI(),alert("Failed getting project")},!0),$(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click")});$("#BackButton").on("click",function(){var n=Wndsr.getLocalStorage("backToProjectList");window.location=n});$("#MarkComplete").on("click",function(){if(confirm("Are you sure you want to make this project complete?")){var n=$("#ProjectId").val();$.blockUI(),app.getProject(n,function(t){t.completedDate===undefined||t.completedDate===null?app.post(app.vroot()+"Project/MarkComplete/"+n,{id:t.id},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed marking project complete")}):(alert("This project is already marked complete."),$.unblockUI())},function(){$.unblockUI(),alert("Failed getting project")},!0),$(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click")}});$("#RemoveProject").on("click",function(){if(confirm("Are you sure you want to remove this project?")){var n=$("#ProjectId").val();$.blockUI(),app.getProject(n,function(t){if(t.inspections.length>0)return alert("You cannot remove a project that has inspections attached"),$.unblockUI(),!1;app.post(app.vroot()+"Project/Remove/"+n,{id:t.id},function(){window.location=app.vroot()+"Project"},function(){$.unblockUI(),alert("Failed deleting project.")})},function(){$.unblockUI(),alert("Failed getting project")},!0),$(".js-options-button").removeClass("ui-active"),$("#ProjectActions").hide(),$("html").off("click")}});$("#AddInspection, #AddInspectionButton").on("click",function(){var t=window.location.href,n=$("#ProjectId").val();window.location=app.vroot()+"Site?mode=3&projectId="+n+"&returnUrl="+t});$(".generateProjectReport").on("click",function(){var i=$("#ProjectId").val(),t=$(this).data("reportType"),n=(new Date).getTimezoneOffset();window.location.href=app.vroot()+"Report/GetProjectReport?projectId="+i+"&curDateOffset="+n+"&reportType="+t});$(".generateIssueLog").on("click",function(){var i=$("#ProjectId").val(),t=$(this).data("reportType"),n=(new Date).getTimezoneOffset();window.location.href=app.vroot()+"Report/GetEndReport?projectId="+i+"&curDateOffset="+n+"&reportType="+t});$(".js-inspection-site-name-link").on("click",function(){return app.isMobile()&&app.principal.login!==$(this).data("login")&&$(this).data("is-complete")==="False"?(alert("When on a mobile device, you can only edit inspections assigned to you and incomplete"),!1):$(this).data("is-complete")==="True"?(alert("You can only edit inspections that are complete"),!1):!0});$("#RequiredAnswerMessage").dialog({title:"Cannot Complete Inspection",autoOpen:!1,modal:!0,resizable:!1,buttons:{OK:function(){$(this).dialog("close")}}}),$("#AddProjectDialog").dialog({title:"Add Project",autoOpen:!1,modal:!0,resizable:!1,height:490,minHeight:490,width:575,minWidth:575,buttons:{OK:function(){var r=$.trim($("#ProjectTitle").val()),u=$.trim($("#ClientName").val()),e=$("#ProjectManager").val(),i=$.trim($(".js-start-date-answer").val()),n=$.trim($(".js-completed-date-answer").val()),t=$.trim($(".js-on-hold-date-answer").val()),f=$("#ProjectId").val();if(r===undefined||r===null||r==="")return alert("Project Title is required."),!1;if(u===undefined||u===null||u==="")return alert("Client Name is required."),!1;if(i!==undefined&&i!==null&&i!==""&&!Wndsr.isValidDate(i))return alert("Start Date must be a valid date"),!1;if(n!==undefined&&n!==null&&n!==""&&!Wndsr.isValidDate(n))return alert("Completed Date must be a valid date"),!1;if(t!==undefined&&t!==null&&t!==""&&!Wndsr.isValidDate(t))return alert("On Hold Date must be a valid date"),!1;if(t!==undefined&&t!==null&&t!==""&&n!==undefined&&n!==null&&n!=="")return alert("A project cannot have both an On Hold Date and a Completed Date."),!1;$.blockUI(),f===""?app.post(app.vroot()+"Project/SaveNew/0",{projectTitle:r,clientName:u,projectManager:e,startDate:i,completedDate:n,onHoldDate:t},function(){window.location=app.vroot()+"Project/"},function(){$.unblockUI(),alert("Failed saving new project")}):app.post(app.vroot()+"Project/EditExisting/"+f,{id:f,projectTitle:r,clientName:u,projectManager:e,startDate:i,completedDate:n,onHoldDate:t},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed editing project")})},Cancel:function(){$("#AddProjectDialog").dialog("close")}}}),$("#AddSiteDialog").dialog({title:"Edit Inspection",autoOpen:!1,modal:!0,resizable:!1,height:725,minHeight:725,width:575,minWidth:575,close:function(){t=!1},buttons:{OK:function(){var u,f,c,s,h;if(t){var r=$.trim($(".js-date-answer").val()),i=$.trim($(".js-inspection-date-answer").val()),e=$.trim($(".js-inspection-review-date-answer").val()),p=$("#InspectionDescription").val(),y=$("#InspectorSelect").val(),b=$("#InspectionTypeSelect").val(),w=$("#ReviewerSelect").val(),l=new moment,o=$("#ProjectSelect").val(),a=$("#ProjectId").val(),v=[];if($("input[type=checkbox]:checked","tbody").each(function(){v.push($(this).data("id"))}),r.length>0&&!Wndsr.isValidDate(r)){alert(r+" is an invalid date"),$(".js-date-answer").val("");return}if(r.length>0&&moment(r).add("days",120)<l){alert("Scheduled Date cannot be more than 120 days old");return}if(i.length>0&&moment(i).add("days",120)<l){alert("Evaluation Date cannot be more than 120 days old");return}if(e.length>0){if(u=new moment(e),u=u.startOf("day"),f=new moment,f=f.startOf("day"),c=f.add("d",30),u>c){alert("Review Request date must be less than 30 days in the future");return}if(i.length>0){if(s=new moment(i),u<s.startOf("day")){alert("Review Request date must be after the Evaluation Date");return}}else if(h=new moment(r),u<h.startOf("day")){alert("request review date cannot be before the Scheduled Date"),$(".js-inspection-review-date-answer").val("");return}}$.blockUI(),app.post(app.vroot()+"Project/GroupEdit/"+a,{id:a,inspectionIds:v,projectId:o,description:p,inspectorId:y,inspectionType:b,scheduledDate:r,evaluationDate:i,requestReviewDate:e,reviewerId:w},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed marking project complete")})}else{var r=$.trim($(".js-date-answer").val()),i=$.trim($(".js-inspection-date-answer").val()),e=$.trim($(".js-inspection-review-date-answer").val()),l=new moment,o=$("#ProjectSelect").val();if(r.length==0){alert("Inspection Date is required");return}if(!Wndsr.isValidDate(r)){alert(r+" is an invalid date"),$(".js-date-answer").val("");return}if(i.length>0&&!Wndsr.isValidDate(i)){alert(i+" is an invalid date"),$(".js-inspection-date-answer").val("");return}if(r.length>0&&moment(r).add("days",120)<l){alert("Scheduled Date cannot be more than 120 days old");return}if(i.length>0&&moment(i).add("days",120)<l){alert("Evaluation Date cannot be more than 120 days old");return}if(e.length>0){if(u=new moment(e),u=u.startOf("day"),f=new moment,f=f.startOf("day"),c=f.add("d",30),u>c){alert("Review Request date must be less than 30 days in the future");return}if(i.length>0){if(s=new moment(i),u<s.startOf("day")){alert("Review Request date must be after the Evaluation Date");return}}else if(h=new moment(r),u<h.startOf("day")){alert("request review date cannot be before the Scheduled Date"),$(".js-inspection-review-date-answer").val("");return}}if(editInspection.site.siteKey!==null&&editInspection.site.siteKey!==undefined&&editInspection.site.siteKey!==""&&$("#SiteKeyTextBox").is(":visible")&&$("#SiteKeyTextBox").val()==="")return alert($("#SiteKeyLabel").val()+" is required"),!1;$.blockUI(),editInspection.scheduledStart=moment(r).format(),editInspection.changedOn=moment(new Date).format(),editInspection.principalId=$("#InspectorSelect").val(),editInspection.principalId===""&&(editInspection.principal=null),$("#ReviewerSelect").val()!==""?editInspection.reviewPrincipalId=$("#ReviewerSelect").val():(editInspection.reviewPrincipalId=null,editInspection.reviewPrincipal=null),editInspection.inspectionTypeCode=$("#InspectionTypeSelect").val(),editInspection.actualStart=i.length>0?moment(i).format():null,$("#SiteKeyTextBox").is(":visible")&&(editInspection.site.siteKey=$("#SiteKeyTextBox").val()),e.length>0?editInspection.reviewRequestDate=moment(e).format():(editInspection.reviewRequestDate=null,editInspection.reviewPrincipal=null),editInspection.description=$("#InspectionDescription").val(),editInspection.projectId=o,(o===undefined||o===null||o==="")&&(editInspection.removeFromProject=!0),editInspection.isDirty=!0,app.updateInspection(editInspection,function(){window.location.reload()},n,!0)}},Cancel:function(){$("#AddSiteDialog").dialog("close")}}});$("#InspectionDetails").on("click",function(){$.blockUI();var t=$("#InspectionActions").data("inspection-id");app.getInspection(t,function(n){editInspection=n,$("#SiteDisplayName").text(n.site.siteName),$("#SiteKeyLabel").text(n.site.siteKey),$("#SiteKeyTextBox").val(n.site.siteKey),$("#InspectorSelect").val(app.principal.id),$("#InspectionTypeSelect").val(n.inspectionTypeCode),$("#ProjectSelect").val(n.project.id),$(".js-date-answer").val(moment(n.scheduledStart).format("M/D/YYYY")),n.project!==null&&$("#ProjectTitle2").text(n.project.projectTitle),$("#InspectionDescription").val(n.description),n.actualStart!==undefined&&n.actualStart!==null?$(".js-inspection-date-answer").val(moment(n.actualStart).format("M/D/YYYY")):$(".js-inspection-date-answer").val(""),n.reviewRequestDate!==undefined&&n.reviewRequestDate!==null?$(".js-inspection-review-date-answer").val(moment(n.reviewRequestDate).format("M/D/YYYY")):$(".js-inspection-review-date-answer").val(""),n.reviewPrincipal!==undefined&&n.reviewPrincipal!==null?$("#ReviewerSelect").val(n.reviewPrincipal.id):$("#ReviewerSelect").val(""),n.site.siteKey!==undefined&&n.site.siteKey!==null&&n.site.siteKey!==""?($("#SiteKeyLabel").hide(),$("#SiteKeyTextBox").show()):n.site.siteKey===undefined||n.site.siteKey===null||n.site.siteKey===""?($("#SiteKeyLabel").hide(),$("#SiteKeyTextBox").show()):($("#SiteKeyLabel").show(),$("#SiteKeyTextBox").hide()),n.inspectionSource===undefined||n.inspectionSource===null||n.inspectionSource===""?$("#InspectionSource").text($("#ApplicationName").val()):$("#InspectionSource").text(n.inspectionSource),app.getInspectionTypes(function(t){for(var r="",u=!1,i=0;i<t.length;i++)t[i].code===n.inspectionTypeCode&&(u=!0),r+="<option value='"+t[i].code+"'>"+t[i].name+"<\/option>";u&&$("#InspectionTypeSelect").html(r),$("#InspectionTypeSelect").val(n.inspectionTypeCode),$("#SiteDisplayName").parent().show(),$("#SiteKeyTextBox").parent().show(),$("#InspectionSource").parent().show(),$("#AddSiteDialog").dialog("option","height",725),$("#AddSiteDialog").dialog("option","maxHeight",725),$("#AddSiteDialog").dialog("open"),$.unblockUI()},function(){$.unblockUI(),alert("Failed getting inspection types")})},n,!0)});n=function(n){n.statusText==="Retry with authentication"?alert("Your session has expired, please log in again."):alert("Failed getting inspection list"),$.unblockUI(),Wndsr.error("GetInspectionList Failed")};$("#MapSiteAddress").on("click",function(){var t=$("#InspectionActions").data("inspection-id");return app.getInspection(t,function(n){var t=n.site.siteAddresses[0].addressLineOne+" "+n.site.siteAddresses[0].city+","+n.site.siteAddresses[0].state+" "+n.site.siteAddresses[0].zipCode;window.open("http://maps.google.com/maps?daddr="+t+"&t=h")},n,!0),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#EditButton").on("click",function(){if($("input[type=checkbox]:checked","tbody").length===0){alert("You must select at least one inspection.");return}$.blockUI(),t=!0,$("#SiteDisplayName").parent().hide(),$("#SiteKeyTextBox").parent().hide(),$("#InspectionSource").parent().hide(),$("#AddSiteDialog").dialog("option","height",600),$("#AddSiteDialog").dialog("option","maxHeight",600),$("#ProjectSelect").val($("#ProjectId").val()),$("#InspectorSelect").val(""),$(".js-date-answer").val("").next().val(""),$(".js-inspection-date-answer").val("").next().val(""),$(".js-inspection-review-date-answer").val("").next().val(""),$("#ReviewerSelect").val(""),$("#InspectionDescription").val(""),app.getInspectionTypes(function(n){for(var i="<option><\/option>",r=!1,t=0;t<n.length;t++)i+="<option value='"+n[t].code+"'>"+n[t].name+"<\/option>";$("#InspectionTypeSelect").html(i),$("#InspectionTypeSelect").val(""),$("#AddSiteDialog").dialog("open"),$.unblockUI()},function(){$.unblockUI(),alert("Failed getting inspection types")}),$("#AddSiteDialog").dialog("open")});$("#DownloadImages").on("click",function(){var n=$("#ProjectActions").data("ProjectId");return window.location.href=app.vroot()+"Report/GetProjectImages?projectId="+n,!1});$("#DeleteButton").on("click",function(){if($("input[type=checkbox]:checked","tbody").length===0){alert("You must select at least one inspection.");return}t=!0,$.blockUI();var i=$("#ProjectId").val(),n=[];$("input[type=checkbox]:checked","tbody").each(function(){n.push($(this).data("id"))}),app.post(app.vroot()+"Project/GroupDelete/"+i,{id:i,inspectionIds:n},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed deleting inspections")})});$("#CompleteButton").on("click",function(){if($("input[type=checkbox]:checked","tbody").length===0){alert("You must select at least one inspection.");return}t=!0,$.blockUI();var i=$("#ProjectId").val(),n=[];$("input[type=checkbox]:checked","tbody").each(function(){n.push($(this).data("id"))}),app.post(app.vroot()+"Project/GroupComplete/"+i,{id:i,inspectionIds:n},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed completing inspections")})});$("#UncompleteButton").on("click",function(){if($("input[type=checkbox]:checked","tbody").length===0){alert("You must select at least one inspection.");return}t=!0,$.blockUI();var i=$("#ProjectId").val(),n=[];$("input[type=checkbox]:checked","tbody").each(function(){n.push($(this).data("id"))}),app.post(app.vroot()+"Project/GroupUncomplete/"+i,{id:i,inspectionIds:n},function(){window.location.reload()},function(){$.unblockUI(),alert("Failed uncompleting inspections")})});$("#RemoveInspection").on("click",function(){if(confirm("Permanently delete all the forms and data for this inspection?")){var t=$("#InspectionActions").data("inspection-id");app.getInspection(t,function(i){for(var u=!1,r=0;r<i.inspectionFormInfoList.length;r++)if(i.inspectionFormInfoList[r].isDeleted==!1){u=!0;break}u&&!app.principal.isAdmin?alert("Cannot remove this inspection. There are forms attached to this inspection."):app.deleteInspection(t,function(){window.location.reload()},n,!0)},function(){alert("Could not remove inspection")},!0)}return $(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#ShowViolations").on("click",function(){if(app.isOnline){var n=$("#InspectionActions").data("inspection-id"),t=$("input[data-id="+n+"]").parent().parent().find(".inspector-name").text();if(app.isMobile()&&t!=app.principal.displayName){alert("From a mobile device, you can only see violations for inspections assigned to you.");return}window.location=app.vroot()+"Inspection/ViolationList?inspectionId="+n}else alert("Violations cannot be displayed while offline")});$(".generateInspectionReport").on("click",function(){var i=(new Date).getTimezoneOffset(),t=$("#InspectionActions").data("inspection-id"),n=$(this).data("reportType");return window.location.href=app.vroot()+"Report/GetReport?inspectionId="+t+"&curDateOffset="+i+"&reportType="+n,$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#RequestInspectionReview").on("click",function(){var t=$("#InspectionActions").data("inspection-id"),f=$("input[data-id="+t+"]").parent().parent().find(".inspector-name").text(),r,u;if(app.isMobile()&&f!=app.principal.displayName){alert("From a mobile device, you can only request inspection review for inspections assigned to you.");return}return r=$("body").data("issearchnforce"),r==="True"?(u=$("div[data-inspection-id="+t+"]").parents("tr").find(".js-site-key").text(),app.post(app.vroot()+"Site/IsInNForce/0",{siteKey:u},function(r){r?confirm("Are you sure you want to request a review on this inspection?")&&app.getInspection(t,i,n):alert("The new "+$("#SiteLabel").val()+" must be added to nForce before the inspection can be completed")},o)):confirm("Are you sure you want to request a review on this inspection?")&&app.getInspection(t,i,n,!0),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});var i=function(t){if(!t){showMapFailed();return}Wndsr.info("Request inspection Success - complete"),app.validateInspection(t,function(i){i?(t.reviewRequestDate=moment(new Date).format(),app.updateInspection(t,s,n)):($("#RequiredAnswerMessage").dialog("open"),$.unblockUI())})},o=function(){alert("Failed getting inspection to complete"),$.unblockUI(),Wndsr.error("GetInspection Failed - complete")},s=function(n){Wndsr.info("Update inspection Success"),n!==undefined&&n.message!==null&&n.message!==undefined&&alert(n.message),window.location.reload()};$("#MarkInspectionComplete").on("click",function(){var t=$("#InspectionActions").data("inspection-id"),f=$("input[data-id="+t+"]").parent().parent().find(".inspector-name").text(),r,u;if(app.isMobile()&&f!=app.principal.displayName){alert("From a mobile device, you can only mark inspections complete for inspections assigned to you.");return}return r=$("body").data("issearchnforce"),r==="True"?(u=$("div[data-inspection-id="+t+"]").parents("tr").find(".js-site-key").text(),app.post(app.vroot()+"Site/IsInNForce/0",{siteKey:u},function(r){r?confirm("Mark Inspection as complete?")&&($.blockUI({message:"<h1>Please Wait...<\/h1>"}),app.getInspection(t,i,n)):alert("The new "+$("#SiteLabel").val()+" must be added to nForce before the inspection can be completed")},n)):(confirm("Mark Inspection as complete?")&&($.blockUI({message:"<h1>Please Wait...<\/h1>"}),t=$("#InspectionActions").data("inspection-id"),app.getInspection(t,i,n,!0)),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide()),$(".js-options-button").removeClass("ui-active"),$("#InspectionActions").hide(),!1});$("#ProjectsFilter").on("keyup",function(){var f=$(this).val().trim().toUpperCase(),t,n,u,r,i;if(f==="")$("tr","#InspectionsTable").show();else for(t=$("tr","#InspectionsTable tbody"),n=0;n<t.length;n++){for(u=!1,r=$("td",t[n]),i=0;i<r.length;i++)if($(r[i]).text().trim().toUpperCase().indexOf(f)>=0){u=!0;break}u?$(t[n]).show():($(t[n]).hide(),$("input[type=checkbox]",t[n]).removeAttr("checked"))}});$("#SelectAll").on("change",function(){$("#SelectAll").is(":checked")?$(".selectProjectInspection").prop("checked",!0):$(".selectProjectInspection").prop("checked",!1)})})}(),function(){$("#Content").data("currentView")==="NotificationTemplate/Index"&&$(function(){$("#NewNotificationButton").button(),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});$(".js-up-notification").button({text:!1,icons:{primary:"ui-icon-admin-up"}}),$(".js-down-notification").button({text:!1,icons:{primary:"ui-icon-admin-down"}});$("#AdminTable").on("click",".js-up-notification",function(){var n=$(this).data("id");$.ajax({type:"POST",url:app.vroot()+"NotificationTemplate/MoveUp/"+n,data:JSON.stringify({id:n}),contentType:"application/json; charset=utf-8",success:function(){window.location=app.vroot()+"NotificationTemplate/"},error:function(){alert("Move Up Failed")}})});$("#AdminTable").on("click",".js-down-notification",function(){var n=$(this).data("id");$.ajax({type:"POST",url:app.vroot()+"NotificationTemplate/MoveDown/"+n,data:JSON.stringify({id:n}),contentType:"application/json; charset=utf-8",success:function(){window.location=app.vroot()+"NotificationTemplate/"},error:function(){alert("Move Up Failed")}})});$("#NewNotificationButton").on("click",function(){window.location=app.vroot()+"NotificationTemplate/New"})})}(),function(){$("#Content").data("currentView")==="NotificationTemplate/Edit"&&$(function(){function n(n){var t=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return t.test(n)}$("#CancelButton").button(),$("#SaveButton").button(),$("#AddEmail").button(),$("#RemoveEmail").button({disabled:!0}),$("#AddTag").button(),$("#RemoveTag").button({disabled:!0}),tinymce.init({selector:"#EmailMessage"}),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});var t=jQuery("select.select2").select2({placeholder:"None selected"});jQuery("select.select2--tag").select2({tagging:!0,placeholder:"Enter text to create a new entry"});$("#CancelButton").on("click",function(){window.location=app.vroot()+"NotificationTemplate/"});$("#SaveButton").on("click",function(){var s,o,h,i,f,t;$.blockUI();var y=$("#Id").val(),u=$("#NotificationTemplateEventType").val(),v=[];for($($("#Organizations").select2("data")).each(function(n,t){v.push(t.id)}),s=[],$($("#InspectionTypes").select2("data")).each(function(n,t){s.push(t.id)}),o=[],$($("#Forms").select2("data")).each(function(n,t){o.push(t.id)}),h=[],$($("#Groups").select2("data")).each(function(n,t){h.push(t.id)}),i=[],f=$.trim($("#EmailAddresses").val()),f.length>0&&(i=f.split("\n")),t=0;t<i.length;t++)i[t]=i[t].trim();var e=[],p=$.trim($("#Tags").val()),r="";for(p.length>0&&(e=p.split("\n")),t=0;t<e.length;t++)r.length>0&&(r+="|"),r+=e[t].trim();var l=$("#EmailSubject").val(),a=tinymce.get("EmailMessage").getContent(),w=$("#attachInspectionReport").is(":checked"),c=$.trim($("#Description").val());if(u===null||u===undefined||u===""){alert("Event type is required"),$.unblockUI();return}for(t=0;t<i.length;t++)if(!n(i[t])){alert(i[t]+" is an invalid email address"),$.unblockUI();return}if($.trim(l)===""){alert("Email Subject is required"),$.unblockUI();return}if($.trim(a)===""){alert("Email Message is required"),$.unblockUI();return}if($.trim(c)===""){alert("Description is required"),$.unblockUI();return}app.post(app.vroot()+"NotificationTemplate/SaveEdit/"+y,{id:y,notificationTemplateEventType:u,organizations:v,inspectionTypes:s,forms:o,groups:h,emailAddresses:i,tags:r,emailSubject:l,emailMessage:a,isAttachInspectionReport:w,description:c},function(n){n.message===""?window.location=app.vroot()+"NotificationTemplate/":(alert(n.message),$.unblockUI())},function(){alert("Save Failed"),$.unblockUI()})});$("#NotificationTemplateEventType").focus()})}(),function(){$("#Content").data("currentView")==="NotificationTemplate/New"&&$(function(){function n(n){var t=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return t.test(n)}$("#CancelButton").button(),$("#SaveButton").button(),$("#AddEmail").button(),$("#RemoveEmail").button({disabled:!0}),$("#AddTag").button(),$("#RemoveTag").button({disabled:!0}),tinymce.init({selector:"#EmailMessage"}),$("#AdminButton").addClass("ui-active");$("#AdminPageSelect").on("change",function(){$(this).val()==="Users"?window.location=app.vroot()+"Principal/":$(this).val()==="Groups"?window.location=app.vroot()+"Group/":$(this).val()==="Organizations"?window.location=app.vroot()+"Organization/":$(this).val()==="InspectionTypes"?window.location=app.vroot()+"InspectionType/":$(this).val()==="Forms"?window.location=app.vroot()+"Form/":$(this).val()==="Report Templates"?window.location=app.vroot()+"ReportTemplate/":$(this).val()==="Form Report Templates"?window.location=app.vroot()+"FormReportTemplate/":$(this).val()==="IntegrationStatus"?window.location=app.vroot()+"InspectionSync/":$(this).val()==="ImportExport"?window.location=app.vroot()+"InspectionImport":$(this).val()==="Notifications"&&(window.location=app.vroot()+"NotificationTemplate/")});var t=jQuery("select.select2").select2({placeholder:"None selected"});jQuery("select.select2--tag").select2({tagging:!0,placeholder:"Enter text to create a new entry"});$("#CancelButton").on("click",function(){window.location=app.vroot()+"NotificationTemplate/"});$("#SaveButton").on("click",function(){var r,s,o,c,h,i,e,t;$.blockUI(),r=$("#NotificationTemplateEventType").val(),s=[],$($("#Organizations").select2("data")).each(function(n,t){s.push(t.id)}),o=[],$($("#InspectionTypes").select2("data")).each(function(n,t){o.push(t.id)}),c=[],$($("#Forms").select2("data")).each(function(n,t){c.push(t.id)}),h=[],$($("#Groups").select2("data")).each(function(n,t){h.push(t.id)}),i=[],e=$.trim($("#EmailAddresses").val()),e.length>0&&(i=e.split("\n"));var f=[],v=$.trim($("#Tags").val()),u="";for(v.length>0&&(f=v.split("\n")),t=0;t<f.length;t++)u.length>0&&(u+="|"),u+=f[t];var y=$("#EmailSubject").val(),l=tinymce.get("EmailMessage").getContent(),p=$("#attachInspectionReport").is(":checked"),a=$.trim($("#Description").val());if(r===null||r===undefined||r===""){alert("Event type is required"),$.unblockUI();return}for(t=0;t<i.length;t++)if(!n(i[t])){alert(i[t]+" is an invalid email address"),$.unblockUI();return}if($.trim(y)===""){alert("Email Subject is required"),$.unblockUI();return}if($.trim(l)===""){alert("Email Message is required"),$.unblockUI();return}if($.trim(a)===""){alert("Description is required"),$.unblockUI();return}app.post(app.vroot()+"NotificationTemplate/SaveNew/0",{notificationTemplateEventType:r,organizations:s,inspectionTypes:o,forms:c,groups:h,emailAddresses:i,tags:u,emailSubject:y,emailMessage:l,isAttachInspectionReport:p,description:a},function(n){n.message===""?window.location=app.vroot()+"NotificationTemplate/":(alert(n.message),$.unblockUI())},function(){alert("Save Failed"),$.unblockUI()})});$("#NotificationTemplateEventType").focus()})}()