/* Minification failed. Returning unminified contents. (425,79-80): run-time error JS1100: Expected ',': = (425,86-87): run-time error JS1002: Syntax error: , (482,94-95): run-time error JS1100: Expected ',': = (506,93-94): run-time error JS1100: Expected ',': = (530,96-97): run-time error JS1100: Expected ',': = (555,95-96): run-time error JS1100: Expected ',': = (579,83-84): run-time error JS1100: Expected ',': = (2896,26-34): run-time error JS1004: Expected ';': function (2903,51-59): run-time error JS1193: Expected ',' or ')': response (2908,15-19): run-time error JS1004: Expected ';': site (2921,39-40): run-time error JS1195: Expected expression: > (2926,22-23): run-time error JS1195: Expected expression: ) (2930,22-23): run-time error JS1195: Expected expression: ) (2934,1-2): run-time error JS1002: Syntax error: } (2937,1-2): run-time error JS1002: Syntax error: } (2939,43-44): run-time error JS1004: Expected ';': { (2948,33-34): run-time error JS1195: Expected expression: > (2951,6-7): run-time error JS1195: Expected expression: ) (2954,7-15): run-time error JS1004: Expected ';': function (2998,80-81): run-time error JS1195: Expected expression: > (3001,6-7): run-time error JS1195: Expected expression: ) (3004,6-7): run-time error JS1195: Expected expression: ) (3409,29-30): run-time error JS1195: Expected expression: > (3409,31-32): run-time error JS1197: Too many errors. The file might not be a JavaScript file: { (3401,46-62): run-time error JS1301: End of file encountered before function is properly closed: function (event) (3410,17-19): run-time error JS1193: Expected ',' or ')': if (3416,14-15): run-time error JS1004: Expected ';': ) (3417,13-14): run-time error JS1197: Too many errors. The file might not be a JavaScript file: . */ var constants = {}; constants.side = { R: 1, L: 2, B: 3 }; // #region State List constants.states = [ { name: "Alaska", code: "AK" }, { name: "Alabama", code: "AL" }, { name: "Arkansas", code: "AR" }, { name: "Arizona", code: "AZ" }, { name: "California", code: "CA" }, { name: "Colorado", code: "CO" }, { name: "Connecticut", code: "CT" }, { name: "District of Columbia", code: "DC" }, { name: "Delaware", code: "DE" }, { name: "Florida", code: "FL" }, { name: "Georgia", code: "GA" }, { name: "Hawaii", code: "HI" }, { name: "Iowa", code: "IA" }, { name: "Idaho", code: "ID" }, { name: "Illinois", code: "IL" }, { name: "Indiana", code: "IN" }, { name: "Kansas", code: "KS" }, { name: "Kentucky", code: "KY" }, { name: "Louisiana", code: "LA" }, { name: "Massachusetts", code: "MA" }, { name: "Maryland", code: "MD" }, { name: "Maine", code: "ME" }, { name: "Michigan", code: "MI" }, { name: "Minnesota", code: "MN" }, { name: "Missouri", code: "MO" }, { name: "Mississippi", code: "MS" }, { name: "Montana", code: "MT" }, { name: "North Carolina", code: "NC" }, { name: "North Dakota", code: "ND" }, { name: "Nebraska", code: "NE" }, { name: "New Hampshire", code: "NH" }, { name: "New Jersey", code: "NJ" }, { name: "New Mexico", code: "NM" }, { name: "Nevada", code: "NV" }, { name: "New York", code: "NY" }, { name: "Ohio", code: "OH" }, { name: "Oklahoma", code: "OK" }, { name: "Oregon", code: "OR" }, { name: "Pennsylvania", code: "PA" }, { name: "Rhode Island", code: "RI" }, { name: "South Carolina", code: "SC" }, { name: "South Dakota", code: "SD" }, { name: "Tennessee", code: "TN" }, { name: "Texas", code: "TX" }, { name: "Utah", code: "UT" }, { name: "Virginia", code: "VA" }, { name: "Vermont", code: "VT" }, { name: "Washington", code: "WA" }, { name: "Wisconsin", code: "WI" }, { name: "West Virginia", code: "WV" }, { name: "Wyoming", code: "WY" } ]; // #endregion // #region Country List constants.countries = [ { name: "Afghanistan", code: "AF" }, { name: "Åland Islands", code: "AX" }, { name: "Albania", code: "AL" }, { name: "Algeria", code: "DZ" }, { name: "American Samoa", code: "AS" }, { name: "Andorra", code: "AD" }, { name: "Angola", code: "AO" }, { name: "Anguilla", code: "AI" }, { name: "Antarctica", code: "AQ" }, { name: "Antigua and Barbuda", code: "AG" }, { name: "Argentina", code: "AR" }, { name: "Armenia", code: "AM" }, { name: "Aruba", code: "AW" }, { name: "Australia", code: "AU" }, { name: "Austria", code: "AT" }, { name: "Azerbaijan", code: "AZ" }, { name: "Bahamas", code: "BS" }, { name: "Bahrain", code: "BH" }, { name: "Bangladesh", code: "BD" }, { name: "Barbados", code: "BB" }, { name: "Belarus", code: "BY" }, { name: "Belgium", code: "BE" }, { name: "Belize", code: "BZ" }, { name: "Benin", code: "BJ" }, { name: "Bermuda", code: "BM" }, { name: "Bhutan", code: "BT" }, { name: "Bolivia (Plurinational State of)", code: "BO" }, { name: "Bonaire, Sint Eustatius and Saba", code: "BQ" }, { name: "Bosnia and Herzegovina", code: "BA" }, { name: "Botswana", code: "BW" }, { name: "Bouvet Island", code: "BV" }, { name: "Brazil", code: "BR" }, { name: "British Indian Ocean Territory", code: "IO" }, { name: "Brunei Darussalam", code: "BN" }, { name: "Bulgaria", code: "BG" }, { name: "Burkina Faso", code: "BF" }, { name: "Burundi", code: "BI" }, { name: "Cambodia", code: "KH" }, { name: "Cameroon", code: "CM" }, { name: "Canada", code: "CA" }, { name: "Cabo Verde", code: "CV" }, { name: "Cayman Islands", code: "KY" }, { name: "Central African Republic", code: "CF" }, { name: "Chad", code: "TD" }, { name: "Chile", code: "CL" }, { name: "China", code: "CN" }, { name: "Christmas Island", code: "CX" }, { name: "Cocos (Keeling) Islands", code: "CC" }, { name: "Colombia", code: "CO" }, { name: "Comoros", code: "KM" }, { name: "Congo", code: "CG" }, { name: "Congo (Democratic Republic of the)", code: "CD" }, { name: "Cook Islands", code: "CK" }, { name: "Costa Rica", code: "CR" }, { name: "Côte d'Ivoire", code: "CI" }, { name: "Croatia", code: "HR" }, { name: "Cuba", code: "CU" }, { name: "Curaçao", code: "CW" }, { name: "Cyprus", code: "CY" }, { name: "Czech Republic", code: "CZ" }, { name: "Denmark", code: "DK" }, { name: "Djibouti", code: "DJ" }, { name: "Dominica", code: "DM" }, { name: "Dominican Republic", code: "DO" }, { name: "Ecuador", code: "EC" }, { name: "Egypt", code: "EG" }, { name: "El Salvador", code: "SV" }, { name: "Equatorial Guinea", code: "GQ" }, { name: "Eritrea", code: "ER" }, { name: "Estonia", code: "EE" }, { name: "Ethiopia", code: "ET" }, { name: "Falkland Islands (Malvinas)", code: "FK" }, { name: "Faroe Islands", code: "FO" }, { name: "Fiji", code: "FJ" }, { name: "Finland", code: "FI" }, { name: "France", code: "FR" }, { name: "French Guiana", code: "GF" }, { name: "French Polynesia", code: "PF" }, { name: "French Southern Territories", code: "TF" }, { name: "Gabon", code: "GA" }, { name: "Gambia", code: "GM" }, { name: "Georgia", code: "GE" }, { name: "Germany", code: "DE" }, { name: "Ghana", code: "GH" }, { name: "Gibraltar", code: "GI" }, { name: "Greece", code: "GR" }, { name: "Greenland", code: "GL" }, { name: "Grenada", code: "GD" }, { name: "Guadeloupe", code: "GP" }, { name: "Guam", code: "GU" }, { name: "Guatemala", code: "GT" }, { name: "Guernsey", code: "GG" }, { name: "Guinea", code: "GN" }, { name: "Guinea-Bissau", code: "GW" }, { name: "Guyana", code: "GY" }, { name: "Haiti", code: "HT" }, { name: "Heard Island and McDonald Islands", code: "HM" }, { name: "Holy See", code: "VA" }, { name: "Honduras", code: "HN" }, { name: "Hong Kong", code: "HK" }, { name: "Hungary", code: "HU" }, { name: "Iceland", code: "IS" }, { name: "India", code: "IN" }, { name: "Indonesia", code: "ID" }, { name: "Iran (Islamic Republic of)", code: "IR" }, { name: "Iraq", code: "IQ" }, { name: "Ireland", code: "IE" }, { name: "Isle of Man", code: "IM" }, { name: "Israel", code: "IL" }, { name: "Italy", code: "IT" }, { name: "Jamaica", code: "JM" }, { name: "Japan", code: "JP" }, { name: "Jersey", code: "JE" }, { name: "Jordan", code: "JO" }, { name: "Kazakhstan", code: "KZ" }, { name: "Kenya", code: "KE" }, { name: "Kiribati", code: "KI" }, { name: "Korea (Democratic People's Republic of)", code: "KP" }, { name: "Korea (Republic of)", code: "KR" }, { name: "Kuwait", code: "KW" }, { name: "Kyrgyzstan", code: "KG" }, { name: "Lao People's Democratic Republic", code: "LA" }, { name: "Latvia", code: "LV" }, { name: "Lebanon", code: "LB" }, { name: "Lesotho", code: "LS" }, { name: "Liberia", code: "LR" }, { name: "Libya", code: "LY" }, { name: "Liechtenstein", code: "LI" }, { name: "Lithuania", code: "LT" }, { name: "Luxembourg", code: "LU" }, { name: "Macao", code: "MO" }, { name: "Macedonia (the former Yugoslav Republic of)", code: "MK" }, { name: "Madagascar", code: "MG" }, { name: "Malawi", code: "MW" }, { name: "Malaysia", code: "MY" }, { name: "Maldives", code: "MV" }, { name: "Mali", code: "ML" }, { name: "Malta", code: "MT" }, { name: "Marshall Islands", code: "MH" }, { name: "Martinique", code: "MQ" }, { name: "Mauritania", code: "MR" }, { name: "Mauritius", code: "MU" }, { name: "Mayotte", code: "YT" }, { name: "Mexico", code: "MX" }, { name: "Micronesia (Federated States of)", code: "FM" }, { name: "Moldova (Republic of)", code: "MD" }, { name: "Monaco", code: "MC" }, { name: "Mongolia", code: "MN" }, { name: "Montenegro", code: "ME" }, { name: "Montserrat", code: "MS" }, { name: "Morocco", code: "MA" }, { name: "Mozambique", code: "MZ" }, { name: "Myanmar", code: "MM" }, { name: "Namibia", code: "NA" }, { name: "Nauru", code: "NR" }, { name: "Nepal", code: "NP" }, { name: "Netherlands", code: "NL" }, { name: "New Caledonia", code: "NC" }, { name: "New Zealand", code: "NZ" }, { name: "Nicaragua", code: "NI" }, { name: "Niger", code: "NE" }, { name: "Nigeria", code: "NG" }, { name: "Niue", code: "NU" }, { name: "Norfolk Island", code: "NF" }, { name: "Northern Mariana Islands", code: "MP" }, { name: "Norway", code: "NO" }, { name: "Oman", code: "OM" }, { name: "Pakistan", code: "PK" }, { name: "Palau", code: "PW" }, { name: "Palestine, State of", code: "PS" }, { name: "Panama", code: "PA" }, { name: "Papua New Guinea", code: "PG" }, { name: "Paraguay", code: "PY" }, { name: "Peru", code: "PE" }, { name: "Philippines", code: "PH" }, { name: "Pitcairn", code: "PN" }, { name: "Poland", code: "PL" }, { name: "Portugal", code: "PT" }, { name: "Puerto Rico", code: "PR" }, { name: "Qatar", code: "QA" }, { name: "Réunion", code: "RE" }, { name: "Romania", code: "RO" }, { name: "Russian Federation", code: "RU" }, { name: "Rwanda", code: "RW" }, { name: "Saint Barthélemy", code: "BL" }, { name: "Saint Helena, Ascension and Tristan da Cunha", code: "SH" }, { name: "Saint Kitts and Nevis", code: "KN" }, { name: "Saint Lucia", code: "LC" }, { name: "Saint Martin (French part)", code: "MF" }, { name: "Saint Pierre and Miquelon", code: "PM" }, { name: "Saint Vincent and the Grenadines", code: "VC" }, { name: "Samoa", code: "WS" }, { name: "San Marino", code: "SM" }, { name: "Sao Tome and Principe", code: "ST" }, { name: "Saudi Arabia", code: "SA" }, { name: "Senegal", code: "SN" }, { name: "Serbia", code: "RS" }, { name: "Seychelles", code: "SC" }, { name: "Sierra Leone", code: "SL" }, { name: "Singapore", code: "SG" }, { name: "Sint Maarten (Dutch part)", code: "SX" }, { name: "Slovakia", code: "SK" }, { name: "Slovenia", code: "SI" }, { name: "Solomon Islands", code: "SB" }, { name: "Somalia", code: "SO" }, { name: "South Africa", code: "ZA" }, { name: "South Georgia and the South Sandwich Islands", code: "GS" }, { name: "South Sudan", code: "SS" }, { name: "Spain", code: "ES" }, { name: "Sri Lanka", code: "LK" }, { name: "Sudan", code: "SD" }, { name: "Suriname", code: "SR" }, { name: "Svalbard and Jan Mayen", code: "SJ" }, { name: "Swaziland", code: "SZ" }, { name: "Sweden", code: "SE" }, { name: "Switzerland", code: "CH" }, { name: "Syrian Arab Republic", code: "SY" }, { name: "Taiwan, Province of China", code: "TW" }, { name: "Tajikistan", code: "TJ" }, { name: "Tanzania, United Republic of", code: "TZ" }, { name: "Thailand", code: "TH" }, { name: "Timor-Leste", code: "TL" }, { name: "Togo", code: "TG" }, { name: "Tokelau", code: "TK" }, { name: "Tonga", code: "TO" }, { name: "Trinidad and Tobago", code: "TT" }, { name: "Tunisia", code: "TN" }, { name: "Turkey", code: "TR" }, { name: "Turkmenistan", code: "TM" }, { name: "Turks and Caicos Islands", code: "TC" }, { name: "Tuvalu", code: "TV" }, { name: "Uganda", code: "UG" }, { name: "Ukraine", code: "UA" }, { name: "United Arab Emirates", code: "AE" }, { name: "United Kingdom of Great Britain and Northern Ireland", code: "GB", altCode: "UK" }, { name: "United States of America", code: "US" }, { name: "United States Minor Outlying Islands", code: "UM" }, { name: "Uruguay", code: "UY" }, { name: "Uzbekistan", code: "UZ" }, { name: "Vanuatu", code: "VU" }, { name: "Venezuela (Bolivarian Republic of)", code: "VE" }, { name: "Viet Nam", code: "VN" }, { name: "Virgin Islands (British)", code: "VG" }, { name: "Virgin Islands (U.S.)", code: "VI" }, { name: "Wallis and Futuna", code: "WF" }, { name: "Western Sahara", code: "EH" }, { name: "Yemen", code: "YE" }, { name: "Zambia", code: "ZM" }, { name: "Zimbabwe", code: "ZW" } ]; // #endregion // #region ServiceTypes constants.serviceTypes = [ { name: "Overnight, next day by 10:30", code: "14" }, { name: "Ground Shipment", code: "03" } ]; // #endregion // #region Product Options constants.productOptions = { CrosTxr: 510, EmCrosTxr: 528, SnapFitNoReceiver: 583, OriginalNoReceiver: 584, Parallel: 424, ParallelSoft: 509, RegSnapConnectYesEM: 651, HeavySnapConnectYesEM: 652, RegSnapConnectNoEM: 656, HeavySnapConnectNoEm: 657, EarplugConversionCord: 731, ManufacturerSelect: 782 }; constants.startHearing = { Name: 'Start Hearing' }; ; // ********************************************************************************* // Core shared functions // ********************************************************************************* var core = { timers: [], requests: [] }; ko = $.extend(function (value, subscriber) { var observable; if (value instanceof Service) { observable = ko.observableArray([]); observable._serviceUrl = value; } else if (value instanceof Array) { observable = ko.observableArray(value); } else if (value instanceof Function) { observable = ko.pureComputed(value); } else { observable = ko.observable(value); } if (subscriber instanceof Function) { observable.subscribe(subscriber); } else { observable.subscribe(function (v) { if (v && v.length > subscriber) observable(v.substring(0, subscriber)); }); } return observable; }, ko); ko.isObservableArray = function (obj) { return ko.isObservable(obj) && !(obj.destroyAll === undefined); }; ko.toCS = function (target) { var input = ko.utils.unwrapObservable(target); if (typeof input == "function") return input; if (input instanceof Array) { var result = []; for (var i = 0; i < input.length; i++) result.push(ko.toCS(input[i])); return result } else if (input instanceof Object) { var result = {}; Object.keys(input).forEach(function (key) { result[key.charAt(0).toUpperCase() + key.slice(1)] = ko.toCS(input[key]); }); return result; } else return input; } core.ko = function (objectGraph, extend) { for (var field in objectGraph) { if (objectGraph[field] instanceof Service) { var serviceUrl = objectGraph[field]; objectGraph[field] = ko.observableArray([]); objectGraph[field]._serviceUrl = serviceUrl; } else if (objectGraph[field] instanceof Function) { continue; } else if (objectGraph[field] instanceof Array) { objectGraph[field] = ko.observableArray(objectGraph[field]); } else if (objectGraph[field] instanceof Object) { objectGraph[field] = core.ko(objectGraph[field]); } else { objectGraph[field] = ko.observable(objectGraph[field]); } } if (extend) return $.extend(extend, objectGraph); return objectGraph; }; core.onUnauthorized = function (status, message) { alert("Sorry, an error has occured.\nPlease contact technical support."); }; core.onError = function (status, message) { alert("Sorry, an error has occured.\nPlease contact technical support."); }; core.get = function (url, queries, onSuccess, onError, isFromConfirmationPage = false, synchronous) { if (queries instanceof Array) { url = (new Service([url].concat(queries)) || { url: url }).url; } else if (queries) { return core.get(url, null, queries, onSuccess, isFromConfirmationPage); } if (!url) { if (onSuccess) onSuccess(); return; } if (url.contains("?") && (url.indexOf("/services/?") == -1 && url.indexOf("ProxyGet?") == -1) || url.split("?").length > 2) { url += "&_=" + new Date().getTime(); } else { url += "?_=" + new Date().getTime(); } if (url.contains(".js") && (url.indexOf("?") == -1 || url.indexOf(".js") < url.indexOf("?"))) { var element; element = document.createElement("script"); element.type = 'text/javascript'; element.src = url; element.onload = function () { if (onSuccess) onSuccess(); delete onSuccess; } element.onreadystatechange = function () { if (this.readyState == "loaded") { if (onSuccess) onSuccess(); delete onSuccess; } } document.body.appendChild(element); // document.getElementsByTagName("head")[0].appendChild(element); } else { var request = $.ajax({ url: url, async: !synchronous, headers: { "Authorization": "bearer " + session.InsiteToken, "X-Timezone-Minute-Offset": -(new Date()).getTimezoneOffset(), "X-Anti-Forgery-Token": core.getCookie("X-Anti-Forgery-Token") }, processdata: false, error: function (request, status, error) { core.requests.splice(core.requests.indexOf(request), 1); if (onError) onError(); // if (core.onError) core.onError(); }, success: function (data, status, request) { core.requests.splice(core.requests.indexOf(request), 1); core.doCallback(url, data, onSuccess, onError, isFromConfirmationPage); } }); core.requests.push(request); } }; core.post = function (url, postData, onSuccess, onError, synchronous, isFromConfirmationPage = false) { var request = $.ajax({ type: "POST", url: url, async: !synchronous, data: JSON.stringify(postData), headers: { "Authorization": "bearer " + session.InsiteToken, "X-Timezone-Minute-Offset": -(new Date()).getTimezoneOffset(), "X-Anti-Forgery-Token": core.getCookie("X-Anti-Forgery-Token") }, contentType: "application/json", error: function (request, status, error) { core.requests.splice(core.requests.indexOf(request), 1); if (onError) onError(); }, success: function (data, status, request) { core.requests.splice(core.requests.indexOf(request), 1); core.doCallback("", data, onSuccess, onError, isFromConfirmationPage); } }); core.requests.push(request); } core.put = function (url, postData, onSuccess, onError, synchronous, isFromConfirmationPage = false) { var request = $.ajax({ type: "PUT", url: url, async: !synchronous, data: JSON.stringify(postData), headers: { "Authorization": "bearer " + session.InsiteToken, "X-Timezone-Minute-Offset": -(new Date()).getTimezoneOffset(), "X-Anti-Forgery-Token": core.getCookie("X-Anti-Forgery-Token") }, contentType: "application/json", error: function (request, status, error) { core.requests.splice(core.requests.indexOf(request), 1); if (onError) onError(); }, success: function (data, status, request) { core.requests.splice(core.requests.indexOf(request), 1); core.doCallback("", data, onSuccess, onError, isFromConfirmationPage); site.updateCartCount(); } }); core.requests.push(request); } core.delete = function (url, postData, onSuccess, onError, synchronous, isFromConfirmationPage = false) { var request = $.ajax({ type: "DELETE", url: url, async: !synchronous, data: JSON.stringify(postData), headers: { "Authorization": "bearer " + session.InsiteToken, "X-Timezone-Minute-Offset": -(new Date()).getTimezoneOffset(), "X-Anti-Forgery-Token": core.getCookie("X-Anti-Forgery-Token") }, contentType: "application/json", error: function (request, status, error) { core.requests.splice(core.requests.indexOf(request), 1); if (onError) onError(); }, success: function (data, status, request) { core.requests.splice(core.requests.indexOf(request), 1); core.doCallback("", data, onSuccess, onError, isFromConfirmationPage); site.updateCartCount(); } }); core.requests.push(request); } core.patch = function (url, postData, onSuccess, onError, synchronous, isFromConfirmationPage = false) { var request = $.ajax({ type: "PATCH", url: url, async: !synchronous, data: JSON.stringify(postData), headers: { "Authorization": "bearer " + session.insiteToken, "X-Timezone-Minute-Offset": -(new Date()).getTimezoneOffset(), "X-Anti-Forgery-Token": core.getCookie("X-Anti-Forgery-Token") }, contentType: "application/json", error: function (request, status, error) { core.requests.splice(core.requests.indexOf(request), 1); if (onError) onError(); }, success: function (data, status, request) { core.requests.splice(core.requests.indexOf(request), 1); core.doCallback("", data, onSuccess, onError, isFromConfirmationPage); } }); core.requests.push(request); } core.doCallback = function (url, data, onSuccess, onError, isFromConfirmationPage = false) { if (data && (data.response || data.Response)) { if (data.response && data.response == 200) { if (onSuccess) onSuccess(data.body); } else if (data.Response && data.Response == 200) { if (onSuccess) onSuccess(data.Body); } else if (isFromConfirmationPage) { core.onConfirmationError(); } else if (data.response && data.response == 403) { if (core.onUnauthorized) core.onUnauthorized(data.response, data.message); } else if (data.Response && data.Response == 403) { if (core.onUnauthorized) core.onUnauthorized(data.Response, data.Message); } else if (data.Message) { if (onError) onError(data.Response, data.Message); if (core.onError) core.onError(data.Response, data.Message); } else if (data.message) { if (onError) onError(data.response, data.message); if (core.onError) core.onError(data.response, data.message); } else { if (core.onError) core.onError(); } } else { //Parse the response to JSON when returned as string due to x-content-type-options header set to nosniff if (typeof data === 'string' && data.startsWith('{"Body')) { data = JSON.parse(data).Body; } if (typeof data === 'string' && data.startsWith('{"id')) { data = JSON.parse(data); } if (url.contains(".txt")) data = core.simpleJson(data); if (url.contains(".csv")) data = core.parseCsv(data); if (onSuccess) onSuccess(data); } } core.abortRequests = function () { for (var i = 0; i < core.requests.length; i++) { core.requests[i].abort(); } core.requests = []; } core.getMap = function (map, callback) { var iteration = 1; if (map.length) { $(map).each(function () { var resource = this; if (resource instanceof Array && resource.length == 2) { core.get("" + resource[1], function (data) { resource[0](data); if (iteration++ == map.length) callback(); }); } else { core.get("" + resource, function () { if (iteration++ == map.length) callback(); }); } }); } else { callback(); } } core.load = function () { // Arguments: map, ..., callback var callback; if (arguments.length == 2) { callback = arguments[1]; } else { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } callback = function () { core.load.apply({}, args); } } if (arguments[0] instanceof String) { core.get(arguments[0], callback); } else if (arguments[0] instanceof Array) { core.getMap(arguments[0], callback); } } core.cleanHead = function () { $("script").each(function () { if (!this.id || this.id.indexOf("#") == -1) $(this).remove(); }); } core.template = function (id, html) { var element = document.getElementById(id); if (element) $(element).remove(); var template = document.createElement("script"); template.id = id; template.type = "text/html"; template.text = html; document.body.appendChild(template); } core.download = function (url, data) { var ie10orEdge = navigator.appVersion.indexOf("MSIE 10") != -1 || navigator.appVersion.indexOf("Edge") != -1; var target = ie10orEdge ? "_self" : "_blank"; console.log('core.download ulr: ' + url); console.log('core.download data: ' + JSON.stringify(data)); var bodyMod = $('
' .format(target, url, encodeURIComponent(JSON.stringify(data)))) .appendTo('body'); bodyMod.submit().remove(); console.log('core.download bodyMod: ' + JSON.stringify(bodyMod)); }; core.query = function (name, defaultValue) { var match = RegExp("[?&]" + name + "=([^&]*)").exec(window.location.href); var value = match && decodeURIComponent(match[1].replace(/\+/g, " ")); return (value == null) ? defaultValue : value; }; core.getSessionStorageItem = function (key, removeItem) { var item = sessionStorage.getItem(key); if (removeItem) { sessionStorage.removeItem(key); } return item; }; core.showWarrantyPdf = function (warrantyUrl) { var xhr = new XMLHttpRequest(); xhr.open("GET", warrantyUrl); xhr.responseType = "arraybuffer"; var url = ""; xhr.onload = function () { var blob = new Blob([xhr.response], { type: 'application/pdf' }); if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob); } else { url = URL.createObjectURL(blob); window.open(url); } } xhr.send(); if (window.document.documentMode == undefined || window.document.documentMode == null) { URL.revokeObjectURL(url); } }; core.IsNewNavigationEnabled = function () { return session.Features.any(function (i) { return (i.FeatureName === "CX 2019"); }); }; core.setAudiogramDefaults = function (audiogram, val500, val1k, val2k, val4k) { if (audiogram.left) { audiogram.left.air()[1].response(val500); audiogram.left.air()[3].response(val1k); audiogram.left.air()[5].response(val2k); audiogram.left.air()[7].response(val4k); } if (audiogram.right) { audiogram.right.air()[1].response(val500); audiogram.right.air()[3].response(val1k); audiogram.right.air()[5].response(val2k); audiogram.right.air()[7].response(val4k); } }; // #region Cookies core.setCookie = function (name, value, days) { var expiration = days instanceof Date ? days : new Date(); if (days && !(days instanceof Date)) expiration.setDate(expiration.getDate() + days); document.cookie = "{0}={1}{2}; path=/".format( name, escape(value), days ? "; expires=" + expiration.toUTCString() : ""); }; core.getCookie = function (name, defaultValue) { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var keyValue = cookies[i].split("="); if (name == keyValue[0].replace(/^\s+|\s+$/g, "")) { return unescape(keyValue[1]); } }; return defaultValue; }; core.removeCookie = function (name) { if (name) core.setCookie(name, "", -1); }; // #endregion core.isValidEmailFormat = function (email) { if (email == undefined) { return false; } var isValid = false; if (email) { var re = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/; isValid = re.test(email); } return isValid; }; core.isInvalidDate = function (date) { if (!(date instanceof Date)) date = new Date(date); return isNaN(date.getTime()); }; core.date = function (dateString, country) { if (!dateString) return ""; var format = "{0}/{1}/{2}"; if (country && !["US", "CA"].contains(country)) format = "{1}/{0}/{2}"; var date = typeof (dateString) === "object" ? dateString : core.dateParse(dateString); if (!date || date.getFullYear() == 1 || isNaN(date.getTime())) return ""; return format.format(date.getMonth() + 1, date.getDate(), date.getFullYear()); }; core.getDateFormat = function (country) { if (["US", "CA"].contains(country)) return "mm/dd/yy"; return "dd/mm/yy"; }; core.dateParse = function (dateString) { var parsed = /\/Date\(([0-9]*)([+-][0-9]*)?\)\//.exec(dateString); if (!parsed) return null; var result = new Date(parseInt(parsed[1])); if (isNaN(result.getTime())) return null; if (parsed[2]) { var offset = parseInt(parsed[2]); result.setMinutes(result.getMinutes() + result.getTimezoneOffset() + (offset % 100) + ((Math.floor(offset / 100)) * 60)); } return result; }; core.parseFormattedDate = function (dateString, formatString, delimiter) { delimiter = delimiter || "/"; var splitFormat = formatString.split(delimiter); var splitDate = dateString.split(delimiter); var year = parseInt(splitDate[splitFormat.indexOf("yy")]); var month = parseInt(splitDate[splitFormat.indexOf("mm")]); var day = parseInt(splitDate[splitFormat.indexOf("dd")]); return new Date(year, month - 1, day); }; core.isIOS = function () { return navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/); } core.jumpToAnchor = function (anchor) { window.location = String(window.location).replace(/\#.*$/, "") + "#" + anchor; } core.scrollIntoView = function (element, callback) { if (typeof (element) == "string") element = $("#" + element); $("body, html").animate( { scrollTop: element.offset()["top"] - ($(window).height() / 3) }, { duration: "slow", easing: "swing", complete: callback } ); } core.addWatermark = function (field, id, functionName, placeholder, vm) { if (!field()) field(placeholder); if (!vm) vm = window.vm; vm[functionName] = ko.computed(function () { return field() == placeholder; }); $("#" + id).focus(function () { if (field() == placeholder) field(null); }); $("#" + id).blur(function () { if (!field()) field(placeholder); }); }; core.tabToNextField = function (event) { var inputs = $(':input'); var nextInput = inputs.get(inputs.index(event.target) + 1); if (nextInput) nextInput.focus(); }; core.alert = function (obj) { alert(JSON.stringify(obj)); }; core.onEnterKey = function (func) { return function (data, event) { if (event.keyCode == 13) { if (event.srcElement) { func(event.srcElement.value); } else { func(event.target.value); } } return true; }; }; core.phoneKeyDown = function (data, event) { return event.keyCode == 189 || event.keyCode == 109 || event.keyCode == 88 || event.keyCode < 48 || event.keyCode == 120 || (event.keyCode >= 112 && event.keyCode <= 123) || (event.keyCode > 48 && event.keyCode < 57 && !event.shiftKey) || event.keyCode == 48 || event.keyCode == 57 || (event.keyCode >= 96 && event.keyCode <= 105) || (event.keyCode == 187 && event.shiftKey); }; core.isArray = function (value) { return value instanceof Array; }; core.makeArray = function (value) { return (core.isArray(value)) ? value : [value]; }; core.setTimeout = function (code, interval) { core.timers.push(window.setTimeout(code, interval)); } core.clearTimeouts = function () { for (var i = 0; i < core.timers.length; i++) { clearTimeout(core.timers[i]); } core.timers = []; } if (typeof (console) == "undefined") { console = { log: function (message) { } }; } core.simpleJson = function (simpleJson) { return core.expandJson(core.parseSimpleJson(simpleJson)); } core.parseSimpleJson = function (simpleJson) { if (!simpleJson) return null; var parents = [{}]; var lines = simpleJson.split('\n'); for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (!line.trim()) continue; var depth = 0; for (var c = 0; c < line.length; c++) { if (line[c] == '\t') depth++; else break; } var keyValue = line.substring(depth).split(':'); var key = keyValue[0].trim(); parents[depth][key] = keyValue.length > 1 ? keyValue[1].trim() : {}; parents[depth + 1] = parents[depth][key]; } return parents[0]; }; core.parseCsv = function (csv) { var lines = csv.split("\r\n"); var data = []; lines.forEach(function (item) { if (!item) return; data.push([]); var fields = item.replace(/""/g, "\"").replace(/�/g, " ").split(","); for (var i = 0; i < fields.length; i++) { var value = fields[i]; if (value.startsWith("\"")) { value = ""; for (; !fields[i].endsWith("\""); i++) { if (value) value += ","; value += fields[i]; } if (value) value += ","; value += fields[i]; value = value.substring(1, value.length - 1); } data[data.length - 1].push(value); } }); return data; } core.expandJson = function (json) { if (!json) return null; var object = {}; var items = []; for (var property in json) { var value = json[property]; if (typeof (value) == "object" && core.isObjectEmpty(value)) { items.push(property); } else if (typeof (value) != "string") { value = core.expandJson(value); items.push({ name: property, value: value }); } else { object[property] = value; } } if (core.isObjectEmpty(object)) return items; if (items.length) object.items = items; return object; }; core.isObjectEmpty = function (o) { for (var property in o) { if (o.hasOwnProperty(property)) { return false; } } return true; }; core.getContextualCallback = function (thisContext, callbackFunction) { return function () { var args = (arguments.length === 1 ? core.makeArray(arguments[0]) : Array.apply(null, arguments)); return callbackFunction.apply(thisContext, args); }; }; // #region Service class var Service = function () { // Arguments: formatUrl, arg1, ..., argn var args = (arguments.length === 1 ? core.makeArray(arguments[0]) : Array.apply(null, arguments)); if (args.length > 0) { this.url = args.shift(); if (args.length > 0) { var qIndex = this.url.indexOf("?"); this.url = this.url.replace(/{(\d+)}/g, function (match, number, position) { if (args[number] == undefined) return ''; return qIndex != -1 && qIndex < position ? encodeURIComponent(args[number]) : args[number]; }); } } }; // #endregion // #region Url class // Because IE 11 doesn't support native URL class function Url(url) { this.original = url; var regString = ""; if (url.indexOf("/") != -1) { if (url.indexOf("://") != -1) { regString += "(.+:\/\/)"; this.protocol = ""; } if ((regString ? url.substring(url.indexOf("://") + 3) : url).indexOf("/") > 1) { regString += "([^\/]+)"; this.base = ""; } regString += "([^\?]*)"; this.path = ""; if (url.indexOf("?") != -1) { regString += "[?]([^=]+=?.*)"; this.query = {}; } if (url.indexOf("#") > url.lastIndexOf("?")) { regString += "([#].*)"; this.hash = ""; } } var matches = (new RegExp(regString)).exec(url); var ndx = 1; if (typeof this.protocol !== 'undefined') this.protocol = matches[ndx++]; if (typeof this.base !== 'undefined') this.base = matches[ndx++]; if (typeof this.path !== 'undefined') { this.path = matches[ndx++]; var file = this.path.substring(this.path.lastIndexOf("/") + 1).match(/(.*)[\.]([A-Za-z0-9]+$)/); if (file) { this.filename = file[1]; this.extension = file[2]; } } if (typeof this.query !== 'undefined') { var urlQuery = matches[ndx++]; this.search = "?" + urlQuery; if (urlQuery.indexOf("=") != -1) { var result = {}; urlQuery.split("&").forEach(function (query) { var queryMatches = query.match(/([^=]+)=(.*)/); if (queryMatches != null) result[queryMatches[1]] = queryMatches[2]; }); this.query = result; } else { this.query = urlQuery; } } if (typeof this.hash !== 'undefined') this.hash = matches[ndx++]; }; // #endregion // ********************************************************************************* // String & Array prototype helpers // ********************************************************************************* String.prototype.contains = function (value) { return this.indexOf(value) != -1; }; String.prototype.startsWith = function (value) { return this.indexOf(value) == 0; }; String.prototype.endsWith = function (suffix) { return this.indexOf(suffix, this.length - suffix.length) != -1; }; String.prototype.format = function () { var args = arguments; return this.replace(/{(\d+)}/g, function (match, number) { return (args[number] != undefined ? args[number] : ''); }); }; String.prototype.toTitleCase = function () { return this.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); }; String.prototype.replaceAll = function (search, replace) { if (search instanceof Array) { if (search.length < 1) return this; if (search.length == 1) return this.replaceAll(search[0][0], search[0][1]); else return this.replaceAll([search.shift()]).replaceAll(search); } return this.split(search).join(replace); }; if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; } String.prototype.padLeft = function (pad, length) { var str = this; while (str.length < length) str = pad + str; return str; }; Number.prototype.currency = function () { return "$" + this.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"); }; if (!Array.prototype.forEach) { Array.prototype.forEach = function (func) { for (var i = 0; i < this.length; i++) func.call(this[i], this[i]); }; } if (!Array.prototype.select) { Array.prototype.select = function (func) { var list = []; for (var i = 0; i < this.length; i++) list.push(func.call(this[i], this[i])); return list; }; } if (!Array.prototype.orderBy) { Array.prototype.orderBy = function (field, descending, nullHigh) { if (!field) return this; var reverse = descending ? -1 : 1; return this.sort(function (a, b) { var koA = ko.unwrap(a[field]), koB = ko.unwrap(b[field]); if (nullHigh && koA != koB && [koA, koB].contains(null)) { if (koA < koB) return reverse; if (koA > koB) return -1 * reverse; } if (koA < koB) return -1 * reverse; if (koA > koB) return reverse; return 0; }); }; } Array.prototype.dedupe = function () { var prims = { "boolean": {}, "number": {}, "string": {} }, objs = []; return this.filter(function (item) { var type = typeof item; if (type in prims) return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true); else return objs.indexOf(item) >= 0 ? false : objs.push(item); }); }; Array.prototype.intersect = function () { /* Arguments: list2, list3, list4 ... */ if (!arguments.length || !Array.isArray(arguments[0])) return []; var args = Array.prototype.slice.call(arguments); if (args.length == 1) { return this.list(function (each) { return args[0].contains(each); }); } var firstList = args.shift(); return Array.prototype.intersect.apply(firstList, args); }; Array.prototype.contains = function (value) { for (var i = 0; i < this.length; i++) if (this[i] == value) return true; return false; }; Array.prototype.caseInsensitiveContains = function (value) { for (var i = 0; i < this.length; i++) if (this[i] == value || (typeof (this[i]) == 'string' && typeof (value) == 'string' && this[i].toUpperCase() === value.toUpperCase())) return true; return false; }; Array.prototype.caseInsensitiveIntersect = function () { /* Arguments: list2, list3, list4 ... */ if (!arguments.length || !Array.isArray(arguments[0])) return []; var args = Array.prototype.slice.call(arguments); if (args.length == 1) { return this.list(function (each) { return args[0].caseInsensitiveContains(each); }); } var firstList = args.shift(); return Array.prototype.caseInsensitiveIntersect.apply(firstList, args); }; if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (value) { for (var i = 0; i < this.length; i++) if (this[i] == value) return i; return -1; }; } Array.prototype.list = function (func) { var list = []; for (var i = 0; i < this.length; i++) if (func.call(this[i], this[i])) list.push(this[i]); return list; }; Array.prototype.count = function (func) { var result = 0; for (var i = 0; i < this.length; i++) if (func.call(this[i], this[i])) result += 1; return result; }; Array.prototype.where = Array.prototype.list; Array.prototype.find = function (func) { for (var i = 0; i < this.length; i++) if (func.call(this[i], this[i])) return this[i]; return null; }; Array.prototype.any = function (func) { for (var i = 0; i < this.length; i++) if (func.call(this[i], this[i])) return true; return false; }; Array.prototype.all = function (func) { for (var i = 0; i < this.length; i++) if (!func.call(this[i], this[i])) return false; return true; }; Array.prototype.sum = function (func) { var sum = 0; for (var i = 0; i < this.length; i++) sum += func.call(this[i], this[i]); return sum; }; Array.prototype.average = function (func) { var sum = 0; for (var i = 0; i < this.length; i++) sum += func.call(this[i], this[i]); return sum / this.length; }; Array.prototype.remove = function (value) { value = core.makeArray(value); for (var v = 0; v < value.length; v++) { for (var i = this.length - 1; i >= 0; i--) { if (this[i] == value[v]) this.splice(i, 1); } } return this; }; Array.prototype.backwards = function () { var result = this.concat([]); result.reverse(); return result; }; ; (function () { ko.bindingHandlers.fadeVisible = { init: function (e, a) { $(e).toggle(ko.utils.unwrapObservable(a())); }, update: function (e, a) { ko.utils.unwrapObservable(a()) ? $(e).fadeIn() : $(e).fadeOut(); } }; ko.bindingHandlers.expanded = { init: function (e, a, b) { if (!b()['staticExpanded']) $(e).toggle(ko.utils.unwrapObservable(a())); }, update: function (e, a, b) { if (!!b()['staticExpanded']) { ko.utils.unwrapObservable(a()) ? $(e).show() : $(e).hide(); } else ko.utils.unwrapObservable(a()) ? $(e).slideDown() : $(e).slideUp(); } }; ko.bindingHandlers.invisible = { init: function (e, a) { $(e).css("visibility", ko.utils.unwrapObservable(a()) ? "hidden" : "visible"); }, update: function (e, a) { $(e).css("visibility", ko.utils.unwrapObservable(a()) ? "hidden" : "visible"); } }; ko.bindingHandlers.enterKey = { init: function (e, a) { ko.utils.registerEventHandler(e, "keydown", function (evt) { if (evt.keyCode == 13) { if (evt.srcElement) a()(evt.srcElement.value); else a()(evt.target.value); } }); } }; ko.bindingHandlers.id = { init: function (e, a) { $(e).attr("id", ko.utils.unwrapObservable(a())); }, update: function (e, a) { $(e).attr("id", ko.utils.unwrapObservable(a())); } }; ko.bindingHandlers.href = { init: function (e, a) { $(e).attr("href", ko.utils.unwrapObservable(a())); }, update: function (e, a) { $(e).attr("href", ko.utils.unwrapObservable(a())); } }; ko.bindingHandlers.labelPopover = { defaults: { target: '', icon: 'glyphicon glyphicon-info-sign', placement: 'bottom', trigger: 'click hover', template: '', html: false, container: false }, init: function (e, a, b) { var $e = $(e), val = a(); var opts = ko.bindingHandlers.labelPopover.defaults; if (val instanceof Object) { opts = $.extend(opts, val); } else if (typeof ko.utils.unwrapObservable(val) === 'string') { opts = $.extend(opts, { content: ko.utils.unwrapObservable(val), html: false }); } $e.append($(opts.target) .addClass(opts.icon) .addClass('label-popover') .popover({ container: ko.utils.unwrapObservable(opts.container), content: ko.utils.unwrapObservable(opts.content), html: ko.utils.unwrapObservable(opts.html), placement: ko.utils.unwrapObservable(opts.placement), template: ko.utils.unwrapObservable(opts.template), trigger: ko.utils.unwrapObservable(opts.trigger) })); } }; ko.bindingHandlers.dateTimePicker = { init: function (element, valueAccessor, allBindingsAccessor) { //initialize datepicker with some optional options var options = allBindingsAccessor().dateTimePickerOptions || {}; $(element).datetimepicker(options); //when a user changes the date, update the view model ko.utils.registerEventHandler(element, "dp.change", function (event) { var value = valueAccessor(); if (ko.isObservable(value)) { if (moment.isMoment(event.date)) { value(event.date.toDate()); } else { value(event.date); } } }); ko.utils.domNodeDisposal.addDisposeCallback(element, function () { var picker = $(element).data("DateTimePicker"); if (picker) { picker.destroy(); } }); }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var picker = $(element).data("DateTimePicker"); //when the view model is updated, update the widget if (picker) { var koDate = ko.utils.unwrapObservable(valueAccessor()); //in case return from server datetime i am get in this form for example /Date(93989393)/ then fomat this if (!koDate) koDate = null; else koDate = (typeof (koDate) !== 'object') ? new Date(parseFloat(koDate.replace(/[^0-9]/g, ''))) : koDate; picker.date(koDate); } } }; ko.bindingHandlers.popover = { defaults: { target: 'icon', icon: 'glyphicon glyphicon-info-sign', visible: 'true', 'data-placement': 'bottom', 'data-trigger': 'click hover' }, targets: { image: "", icon: "" }, init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var $element = $(element), value = valueAccessor(), defaults = ko.bindingHandlers.popover.defaults; $element.hide(); var $target; if ((value.target || defaults.target) == "image") { $target = $(ko.bindingHandlers.popover.targets.image); $element.before($target); } else if ((value.target || defaults.target) == "icon") { $target = $(ko.bindingHandlers.popover.targets.icon); $target.addClass(ko.unwrap(value.icon) || defaults.icon); $element.before($target); } else if (value.target.substring(0, 1) == "#") { $target = $(value.target); } else { throw new Error("You need to provide a valid target! ('image', 'icon' or an element id)"); } $target.addClass('knockoutBootsPopoverTarget'); $target.attr('data-toggle', 'popover'); ko.bindingHandlers.popover.applyKbBindings($element, $target, value, true); }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var $element = $(element), value = valueAccessor(), defaults = ko.bindingHandlers.popover.defaults; var $target = ((typeof value.target !== 'undefined' && value.target.substring(0, 1) == "#") ? $(value.target) : $element.prev('.knockoutBootsPopoverTarget')); ko.bindingHandlers.popover.applyKbBindings($element, $target, value, false); }, applyKbBindings: function ($element, $target, value, isInit) { var defaults = ko.bindingHandlers.popover.defaults if (typeof value.title !== 'undefined') { $target.attr('title', ko.unwrap(value.title)); } $target.attr({ 'data-placement': (ko.unwrap(value['data-placement']) || defaults['data-placement']), 'data-trigger': (ko.unwrap(value['data-trigger']) || defaults['data-trigger']) }); if (ko.unwrap(value.visible) || defaults.visible) { if ($target.hasClass('hiddenKBPT') || isInit) { $target.removeClass('hiddenKBPT'); if (ko.unwrap(value.container)) { $target.popover({ html: true, container: ko.unwrap(value.container), content: function () { return $element.html(); } }); } else { $target.popover({ html: true, content: function () { return $element.html(); } }); } } } else if (!$target.hasClass('hiddenKBPT') || isInit) { $target.addClass('hiddenKBPT'); $target.hide(); } } }; ko.bindingHandlers.numeric = { init: function (element, valueAccessor) { $(element).on("keydown", function (event) { // Allow: backspace, delete, tab, escape, and enter if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || // Allow: Ctrl+A (event.keyCode == 65 && event.ctrlKey === true) || // Allow: Ctrl+V (event.keyCode == 86 && event.ctrlKey === true) || // Allow: . , (event.keyCode == 188 || event.keyCode == 190 || event.keyCode == 110) || // Allow: home, end, left, right (event.keyCode >= 35 && event.keyCode <= 39)) { // let it happen, don't do anything return; } else { // Ensure that it is a number and stop the keypress if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault(); } } }); } }; ko.components.register('loadingBtn', { viewModel: function (params) { if (typeof params.id === 'undefined') throw new Error("You need to define the 'id' parameter to use the 'loadingBtn' component."); if (typeof params.click === 'undefined') throw new Error("You need to define the 'click' parameter to use the 'loadingBtn' component."); if (typeof params.loading === 'undefined') { params.loading = ko.observable(false); this.click = function () { params.loading(true); params.click.apply(this, arguments); }; } else { this.click = params.click; } this.text = ko.pureComputed(function () { return (ko.utils.unwrapObservable(params.loading) ? ko.utils.unwrapObservable(params.loadingText) : ko.utils.unwrapObservable(params.readyText)); }); this.icon = ko.pureComputed(function () { return (ko.utils.unwrapObservable(params.loading) || !ko.utils.unwrapObservable(params.icon) ? null : "fa fa-" + ko.utils.unwrapObservable(params.icon)); }); this.css = ko.pureComputed(function () { return (ko.utils.unwrapObservable(params.loading) ? ko.utils.unwrapObservable(params.loadingCss || "btn btn-primary") + " btn-loading" : ko.utils.unwrapObservable(params.readyCss || "btn btn-primary")); }); this.id = ko.pureComputed(function () { return ko.utils.unwrapObservable(params.id); }); }, template: '' }); ko.components.register('expandIcon', { viewModel: function (params) { if (!params.expandedIcon) params.expandedIcon = "fa fa-caret-down"; if (!params.collapsedIcon) params.collapsedIcon = "fa fa-caret-right"; this.icon = ko.pureComputed(function () { return (ko.utils.unwrapObservable(params.isExpanded) ? ko.utils.unwrapObservable(params.expandedIcon) : ko.utils.unwrapObservable(params.collapsedIcon)); }); }, template: '' }); ko.components.register('transferPatientAlert', { viewModel: function (params) { this.header = text("ATTENTION") + ":"; this.body = text("We have transferred patient data for {0}. The data will be cleared as soon as you log out.").format(site.transferPatientName()); this.buttonText = text("Clear Patient Data"); }, template: '
' }); ko.components.register('informationAlertBox', { viewModel: function (params) { this.visible = ko.pureComputed(function () { return ko.utils.unwrapObservable(params.visible); }); this.headerList = []; if (ko.utils.unwrapObservable(params.header) instanceof Array) { this.headerList = params.header; } else if (ko.utils.unwrapObservable(params.header) != null) { this.headerList = [params.header]; } this.body = params.body; }, template: '
' }); ko.components.register('htmlFlexAlert', { viewModel: function (params) { this.alertCss = params.alertCss || "alert alert-info"; this.headerHtml = params.headerHtml; this.useIconHeader = params.useIconHeader; this.headerIconHtml = params.headerIconHtml || ''; this.headerCss = params.headerCss || "alert-header"; this.headerText = params.headerText; this.bodyHtml = params.bodyHtml; this.bodyCss = params.bodyCss; this.bodyText = params.bodyText; }, template: '
' + '' + '
' + '
' + '
' + '
' + '' + '' + '
' + '' + '' + '
' + '' + '' + '
' + '' + '
' }); ko.components.register('modal', { viewModel: { createViewModel: function (params, componentInfo) { return new function () { this.title = params.title; this.hasBody = (!!componentInfo.templateNodes.length); this.body = (this.hasBody ? componentInfo.templateNodes : []); this.id = params.id; this.modalCss = params.css; this.cancelText = (params.cancel && params.cancel.text) ? params.cancel.text : text("Cancel"); this.cancelCss = params.cancel ? params.cancel.css : null; this.cancelClick = params.cancel ? params.cancel.click : null; this.cancelId = params.cancel ? params.cancel.id : null; this.confirmText = (params.confirm && params.confirm.text) ? params.confirm.text : text("OK"); this.confirmCss = params.confirm ? params.confirm.css : null; this.confirmClick = params.confirm ? params.confirm.click : null; this.confirmId = params.confirm ? params.confirm.id : null; }; } }, template: '' }); })();; var Audiogram = function (id, x0, y0, w, h, ranges, hideRequiredGridLines) { var ag = this; var canvas = document.getElementById(id); if (!canvas.getContext) G_vmlCanvasManager.initElement(canvas); var canvas2D = "2d"; ag.g = canvas.getContext(canvas2D); ag.range1 = null; ag.range2 = null; ag.range3 = null; ag.range4 = null; if (ranges) { if (ranges.length && ranges.length < 4) { var lastRange = ranges.pop(); while (ranges.length < 3) { ranges.push(null); } ranges.push(lastRange); } if (ranges.length > 0) ag.range1 = ranges[0]; if (ranges.length > 1) ag.range2 = ranges[1]; if (ranges.length > 2) ag.range3 = ranges[2]; if (ranges.length > 3) ag.range4 = ranges[3]; } ag.updateFitting = function (fitting) { ag.range1 = ag.range2 = ag.range3 = ag.range4 = null; if (fitting) { if (fitting.length && fitting.length < 4) { var lastRange = fitting.pop(); while (fitting.length < 3) { fitting.push(null); } fitting.push(lastRange); } if (fitting.length > 0) ag.range1 = fitting[0]; if (fitting.length > 1) ag.range2 = fitting[1]; if (fitting.length > 2) ag.range3 = fitting[2]; if (fitting.length > 3) ag.range4 = fitting[3]; } ag.draw(); }; ag.modes = ko([text("Input Right"), text("Input Binaural"), text("Input Left")]); ag.mode = ko(); ag.side = ko(null, function (side) { ag.draw(); if (side == "R") ag.mode(ag.modes()[0]); if (side == "B") ag.mode(ag.modes()[1]); if (side == "L") ag.mode(ag.modes()[2]); }); ag.update = function () { if (ag.autoCorrect(ag.right.air())) return; if (ag.autoCorrect(ag.right.bone())) return; if (ag.autoCorrect(ag.left.air())) return; if (ag.autoCorrect(ag.left.bone())) return; ag.roundResponse(ag.right.mcl); ag.roundResponse(ag.right.ucl); ag.roundResponse(ag.left.mcl); ag.roundResponse(ag.left.ucl); ag.roundResponse(ag.mcl); ag.roundResponse(ag.ucl); ag.draw(); if (vm) { if (vm.agL && vm.agL()) vm.agL().draw(); if (vm.queueMatrixRank) vm.queueMatrixRank(); } }; ag.autoCorrect = function (curve) { for (var i = 0; i < curve.length; i++) { var value = curve[i].response(); if (!!value) { if (ag.roundResponse(curve[i].response, value)) { return true; } } else if (curve[i].noResponse()) { curve[i].noResponse(false); return true; } } }; ag.roundResponse = function (observable, value) { if (!value) value = observable(); if (!value) return; var v = parseInt(value); if (isNaN(v)) v = 0; v = Math.round(v / 5) * 5; if (v < -10) v = -10; if (v > 130) v = 130; v = "" + v; if (value != v) { observable(v); return true; } }; ag.createCurve = function (isBone) { return [ { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 250, label: "250" }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 500, label: "500", required: !isBone }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 750, label: "750" }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 1000, label: "1k", required: !isBone }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 1500, label: "1.5k" }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 2000, label: "2k", required: !isBone }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 3000, label: "3k" }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 4000, label: "4k", required: !isBone }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 6000, label: "6k" }, { response: ko(null, ag.update), noResponse: ko(null, ag.update), frequency: 8000, label: "8k" }, ]; }; ag.right = { air: ko(ag.createCurve()), bone: ko(ag.createCurve(true)), mcl: ko(null, ag.update), ucl: ko(null, ag.update), loss: ko(null, ag.update) }; ag.left = { air: ko(ag.createCurve()), bone: ko(ag.createCurve(true)), mcl: ko(null, ag.update), ucl: ko(null, ag.update), loss: ko(null, ag.update) }; ag.mcl = ko(null, ag.update); ag.ucl = ko(null, ag.update); ag.loss = ko(null, ag.update); ag.draw = function (x, y) { ag.g.clearRect(0, 0, w * 9 + x0 + y0, h * 14 + y0 * 2); ag.g.fillStyle = "#aaa"; ag.g.fillRect(x0 + 1, y0 + 1, w * 9 - 1, h * 14 - 1); // fitting range(s) if (ag.range1) ag.drawRange("#777", ag.range1); if (ag.range2) ag.drawRange("#444", ag.range2); if (ag.range3) ag.drawRange("#000", ag.range3); if (ag.range4) ag.drawRange("#ddd", ag.range4); if (!hideRequiredGridLines) { // required values for (var i = 0; i < 4; i++) { ag.drawLine("#ffff00", 3, i * w * 2 + w + x0 + 0.5, y0 + 1, i * w * 2 + w + x0 + 0.5, 14 * h + y0); } } // grid lines for (var i = 0; i <= 14; i++) { ag.drawLine("#ffffff", 1, i * w + x0 + 0.5, y0 + 1, i * w + x0 + 0.5, 14 * h + y0); ag.drawLine("#ffffff", 1, x0, i * h + y0 + 0.5, 9 * w + x0 + 1, i * h + y0 + 0.5); } // response curves if (ag.side() != 'L') ag.drawCurve("#bb0000", "o", ag.right.air()); if (ag.side() != 'R') ag.drawCurve("#0000bb", "x", ag.left.air()); // crosshairs if (x && y) { x = Math.round((x - x0) / w) * w + x0; y = Math.round((y - y0) / (h / 2)) * (h / 2) + y0; if (x < x0) x = x0; if (y < y0) y = y0; if (x > (w * 9 + x0)) x = w * 9 + x0; if (y > (h * 14 + y0)) y = h * 14 + y0; var color = "#5e3885"; if (ag.mode() == text("Input Right")) var color = "#871a1a"; if (ag.mode() == text("Input Left")) var color = "#1a4d87"; ag.drawLine(color, 1, x + 0.5, 0, x + 0.5, h * 14 + y0 * 2); ag.drawLine(color, 1, 0, y + 0.5, w * 9 + x0 + y0, y + 0.5); } }; ag.drawRange = function (color, curve) { var i2, j2 = null; ag.g.fillStyle = color; ag.g.beginPath(); ag.g.moveTo(x0 + 1, h * 14 + y0); for (var i = 0; i < 10; i++) { var j = curve[i]; if (j == null && i == 9) j = j2; if (j != null && j !== "") { if (j2 == null) ag.g.lineTo(x0 + 0.5, (j / 10 + 1) * h + y0 + 0.5); ag.g.lineTo(i * w + x0 + 0.5, (j / 10 + 1) * h + y0 + 0.5); j2 = j; } } ag.g.lineTo(w * 9 + x0 + 1, h * 14 + y0); ag.g.closePath(); ag.g.fill(); } ag.drawCurve = function (color, symbol, curve) { var i2 = null, j2 = null; for (var i = 0; i < curve.length; i++) { var j = curve[i].response(); if (j != null && j !== "") { if (j2 != null && j !== "") { ag.drawLine(color, 1, i2 * w + x0, (j2 / 10 + 1) * h + y0, i * w + x0, (j / 10 + 1) * h + y0); } i2 = i; j2 = j; } } for (var i = 0; i < curve.length; i++) { var r = curve[i]; if (r.response() != null && r.response() !== "") { var x1 = i * w + x0; var y1 = (r.response() / 10 + 1) * h + y0; if (symbol == "x") { ag.drawLine(color, 3, x1 - 4, y1 - 4, x1 + 4, y1 + 4); ag.drawLine(color, 3, x1 - 4, y1 + 4, x1 + 4, y1 - 4); if (r.noResponse()) { ag.drawLine(color, 3, x1 + 3, y1 + 3, x1 + 6, y1 + 6); ag.drawTriangle(color, x1 + 8, y1 + 8, x1 + 8, y1 + 2, x1 + 2, y1 + 8); } } else { ag.drawCircle(color, "#d5d5d5", 4, x1, y1); if (r.noResponse()) { ag.drawLine(color, 3, x1 - 3, y1 + 3, x1 - 6, y1 + 6); ag.drawTriangle(color, x1 - 8, y1 + 8, x1 - 8, y1 + 2, x1 - 2, y1 + 8); } } } } }; ag.drawLine = function (color, width, x1, y1, x2, y2) { ag.g.strokeStyle = color; ag.g.lineWidth = width; ag.g.beginPath(); ag.g.moveTo(x1, y1); ag.g.lineTo(x2, y2); ag.g.closePath(); ag.g.stroke(); }; ag.drawCircle = function (color, fill, r, x, y) { ag.g.lineWidth = 3; ag.g.beginPath(); ag.g.arc(x, y, r, 0, Math.PI * 2, true); ag.g.closePath(); ag.g.fillStyle = fill; ag.g.fill(); ag.g.strokeStyle = color; ag.g.stroke(); }; ag.drawTriangle = function (color, x, y, x2, y2, x3, y3) { ag.g.fillStyle = color; ag.g.beginPath(); ag.g.moveTo(x, y); ag.g.lineTo(x2, y2); ag.g.lineTo(x3, y3); ag.g.closePath(); ag.g.fill(); }; ag.mouseMove = function (object, event) { ag.draw(event.offsetX, event.offsetY); }; ag.mouseLeave = function (object, event) { ag.draw(); }; ag.mouseClick = function (object, event) { if (typeof event.offsetX === "undefined" || typeof event.offsetY === "undefined") { var targetOffset = $(event.target).offset(); event.offsetX = event.pageX - targetOffset.left; event.offsetY = event.pageY - targetOffset.top; } var x = event.offsetX; var y = event.offsetY; x = Math.round((x - x0) / w); y = Math.round((y - y0) / h * 2) * 5 - 10; if (x < 0) x = 0; if (y < -10) y = -10; if (y > 130) y = 130; var responses = []; if (ag.mode() != text("Input Left")) responses.push(ag.right.air()[x]); if (ag.mode() != text("Input Right")) responses.push(ag.left.air()[x]); var remove = !responses.any(function (r) { return r.response() != y; }); responses.forEach(function (r) { if (remove) { if (event.which == 3) { r.noResponse(!r.noResponse()) } else { r.response(null); } } else { r.response(y); r.noResponse(event.which == 3); } }); }; ag.audioKeyDown = function (data, event) { if (event.keyCode == 229) return false; // prevent Chrome keys if (event.keyCode == 78 || event.keyCode == 13) { data.response(event.target.value); if (event.keyCode == 78) { data.noResponse(!data.noResponse()); } else { core.tabToNextField(event); } return false; } return ag.responseKeyDown(data, event); }; ag.responseKeyDown = function (data, event) { return event.keyCode != 32 && (event.keyCode == 189 || event.keyCode == 109 || event.keyCode < 48 || (event.keyCode >= 112 && event.keyCode <= 123) || (event.keyCode >= 48 && event.keyCode <= 57 && !event.shiftKey) || (event.keyCode >= 96 && event.keyCode <= 105)); }; ag.speechKeyDown = function (data, event) { //restrict input values to numbers 0-9 return event.keyCode != 32 && (event.keyCode < 48 || (event.keyCode >= 112 && event.keyCode <= 123) || (event.keyCode >= 48 && event.keyCode <= 57 && !event.shiftKey) || (event.keyCode >= 96 && event.keyCode <= 105)); }; ag.copyToLeft = function (agL) { ag.copyCurve(ag.right.air(), (agL || ag).left.air()); ag.copyCurve(ag.right.bone(), (agL || ag).left.bone()); (agL || ag).draw(); }; ag.copyToRight = function (agR) { ag.copyCurve(ag.left.air(), (agR || ag).right.air()); ag.copyCurve(ag.left.bone(), (agR || ag).right.bone()); (agR || ag).draw(); }; ag.copyCurve = function (src, dst) { for (var i = 0; i < src.length; i++) { dst[i].response(src[i].response()); dst[i].noResponse(src[i].noResponse()); } }; ag.resetAll = function () { ag.right.air().forEach(function (r) { r.response(null); }); ag.right.bone().forEach(function (r) { r.response(null); }); ag.left.air().forEach(function (r) { r.response(null); }); ag.left.bone().forEach(function (r) { r.response(null); }); }; ag.decodeCurve = function (curve, code) { if (!code) return; var responses = code.split(","); for (var i = 0; i < responses.length; i++) { var r = responses[i]; if (r) { // 'A' = 5 dB, 'B' = 10 dB, ... 'Z' = 130 dB // 'a' = *5 dB, 'b' = *10 dB, ... 'z' = *130 dB // '0' = 0 dB, '1' = -5 dB, '2' = -10 dB var c = r.charCodeAt(0); if (r == "0") curve[i].response(0); if (r == "1") curve[i].response(-5); if (r == "2") curve[i].response(-10); if (r >= "A" && r <= "Z") curve[i].response((c - 64) * 5); if (r >= "a" && r <= "z") { curve[i].response((c - 96) * 5); curve[i].noResponse(true); } } } }; ag.encodeCurve = function (curve) { var code = ""; var needsComma = false; curve.forEach(function (point) { var i = parseInt(point.response()); var nr = point.noResponse(); var c = ""; if (isNaN(i)) c = ""; else if (i == 0) c = "0"; else if (i == -5) c = "1"; else if (i == -10) c = "2"; else c = String.fromCharCode(Math.round(i / 5) + (nr ? 96 : 64)); code += (needsComma ? "," + c : c); needsComma = true; }); return code; }; ag.validate = function (curve) { if (!curve || !curve.length) return false; return curve[1].response() == null || curve[1].response() === "" || curve[3].response() == null || curve[3].response() === "" || curve[5].response() == null || curve[5].response() === "" || curve[7].response() == null || curve[7].response() === ""; }; ag.buildCurve = function (code, isBone) { var curve = ag.createCurve(isBone); if (code) { var responses = code.split(","); for (var i = 0; i < responses.length; i++) { if (responses[i]) { // 'A' = 5 dB, 'B' = 10 dB, ... 'Z' = 130 dB // 'a' = *5 dB, 'b' = *10 dB, ... 'z' = *130 dB // '0' = 0 dB, '1' = -5 dB, '2' = -10 dB var r = responses[i]; var c = r.charCodeAt(0); if (r == "0") curve[i].response("0"); if (r == "1") curve[i].response(-5); if (r == "2") curve[i].response(-10); if (r >= "A" && r <= "Z") curve[i].response((c - 64) * 5); if (r >= "a" && r <= "z") { curve[i].response((c - 96) * 5); curve[i].noResponse(true); } } } } return curve; }; ag.draw(); } ; (function () { 'use strict'; ko.extenders.required = function (target, options) { var opts = { validateFunction: function (newValue) { return !newValue; }, shouldValidate: ko.observable(true), isEnabled: ko.observable(true), isRequired: ko.observable(true) }; if (options instanceof Function) { opts.validateFunction = options; } else if (options instanceof Object) { opts = $.extend(opts, options); } target.hasError = ko.observable(null); target.isEnabled = opts.isEnabled; target.isRequired = opts.isRequired; function validate(newValue) { if (ko.utils.unwrapObservable(opts.shouldValidate) && ko.utils.unwrapObservable(target.isEnabled) && ko.utils.unwrapObservable(target.isRequired)) { target.hasError(opts.validateFunction(newValue)); } else { target.hasError(null); } } validate(target()); target.subscribe(validate); if (ko.isObservable(opts.shouldValidate)) opts.shouldValidate.subscribe(function () { validate(target()); }); if (ko.isObservable(target.isEnabled)) target.isEnabled.subscribe(function () { validate(target()); }); if (ko.isObservable(target.isRequired)) target.isRequired.subscribe(function () { validate(target()); }); return target; }; }()); ; // ********************************************************************************* // // Rules Engine for product options // // ********************************************************************************* var rules = new RulesEngine(); function RulesEngine() { var rules = function (rule, side) { if (!rules.data) return; var result = {}; if (rule.Activates) { core.makeArray(rule.Activates).forEach(function (id) { var item = rules.find(id); rules.setAvailable(item, side, true); if (item && ["select", "select-nd", "single", "single, inline", "dual-single", "dual-single-nd"].contains(item.parent.Kind)) { if (!item.parent.Items.any(function (i) { return rules.isSelected(i, side); })) { rules.selectDefaults(item.parent, side, false); } } }); } if (rule.Deactivates) { core.makeArray(rule.Deactivates).forEach(function (id) { var item = rules.find(id); if (rules.isSelected(item, side)) { rules.setSelected(item, side, false); result.changesMade = true; } rules.setAvailable(item, side, false); if (item && ["select", "select-nd", "dual-select", "dual-select-nd", "single", "single, inline", "dual-single", "dual-single-nd"].contains(item.parent.Kind)) { if (!item.parent.Items.any(function (i) { return rules.isSelected(i, side); })) { rules.selectDefaults(item.parent, side, false); } } }); } if (rule.Undeactivates) { core.makeArray(rule.Undeactivates).forEach(function (id) { if (rules.isActivatable(id, side)) { rules({ Activates: id }, side); } }); } if (rule.Selects) { core.makeArray(rule.Selects).forEach(function (id) { var item = rules.find(id); if (rules.isAvailable(item, side)) { if (!rules.isSelected(item, side)) result.changesMade = true; rules.setSelected(item, side, true); } else { if (item) { result.error = '"{0}" is required and is not currently selectable'.format(item.Name); } else { result.error = "required item {0} is not present".format(rule.Selects); } } }); } if (rule.Prefers && !rules.ignorePrefers) { core.makeArray(rule.Prefers).forEach(function (id) { var item = rules.find(id); if (rules.isAvailable(item, side)) { if (!rules.isSelected(item, side)) result.changesMade = true; rules.setSelected(item, side, true); } }); } if (rule.Unselects) { core.makeArray(rule.Unselects).forEach(function (id) { var item = rules.find(id); if (rules.isSelected(item, side)) result.changesMade = true; rules.setSelected(item, side, false); }); } if (rule.Reevaluates) { core.makeArray(rule.Reevaluates).forEach(function (id) { var item = rules.find(id); if (rules.isAvailable(item, side) && (side == rules.left || item.saved_SelectedRight != undefined) && (side == rules.right || item.saved_SelectedLeft != undefined)) { result.changesMade = true; if (side != rules.left) item.saved_SelectedRight = undefined; if (side != rules.right) item.saved_SelectedLeft = undefined; } }); } return result; } rules.data = null; rules.rules = null; rules.running = false; rules.error = null; rules.right = "Right"; rules.left = "Left"; rules.sides = [rules.right, rules.left]; rules.kinds = ["hidden", "select", "dual-select", "multi", "dual-multi", "single", "dual-single", "select-nd", "dual-select-nd", "dual-single-nd", "single, inline", "display"]; rules.onChange = function () { } rules.ignorePrefers = false; rules.evaluate = function () { if (!rules.running) { rules.running = true; rules.save(); rules.sync(); setTimeout(rules.runRules); } }; rules.runRules = function () { if (!rules.rules) return; rules.running = true; var error = rules.sides.any(function (side) { var iteration = 1; var result = { changesMade: true }; while (result.changesMade) { result = rules.runRulesSide(side); if (++iteration >= 50) { result.error = "Error: circular rules detected"; } if (result.error) { rules.revert(); rules.error(result.error); rules.running = false; return true; } } rules.runRulesSide(side); }); if (!error) { rules.error(null); rules.running = false; rules.sync(); rules.save(); rules.onChange(); } }; rules.runRulesSide = function (side) { for (var r = 0; r < rules.rules.length; r++) { var rule = rules.rules[r]; var result = null; if (rule.Selected) { var conditionMet = core.makeArray(rule.Selected).any(function (id) { var item = rules.find(id); return rules.hasChanged(item, side) && rules.isSelected(item, side); }); if (conditionMet) { result = rules(rule, side); if (result.error) { if (item && item.Name) { result.error = '"{0}" cannot be selected: {1}'.format(item.Name, result.error); } else { result.error = 'Cannot select item: {0}'.format(result.error); } return result; } else if (result.changesMade) { return result; } } } if (rule.Unselected) { var item = rules.find(rule.Unselected); if (rules.hasChanged(item, side) && !rules.isSelected(item, side)) { result = rules(rule, side); if (result.changesMade) { return result; } } } if (rule.Incompatible) { if (rule.Hides) { var item = rules.find(rule.Incompatible); if (rules.hasChanged(item, side)) { if (rules.isSelected(item, side)) { result = rules({ Deactivates: rule.Hides }, side); if (result.changesMade) return result; } else { // TODO: Don't used hard coded option IDs for CROS with earmold goofiness in RulesEngine rules([constants.productOptions.CrosTxr, constants.productOptions.EmCrosTxr, constants.productOptions.SnapFitNoReceiver, constants.productOptions.OriginalNoReceiver, constants.productOptions.Parallel, constants.productOptions.ParallelSoft].contains(rule.Incompatible) ? { Undeactivates: rule.Hides } : { Activates: rule.Hides }, side); } } } if (rule.HidesFrom && rules.anyChanged(rule.HidesFrom, side)) { if (rules.anySelected(rule.HidesFrom, side)) { result = rules({ Deactivates: rule.Incompatible }, side); if (result.changesMade) return result; } else { if ([constants.productOptions.RegSnapConnectYesEM, constants.productOptions.HeavySnapConnectYesEM, constants.productOptions.RegSnapConnectNoEM, constants.productOptions.HeavySnapConnectNoEm, constants.productOptions.EarplugConversionCord].contains(rule.Incompatible)) { rules({ Undeactivates: rule.Incompatible }, side); } else rules({ Activates: rule.Incompatible }, side); } } if (rule.ShowIf && rules.anyChanged(rule.ShowIf, side)) { if (rules.anySelected(rule.ShowIf, side)) { rules({ Activates: rule.Incompatible }, side); } else { result = rules({ Deactivates: rule.Incompatible }, side); if (result.changesMade) return result; } } if (rule.Requires && rules.anyChanged(rule.Requires, side)) { if (rules.allSelected(rule.Requires, side)) { rules({ Undeactivates: rule.Incompatible }, side); } else { result = rules({ Deactivates: rule.Incompatible }, side); if (result.changesMade) return result; } } } } return { changesMade: false }; }; rules.find = function (id, group) { if (!rules.data || !id) return null; if (!group) group = { Items: rules.data() }; for (var i = 0; i < group.Items.length; i++) { var item = group.Items[i]; if (item.Name == id || item.English == id) { return item; } else if (item.Items) { var subItem = rules.find(id, item); if (subItem) return subItem; } else if (item.Id == id) { return item; } } return null; } rules.anyChanged = function (idList, side) { return idList.any(function (id) { return rules.hasChanged(rules.find(id), side); }); } rules.anySelected = function (idList, side) { return idList.any(function (id) { return rules.isSelected(rules.find(id), side); }); } rules.allSelected = function (idList, side) { return idList.all(function (id) { return rules.isSelected(rules.find(id), side); }); } rules.hasChanged = function (item, side) { return item && (side == rules.right ? item.selectedRight() != item.saved_SelectedRight : item.selectedLeft() != item.saved_SelectedLeft); } rules.isSelected = function (item, side) { return item && ((rules.isAvailable(item, side) && item.parent.Kind == "display") || (side == rules.right ? item.selectedRight() : item.selectedLeft())); }; rules.isAvailable = function (item, side) { return item && (side == rules.right ? item.availableRight() : item.availableLeft()); }; rules.isActivatable = function (itemId, side) { return !rules.rules.any(function (r) { return (r.Incompatible == itemId && ((r.HidesFrom || []).any(function (opt) { return rules.isSelected(rules.find(opt), side); }) || (r.ShowIf && r.ShowIf.all(function (opt) { return !rules.isSelected(rules.find(opt), side); })))) || ((r.Hides || []).contains(itemId) && rules.isSelected(rules.find(r.Incompatible), side)) || ((r.Deactivates || []).contains(itemId) && (r.Unselected && !rules.isSelected(rules.find(r.Unselected), side) || (r.Selected && rules.isSelected(rules.find(r.Selected), side)))) || (r.Incompatible == itemId && (r.Requires || []).any(function (opt) { return !rules.isSelected(rules.find(opt), side); })); }); }; rules.setSelected = function (item, side, value) { if (item) { if (value && (item.parent.Kind == "single" || item.parent.Kind == "single, inline")) value = item.Id; if (value) { if ([ "select", "select-nd", "single", "single, inline", "dual-select", "dual-select-nd", "dual-single", "dual-single-nd" ].contains(item.parent.Kind)) { rules.resetGroup(item, side); } if (["select", "select-nd"].contains(item.parent.Kind)) { item.parent.selectedItem(item); } if (["dual-select", "dual-select-nd"].contains(item.parent.Kind)) { if (!side || side == rules.right) item.parent.selectedItemRight(item); if (!side || side == rules.left) item.parent.selectedItemLeft(item); } } if (!side || side == rules.right) { item.selectedRight(value); } if (!side || side == rules.left) { item.selectedLeft(value); } item.selected(item.selectedRight() || item.selectedLeft()); } }; rules.setAvailable = function (item, side, value) { if (item) { if (!side || side == rules.right) { item.availableRight(value); } if (!side || side == rules.left) { item.availableLeft(value); } item.available(item.availableRight() || item.availableLeft()); item.availableBoth(item.availableRight() && item.availableLeft()); } }; rules.reevaluate = function (item) { item.saved_SelectedRight = null; item.saved_SelectedLeft = null; rules.evaluate(); }; rules.selectDefaults = function (group, side, needsValue) { if (!group) return; var hasDefault = false; var firstId = null; var lastId = null; for (var i = 0; i < group.Items.length; i++) { var item = group.Items[i]; if (item.Items) { rules.selectDefaults(item, side, needsValue); } else if (rules.isAvailable(item, side)) { if (firstId == null) firstId = item.Id; lastId = item.Id; if (item.IsDefault) { rules({ Selects: item.Id }, side); hasDefault = true; } } } if (["select", "dual-select"].contains(group.Kind)) needsValue = true; if (["select-nd", "dual-select-nd"].contains(group.Kind)) needsValue = false; if (firstId == lastId && group.Id != 85 && group.Id != 41) needsValue = true; // Group Id 85 for Include CROS Earmold Options if (["multi", "dual-multi", "dual-single-nd"].contains(group.Kind)) needsValue = false; if (!hasDefault && needsValue) { rules({ Selects: firstId }, side); } } rules.itemClick = function (data, side) { var right = !side || side == rules.right; var left = !side || side == rules.left; var value = false; if (right && data.availableRight() && !data.selectedRight()) value = true; if (left && data.availableLeft() && !data.selectedLeft()) value = true; rules.atomicChange(function () { if (["single", "single, inline", "dual-single", "dual-select", "dual-single-nd"].contains(data.parent.Kind)) { rules.resetGroup(data, side); value = true; } if (right && data.availableRight()) data.selectedRight(value); if (left && data.availableLeft()) data.selectedLeft(value); data.selected(data.selectedRight() || data.selectedLeft()); }); } rules.resetGroup = function (item, side) { if (!item) return; item.parent.Items.forEach(function (child) { if (child != item) { if (!side || side == rules.right) { child.selectedRight(false); } if (!side || side == rules.left) { child.selectedLeft(false); } child.selected(false); } }); }; rules.sync = function (group) { if (!group) group = { Items: rules.data() }; group.Items.forEach(function (item) { if (item.Items) { rules.sync(item); } else { item.m_SelectedRight = item.selectedRight(); item.m_SelectedLeft = item.selectedLeft(); item.m_AvailableRight = item.availableRight(); item.m_AvailableLeft = item.availableLeft(); } }); } rules.save = function (group) { if (!group) group = { Items: rules.data() }; group.Items.forEach(function (item) { if (item.Items) { rules.save(item); } else { item.saved_SelectedRight = item.m_SelectedRight; item.saved_SelectedLeft = item.m_SelectedLeft; item.saved_AvailableRight = item.m_AvailableRight; item.saved_AvailableLeft = item.m_AvailableLeft; } }); } rules.revert = function (group) { if (!group) group = { Items: rules.data() }; group.Items.forEach(function (item) { if (item.Items) { rules.revert(item); } else { item.m_SelectedRight = item.saved_SelectedRight; item.m_SelectedLeft = item.saved_SelectedLeft; item.m_AvailableRight = item.saved_AvailableRight; item.m_AvailableLeft = item.saved_AvailableLeft; rules.setSelected(item, rules.right, item.saved_SelectedRight); rules.setSelected(item, rules.left, item.saved_SelectedLeft); rules.setAvailable(item, rules.right, item.saved_AvailableRight); rules.setAvailable(item, rules.left, item.saved_AvailableLeft); } }); }; rules.getSelectedIds = function (group, side, options) { if (!options) options = []; if (typeof group == "string") { group = rules.find(group); if (!group) return []; } if (!group) group = { Items: rules.data() }; group.Items.forEach(function (item) { if (item.Items) { rules.getSelectedIds(item, side, options); } else { if (rules.isSelected(item, side)) { options[options.length] = item.Id; } } }); return options; } rules.atomicChange = function (changes) { if (!rules.running) { rules.running = true; changes(); rules.running = false; rules.evaluate(); } }; rules.printModel = function (group) { if (!group) { console.log("==================================="); group = { Items: rules.data() }; } group.Items.forEach(function (item) { if (item.Items) { rules.printModel(item); } else { console.log(item.Name + ": " + item.selectedRight() + ", " + item.selectedLeft() + ", Model: " + item.m_SelectedRight + ", " + item.m_SelectedLeft + ", Saved: " + item.saved_SelectedRight + ", " + item.saved_SelectedLeft); } }); } rules.init = function (data, error, rulesList) { rules.initGroup({ Items: data() }); rules.data = data; rules.rules = rulesList.list(function (val) { return !val.Reevaluates; }).concat(rulesList.list(function (val) { return val.Reevaluates; })); rules.error = error; }; rules.initGroup = function (group) { if (!group || !group.Items) return; group.Items.forEach(function (item) { item.available = ko.observable(true); item.availableRight = ko.observable(true); item.availableLeft = ko.observable(true); if (item.Items) { rules.initGroup(item); } else { item.selected = ko.observable(false); item.selectedRight = ko.observable(false); item.selectedLeft = ko.observable(false); item.availableBoth = ko.observable(true); item.m_SelectedRight = undefined; item.m_SelectedLeft = undefined; item.m_AvailableRight = true; item.m_AvailableLeft = true; item.parent = group; item.selected.subscribe(rules.selectedChanged(item)); item.selectedRight.subscribe(rules.selectedChanged(item, rules.right)); item.selectedLeft.subscribe(rules.selectedChanged(item, rules.left)); item.availableRight.subscribe(rules.availableChanged(item, rules.right)); item.availableLeft.subscribe(rules.availableChanged(item, rules.left)); } }); group.validate = function (side) { var valid = true; if (["single", "single, inline", "dual-single", "select-nd", "dual-select-nd", "dual-single-nd"].contains(group.Kind)) { if (!side || side == rules.right) { valid = !group.availableItemsRight().length || group.Items.any(function (item) { return item.Items ? item.validate(side) : item.selectedRight(); }); } if (!side || side == rules.left) { valid = valid && (!group.availableItemsLeft().length || group.Items.any(function (item) { return item.Items ? item.validate(side) : item.selectedLeft(); })); } } return !valid; }; group.selectedItem = ko.observable(); group.selectedItem.subscribe(rules.selectedItemChanged(group)); group.selectedItemRight = ko.observable(); group.selectedItemRight.subscribe(rules.selectedItemChanged(group, rules.right)); group.selectedItemLeft = ko.observable(); group.selectedItemLeft.subscribe(rules.selectedItemChanged(group, rules.left)); group.availableItems = ko.observableArray(group.Items); group.availableItemsRight = ko.observableArray(group.Items); group.availableItemsLeft = ko.observableArray(group.Items); } rules.selectedChanged = function (item, side) { return function (newValue) { rules.atomicChange(function () { if (["single", "single, inline", "dual-single", "dual-single-nd"].contains(item.parent.Kind)) { rules.resetGroup(item, side); } if (side == rules.right) { item.selectedRight(newValue); } else if (side == rules.left) { item.selectedLeft(newValue); } else { item.selected(newValue); if (!["select", "dual-select"].contains(item.parent.Kind)) { item.selectedRight(newValue); item.selectedLeft(newValue); } } }); }; }; rules.availableChanged = function (item, side) { return function (newValue) { var items = [], itemsRight = [], itemsLeft = []; item.parent.Items.forEach(function (child) { if (child.availableRight()) itemsRight[itemsRight.length] = child; if (child.availableLeft()) itemsLeft[itemsLeft.length] = child; if ((child.availableRight() && child.availableLeft()) || ((item.Kind == "dual-single" || item.Kind == 'dual-single-nd') && (child.availableRight() || child.availableLeft()))) { items[items.length] = child; } }); item.parent.availableItems(items); item.parent.availableItemsRight(itemsRight); item.parent.availableItemsLeft(itemsLeft); rules.evaluate(); }; }; rules.selectedItemChanged = function (group, side) { return function (newValue) { rules.atomicChange(function () { if (newValue) { rules.resetGroup(newValue, side); if (!side || side == rules.right) { newValue.selectedRight(true); } if (!side || side == rules.left) { newValue.selectedLeft(true); } if (!side) { newValue.selected(true); } } else { group.Items.forEach(function (child) { if (!side || side == rules.right) child.selectedRight(false); if (!side || side == rules.left) child.selectedLeft(false); child.selected(false); }); } }); }; }; return rules; } ; // ********************************************************************************* // Site framework // ********************************************************************************* // Enable new Knockout 3.4.0 deferred updates *NOTE* EXPERIMENTAL AT THIS POINT -- BE CAREFUL //ko.options.deferUpdates = true; // #region Globals const loggingInCookie = 'is_logging_in'; const orderPrefix = 'order.'; const dashOrderPrefix = '-order'; const miracleEarPrefix = 'miracle-earpro'; const koreaPrefix = 'kr.'; const receiverTypeG23 = 'SnapFit2'; const chargersProductType = 'Rechargeable Accessories'; const chargerOptionsId = 68; const chargerOptionsIdIBD = 69; const chargerOptionsIdACO = 73; const chargerOptionTypeId = 1032; const chargerOptionIdsList = [68, 69, 73] const patientOrder = 'patient'; const stockOrder = 'bulk'; const noChargerValidationCountries = ['FR', 'NZ', 'AU', 'UK']; const powerAdapterPartNumber = '43092-003'; const premiumStandardChargerOptionId = 1215; var site = { pageTitle: null, brand: null, brandDescription: null, prefix: null, firstLoad: true, rscript: /)<[^<]*)*<\/script>/gi, currentRoute: null, userReview: false, navHeight: 0, searchText: ko(), loading: false, spinner: true, spinnerTimer: null, hoverMenus: null, loginComponentRegistrations: function (params) { this.fullWidth = true; }, sizeClass: ko(), chatVisible: ko(false), documentReady: ko(false), fullWidth: ko(false), transferPatient: ko(null, function (value) { if (!value) return; if (!(value instanceof Object)) return site.transferPatient(JSON.parse(Base64.decode(value))); else if (value.userGuid == session.userGuid) return; if (core.getCookie("transferPatient")) return; site.transferPatient(null); }), historyStart: ko(true), imagesPreloaded: ko(false), cookieBannerVisible: ko(!core.getCookie("hideCookieBanner")), noRushBannerVisible: ko(!core.getCookie("hideNoRushBanner")), accountId: "", userName: "", myMSALObj: null, productId: null, defaultLoginErrorMessage: "Login Failed", hideOldLogin: true, msalError: null, isLoginError: ko(false), noAccountForLoginError: ko(false), loginLoading: false, logoRoute: '/', sessionCookieExists: false, currentURL: null, injectRUM: ko(false), injectStageRUM: ko(false), injectProductionRUM: ko(false) }; var vm, session = {}, text = function (t) { return t; } var buckets = { AccountSummary: 1, OrderTracking: 2, Ordering: 3, FinancialStatus: 4, HearingAidHistory: 5, SoftwareDownloads: 6, MarketingOnDemand: 7, WarrantyRequest: 8, LossDamageClaim: 9, FedexLabels: 10, WorkshopRequest: 11, ManageUsers: 12, PatientBase: 14, BusinessTools: 15, ProfessionalLocator: 16, Consignment: 17 }; var spaPages = [ '/my-account/my-profile', '/my-account/patient-consent' ]; var CartItemType = { BteOnly: 1, RicWithStockReceiver: 2, Custom: 3, Earmold: 4, BteWithEarmold: 5, RicWithEarmold: 6, ApReceiver: 7, RicWithAp: 8, FacePlates: 9, AMP: 30, Accessory: 40, Supply: 50, StockReceiver: 55, SparePart: 60, Literature: 70, SoundGear: 80, SoundGearCustom: 83, SoundGearEarmold: 84, DashTailored: 85 }; var ReceiverType = { NonSnapFit: 0, SnapFit: 1, SnapFit2: 2 } site.isServer = function () { return !!window.callPhantom; }; const env = document.location.host.contains("local") || document.location.host.contains("dev") ? "dev" : document.location.host.contains("test") ? "test" : document.location.host.contains("stage") ? "stage" : "production"; let msalConfig; if (location.href.contains('miracle-earpro')) { msalConfig = { auth: { clientId: env === "test" ? "2354d8a4-0796-4948-854a-b2c13f3375c8" : env === "stage" ? "429de552-5317-493f-851e-e55e2368f415" : env === "production" ? "950ecbef-18a7-4016-a23f-1ea80a475c28" : "c7fc6797-b1ed-48a5-adae-9c9caa00ec98", authority: env === "test" ? "https://teststarkeyb2c.b2clogin.com/teststarkeyb2c.onmicrosoft.com/B2C_1A_MIRACLE-EARV1SIGNIN/" : env === "stage" ? "https://stagestarkeyb2c.b2clogin.com/stagestarkeyb2c.onmicrosoft.com/B2C_1A_MIRACLE-EARV1SIGNIN/" : env === "production" ? "https://starkeyb2c.b2clogin.com/starkeyb2c.onmicrosoft.com/B2C_1A_MIRACLE-EARV1SIGNIN/" : "https://devstarkeyb2c.b2clogin.com/devstarkeyb2c.onmicrosoft.com/B2C_1A_MIRACLE-EARV1SIGNIN/", knownAuthorities: env === "test" ? ["teststarkeyb2c.b2clogin.com"] : env === "stage" ? ["stagestarkeyb2c.b2clogin.com"] : env === "production" ? ["starkeyb2c.b2clogin.com"] : ["devstarkeyb2c.b2clogin.com"], redirectUri: document.location.origin, navigateToLoginRequestUrl: true, postLogoutRedirectUri: document.location.origin + "/login?/estore", }, cache: { cacheLocation: "sessionStorage", // This configures where your cache will be stored storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge } }; } else { msalConfig = { auth: { clientId: env === "test" ? "2354d8a4-0796-4948-854a-b2c13f3375c8" : env === "stage" ? "429de552-5317-493f-851e-e55e2368f415" : env === "production" ? "950ecbef-18a7-4016-a23f-1ea80a475c28" : "c7fc6797-b1ed-48a5-adae-9c9caa00ec98", authority: env === "test" ? "https://teststarkeyb2c.b2clogin.com/teststarkeyb2c.onmicrosoft.com/B2C_1A_ESTOREV1SIGNIN/" : env === "stage" ? "https://stagestarkeyb2c.b2clogin.com/stagestarkeyb2c.onmicrosoft.com/B2C_1A_ESTOREV1SIGNIN/" : env === "production" ? "https://starkeyb2c.b2clogin.com/starkeyb2c.onmicrosoft.com/B2C_1A_ESTOREV1SIGNIN/" : "https://devstarkeyb2c.b2clogin.com/devstarkeyb2c.onmicrosoft.com/B2C_1A_ESTOREV1SIGNIN/", knownAuthorities: env === "test" ? ["teststarkeyb2c.b2clogin.com"] : env === "stage" ? ["stagestarkeyb2c.b2clogin.com"] : env === "production" ? ["starkeyb2c.b2clogin.com"] : ["devstarkeyb2c.b2clogin.com"], redirectUri: document.location.origin, navigateToLoginRequestUrl: true, postLogoutRedirectUri: document.location.origin + "/login?/estore", }, cache: { cacheLocation: "sessionStorage", // This configures where your cache will be stored storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge } }; } // #endregion site.hasFeature = function (featureName) { return session.Features.any(function (i) { return i.FeatureName === featureName; }); }; site.getCartPath = function () { return site.hasFeature("CX 2019") ? "/prosite/estore/cart" : "/estore/cart"; }; site.handleLogIn = async function () { site.beforeLogIn(); } // #region Azure AD MSAL site.myMSALObj = new msal.PublicClientApplication(msalConfig); site.myMSALObj.handleRedirectPromise().then(async response => { site.currentURL = window.location.href; if (location.href.contains("postsignuplogout") || (response && response.idTokenClaims && response.idTokenClaims.isForgotPassword)) { const currentAcc = site.myMSALObj.getAccountByHomeId(site.accountId); await site.myMSALObj.logout(currentAcc); } if (response) { handleResponse(response); } else { if (env !== 'dev') { const currentAccounts = site.myMSALObj.getAllAccounts(); if (currentAccounts.length === 0) { ssoSilent(); } else { site.myMSALObj.ssoSilent({ loginHint: "test@starkey.com" }) .then((response) => { site.msalError = null; if (!response.idToken || response.idToken === "") { throw new msal.InteractionRequiredAuthError; } }) .catch(error => { site.msalError = error; handleInteractionRequiredError(); }); } } } }).catch((e) => { // If you somehow get caught in a login loop due to duplicate credential tokens in session storage, this fixes it sessionStorage.clear(); }) function handleInteractionRequiredError() { if (session.userName && site.msalError instanceof msal.InteractionRequiredAuthError) { site.logOut(); } else { console.log(site.msalError); } } function delay(time) { return new Promise(resolve => { $("#mobileSpin").fadeIn(0.6); setTimeout(resolve, time) }); } async function handleResponse(response) { if (response !== null) { if (response.idTokenClaims.starkeySelectStatus == null && env !== "dev") { sessionStorage.clear(); site.isLoginError(true); return; } $("#mobileSpin").fadeIn(0.6); $("html").addClass("wait"); site.msalError = null; site.loginLoading = true; site.accountId = response.account.homeAccountId; site.userName = response.account.idTokenClaims.email; core.get("/services/session/postLogIn?userName={0}", [site.userName], function (result) { if (!result) { $("#mobileSpin").fadeOut(); if (vm) { site.loginLoading = false; site.msalError = site.defaultLoginErrorMessage; vm.showLoginError(site.defaultLoginErrorMessage); sessionStorage.clear(); site.go('/login?/prosite'); } }; site.beforeLogIn(); if (JSON.parse(result).IsError) { $("#mobileSpin").fadeOut(); if (vm) { site.loginLoading = false; vm.showLoginError(site.defaultLoginErrorMessage); sessionStorage.clear(); site.go('/login?/prosite'); } } else { site.isLoginError(false); site.logIn(JSON.parse(result).Token, JSON.parse(result).Authority, JSON.parse(result).Redirect); } }, null, false, true); } } function ssoSilent() { $("#mobileSpin").fadeTo(null, 0.6); site.myMSALObj.ssoSilent({ loginHint: "test@starkey.com" }).then(response => { handleResponse(response); $("#mobileSpin").fadeOut(); }).catch(error => { site.msalError = error; handleInteractionRequiredError(); }); } if (!location.href.contains("singlelogout")) { const currentAccounts = site.myMSALObj.getAllAccounts(); if (currentAccounts.length > 0) { site.accountId = currentAccounts[0].homeAccountId; site.userName = currentAccounts[0].idTokenClaims.email; } } function signIn(e) { if (e) { e.preventDefault(); } if (vm && vm.submitting) { vm.submitting(true); } sessionStorage.clear(); site.myMSALObj.loginRedirect(); } function signOut(e) { if (e) { e.preventDefault(); } if (vm && vm.submitting) { vm.submitting(true); } sessionStorage.clear(); site.isLoginError(false); site.logOut(); } // #endregion Azure AD MSAL if (location.href.contains("b2clogin")) { var redirectUrl = window.location.href.replace("b2clogin", ""); window.location.href = redirectUrl; } // #region Initialization site.beforeLogIn = function () { if (session.account && window.location.href.contains("estore")) { window.location.href = window.location.href.substring(window.location.href.lastIndexOf("?") + 1); } else { site.page(text("Log In"), new function () { var vm = this; site.register("login", vm, function (params) { }); site.prepareLoginPage(vm); }, function () { // ATTN: New International site.fullWidth(!(window.location.href.contains('estore') && ["US", "CA", "AU", "NZ", "CO", "BR"].contains(session.country))); setTimeout(function () { site.focus("username") }, 100); }); } } site.init = function () { if (window.callPhantom) { $.fancybox.init = function () { }; } else { //Origami.fastclick.FastClick.attach(document.body); $(function () { FastClick.attach(document.body); }); if (window.location.href.contains('.com/#!')) { $("body").hide(); document.body.style.cursor = "wait"; document.title = ""; window.ignoreLoad = true; window.data = null; } site.navHeight = $("header").outerHeight(); } site.getRoute(); if (window.data && !window.callPhantom) { session = data.session; } else { site.runRoute(); } if (typeof (history.pushState) != "undefined" && typeof (window.addEventListener) != "undefined") { window.addEventListener("popstate", site.runRoute); } else { $(window).on("hashchange", site.runRoute); } if (window.location.href.contains("&#")) { window.location.href = $('
').html(window.location.href).text(); } if (!window.stop) { window.stop = function () { document.execCommand("Stop"); }; } $.browser = { msie: false }; site.injectRUM = ko(!document.location.host.contains("local") && !document.location.host.contains("test") && !document.location.host.contains("dev2")); site.injectStageRUM = ko(site.injectRUM() && document.location.host.contains("stage")); site.injectProductionRUM = ko(site.injectRUM() && !site.injectStageRUM()); }; // #endregion // #region Knockoutify $(document).ready(function () { site.documentReady(true); }); $(window).resize(function () { var width = window.innerWidth || (document.documentElement || document.body).clientWidth; if (width >= 99999) { site.sizeClass("lg"); } else if (width >= 1024) { site.sizeClass("md"); } else if (width >= 736) { site.sizeClass("sm"); } else { site.sizeClass("xs"); } }); var width = window.innerWidth || (document.documentElement || document.body).clientWidth; if (width >= 99999) { site.sizeClass("lg"); } else if (width >= 1024) { site.sizeClass("md"); } else if (width >= 736) { site.sizeClass("sm"); } else { site.sizeClass("xs"); } site.knockoutSession = function () { if (!session || !ko) { return; } if (!session.carts) { session.carts = { HasPatientProducts: false, HasSavedItems: false }; } session.carts.hasPatientProducts = session.carts.HasPatientProducts !== undefined ? ko(session.carts.HasPatientProducts) : ko(false); session.carts.hasSavedItems = session.carts.HasSavedItems !== undefined ? ko(session.carts.HasSavedItems) : ko(false); session.carts.favorites = session.carts.Favorites == null ? ko([]) : ko(session.carts.Favorites); session.carts.primary = session.carts.Primary == null ? ko([]) : ko(session.carts.Primary); if (session.carts.primary() && session.carts.primary().length) { site.prepareCartProducts(session.carts.primary()); } }; // #endregion // #region Page Setup site.require = function (scripts) { if (site.isServer() || !site.firstLoad) { scripts.forEach(function (script) { core.get(script); }); } }; site.include = function (script, componentName) { if (componentName && ko.components.isRegistered(componentName)) return; //if (window.callPhantom || !site.firstLoad) core.get(script); }; site.register = function (component, vm, viewModel) { vm["component" + component] = ko(new Service("/scripts/components/{0}.html", component), function (html) { if (!ko.components.isRegistered(component)) { ko.components.register(component, { viewModel: viewModel, template: html, synchronous: true }); } }); }; site.page = function (title, viewModel, init) { if (window.ignoreLoad) return; if ($.isFunction(viewModel)) { init = viewModel, viewModel = null; } site.pageTitle = title; vm = core.ko(viewModel ? viewModel : {}); site.loadCookies(); if (!window.callPhantom && window.data) { for (var item in data.vm) vm[item](data.vm[item]); site.knockoutSession(); data = null; site.brandPage(); site.bind(init); site.trackAnalytics(site.currentRoute); } else { if (window.callPhantom) site.cache = {}; var datas = []; for (var item in vm) { if (vm[item].subscribe) { if (vm[item]() instanceof Array && vm[item]().length == 1 && typeof (vm[item]()[0]) == "string" && vm[item]()[0].startsWith("/")) { datas.push([vm[item], vm[item]()[0]]); if (site.cache) site.cache[item] = null; } else if (ko.isObservableArray(vm[item]) && vm[item]._serviceUrl instanceof Service) { datas.push([vm[item], vm[item]._serviceUrl.url]); if (site.cache) site.cache[item] = null; } else if (ko.isObservable(vm[item]) && vm[item]() instanceof Service) { datas.push([vm[item], vm[item]().url]); if (site.cache) site.cache[item] = null; } } } core.load(datas, function () { if (site.cache) for (var item in site.cache) site.cache[item] = vm[item](); site.bind(init); }); } site.historyStart(window.location.href.indexOf("#") == -1); if (!site.isServer && !!window.appInsights) window.appInsights.trackPageView(); }; site.loadAppInsights = function (instrumentationKey) { var appInsights = window.appInsights || function (config) { function r(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, u = document, e = window, o = "script", s = u.createElement(o), i, f; for (s.src = config.url || "//az416426.vo.msecnd.net/scripts/a/ai.0.js", u.getElementsByTagName(o)[0].parentNode.appendChild(s), t.cookie = u.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace"]; i.length;) r("track" + i.pop()); return r("setAuthenticatedUserContext"), r("clearAuthenticatedUserContext"), config.disableExceptionTracking || (i = "onerror", r("_" + i), f = e[i], e[i] = function (config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t["_" + i](config, r, u, e, o), s }), t }({ instrumentationKey: instrumentationKey, overridePageViewDuration: true, disableExceptionTracking: true, disableAjaxTracking: true }); window.appInsights = appInsights; }; site.removeIsBusy = function () { site.loading = false; site.documentReady(true); if (!window.rxApp || !window.rxApp.isBusy()) { $("#mobileSpin").fadeOut(); } if (site.spinnerTimer) { clearTimeout(site.spinnerTimer); } if (site.spinner) { $("html").removeClass("wait"); document.body.style.cursor = "wait"; document.body.style.cursor = "default"; site.spinner = false; } }; site.bind = function (init) { ko.cleanNode($("body")[0]); ko.tasks.runEarly(); ko.applyBindings(vm); site.stylePage(); ko.tasks.runEarly(); if (init) init(); if (site.firstLoad) { $("body").show(); } else { site.scrollTop(); } site.removeIsBusy(); if (window.callPhantom) { // Data cache var script = document.createElement("script"); script.type = "text/javascript"; script.text = "var data={\"vm\":{0},\"session\":{1}};".format(JSON.stringify(ko.toJS(site.cache)), JSON.stringify(session)); var node = document.getElementById("#Z"); node.parentNode.insertBefore(script, node); // Mark selected items $("select > option").each(function () { if (this.selected) $(this).attr("selected", "selected"); }); $("input").each(function () { if (this.value) $(this).attr("value", this.value); if (this.checked) $(this).attr("checked", this.checked); }); // Server-side render callback window.callPhantom(); } core.cleanHead(); site.firstLoad = false; $('#myaccount-slider').hide(); var searchSlider = $('#search-slider'); if (searchSlider.length) { searchSlider.hide(); } if (vm.logIn) setTimeout(site.checkCookiesEnabled); }; site.preloadedImages = []; site.preloadImages = function () { if (!session || !session.account) return false; if (site.imagesPreloaded()) return true; var preloadedImages = [ "/images/icons/spinner.gif", "/images/icons/spinner.png", "/images/icons/loading.gif", "/estore/images/radio-enabled-checked-red.png", "/estore/images/radio-enabled-checked-blue.png", "/estore/images/checkbox-enabled-checked-red.png", "/estore/images/checkbox-enabled-checked-blue.png" ]; for (i = 0; i < preloadedImages.length; i++) { var preloadedImg = new Image(); preloadedImg.src = preloadedImages[i]; site.preloadedImages.push(preloadedImg); } site.imagesPreloaded(true); return true; }; site.breadCrumbVisible = ko.observable(true); site.stylePage = function () { var spaPrefx = (site.prefix ? site.prefix : '') + '/prosite'; if (!location.pathname.startsWith(spaPrefx)) { document.title = site.pageTitle ? "{1} | {0}".format(session.title, site.pageTitle) : session.title; } site.searchText(decodeURIComponent(core.query("q") || "")); site.breadCrumbVisible(true); site.hoverMenus = $(); $('[data-toggle="dropdown"]').not(".hover-off").dropdownHover(); $("div.tipdown").hide(); $("h3.tipdown").click(function (event) { event.preventDefault(); $(this).toggleClass("expanded").next("div.tipdown").slideToggle("fast"); }); $("h3.expanded").next("div.tipdown").show(); $("dd:even").addClass("alt"); $(".fancybox").fancybox(); $(".fancybox_480x270").fancybox({ width: 480, height: 270, titlePosition: "inside", type: "iframe", autoScale: false }); $(".fancybox_640x360").fancybox({ width: 640, height: 394, titlePosition: "inside", type: "iframe", autoScale: false }); $(".fancybox_640x480").fancybox({ width: 640, height: 514, titlePosition: "inside", type: "iframe", autoScale: false }); $(".fancybox_854x480").fancybox({ width: 854, height: 514, scrolling: "no", titlePosition: "inside", type: "iframe", autoScale: false }); $(".fancybox_854x480exact").fancybox({ width: 854, height: 480, scrolling: "no", titlePosition: "inside", type: "iframe", autoScale: false }); $(".fancybox_500x500").fancybox({ width: 500, height: 500, titlePosition: "inside", type: "iframe", autoScale: false }); $(".fancybox_500x560").fancybox({ width: 500, height: 560, titlePosition: "inside", type: "iframe", autoScale: false }); $(".fancybox_500x700").fancybox({ width: 500, height: 715, titlePosition: "inside", type: "iframe", autoScale: false }); if (!window.callPhantom) $("#fancybox-close").click($.fancybox.close); $.datepicker.setDefaults({ closeText: text("Done"), prevText: text("Previous"), nextText: text("Next"), currentText: text("Today"), dayNames: [text("Sunday"), text("Monday"), text("Tuesday"), text("Wednesday"), text("Thursday"), text("Friday"), text("Saturday")], dayNamesMin: [text("Su"), text("Mo"), text("Tu"), text("We"), text("Th"), text("Fr"), text("Sa")], dateFormat: core.getDateFormat(session.country), monthNames: [ text("January"), text("February"), text("March"), text("April"), text("May"), text("June"), text("July"), text("August"), text("September"), text("October"), text("November"), text("December") ] }); $(".date-picker").datepicker(); $("#content a").each(function () { if (!this.onclick && this.href) this.onclick = hijax; if (!this.href) this.href = "javascript:click()"; if (site.prefix) { if (this.href.startsWith("/") && !this.href.contains(".") && !this.href.contains(site.prefix)) { this.href = site.prefix + href; } } }); $('[data-toggle="popover"]').popover(); $('.navItem-navHeader[href$="#"]').click(function (event) { event.preventDefault(); const url = window.location.href; const path = "{0}/pdfs/MicroTech_Product_Comparison.pdf".format(url.substring(0, url.indexOf("/prosite"))); const pdfWindow = window.open(); pdfWindow.document.body.innerHTML = "Loading document..."; fetch(path) .then(response => { if (!response.ok) { const errMsg = "Failed to load the document. Make sure the file path is correct."; pdfWindow.document.body.innerHTML = errMsg; throw new Error(errMsg); } return response.arrayBuffer() }) .then(arrayResult => { const data = new Blob([arrayResult], { type: 'application/pdf', }); const pdfUrl = URL.createObjectURL(data); pdfWindow.location.replace(pdfUrl); }); }); site.preloadImages(); }; site.brandPage = function () { site.prefix = (session.subsite) ? "/" + session.subsite : ""; site.subSite = text("Professional"); if (site.prefix === '/government') site.subSite = text("Government"); if (site.prefix === '/students-faculty') site.subSite = text("Students & Faculty"); if (site.prefix === '/starkey-select-network') site.subSite = text("Starkey Select Network"); if (site.prefix === '/starkey-hearing-alliance') site.subSite = text("Starkey Hearing Alliance"); var font = ""; if (!session) { session = {}; } if (!session.title) { session.title = ""; } if (session.title.contains("KIND")) { site.brand = "KIND"; } else if (window.location.href.toLowerCase().contains("audibelpro.com")) { site.brand = "Audibel"; } else if (window.location.href.toLowerCase().contains("nuearpro.com")) { site.brand = "NuEar"; } else if (window.location.href.toLowerCase().contains("miracle-earpro.com")) { localStorage.setItem('MiracleEar', true); site.brand = "MiracleEar"; site.brandDescription = "Miracle Ear"; } else { site.brand = "Starkey"; font = ""; } site.brandDescription = site.brandDescription || site.brand; }; site.loadCookies = async function () { var url = window.location.href.replace("login?/", ""); var paramIndex = url.indexOf("?"); if (paramIndex > 0 && url.contains('hearing-aids-and-earmolds')) { var searchParams = url.slice(paramIndex); if (searchParams.contains('fn=') && searchParams.contains('ln=')) { await core.get("/services/session/createTransferPatientCookie?queryString={0}", [searchParams]); } } var transferPatientCookie = core.getCookie("transferPatient", null); if (transferPatientCookie) site.transferPatient(JSON.parse(Base64.decode(transferPatientCookie))); }; // #endregion // #region Page Prepare site.attachClickToLink = function () { const links = $('a[href$=".ashx"], a[href$=".pdf"]'); $(links).click(function (event) { event.preventDefault(); const path = $(this).attr("href"); const pdfWindow = window.open(); pdfWindow.document.body.innerHTML = "Loading document..."; fetch(path) .then(response => { if (!response.ok) { const errMsg = "Failed to load the document. Make sure the file path is correct."; pdfWindow.document.body.innerHTML = errMsg; throw new Error(errMsg); } return response.arrayBuffer() }) .then(arrayResult => { const data = new Blob([arrayResult], { type: "application/pdf", }); const pdfUrl = URL.createObjectURL(data); pdfWindow.location.replace(pdfUrl); }); }); } site.getStarkeyAdminReports = (event, address) => { event.preventDefault(); const url = window.location.href; const path = `{0}${address}`.format(url.substring(0, url.indexOf("/estore"))); const pdfWindow = window.open(); pdfWindow.document.body.innerHTML = "Loading document..."; fetch(path) .then(response => { if (!response.ok) { const errMsg = "Failed to load the document. Make sure the file path is correct."; pdfWindow.document.body.innerHTML = errMsg; throw new Error(errMsg); } return response.arrayBuffer() }) .then(arrayResult => { const data = new Blob([arrayResult], { type: "text/csv", }); const pdfUrl = URL.createObjectURL(data); pdfWindow.location.replace(pdfUrl); setTimeout(() => pdfWindow.close(), 1500); }); } site.prepareStoreNav = function (vm, collapseMenu) { vm.storeNav = ko(session.storeNav); vm.storeNavActive = ko(null); vm.storeNavActiveItem = ko(null); vm.storeNavExpanded = ko(false); if (vm.storeNav().length && !collapseMenu) vm.storeNavActive(vm.storeNav()[0].english); vm.storeNav().forEach(function (menu) { var activeItem; if (!menu.items) { if (window.location.href.contains(menu.route.substring(1))) { if (!collapseMenu) vm.storeNavActive(menu.english); vm.storeNavActiveItem(menu); } } else if (activeItem = menu.items.find(function (item) { return window.location.href.contains(item.route.substring(1)) })) { vm.storeNavActiveItem(activeItem); if (!collapseMenu) vm.storeNavActive(menu.english); } }); }; site.prepareProductList = function (products) { products.forEach(function (product) { if (!product.Brand) product.Brand = "N/A"; product.favorite = ko(product.Favorite); product.loadingFavorite = ko(); product.isChecked = ko(); product.hasQuickAdd = ko(product.CartItemTypeId > 8 && ![CartItemType.AMP, CartItemType.SoundGear, CartItemType.SoundGearEarmold, CartItemType.SoundGearCustom, CartItemType.DashTailored].contains(product.CartItemTypeId)); product.addedToCart = ko(); product.loadingBulkAdd = ko(); product.quantity = ko(); product.isDeleted = ko(product.Quantity == 0); product.quantity.subscribe(function (value) { if (!value) { product.addedToCart(false); return; } core.get("/services/parts/{0}/validateQuantity/{1}", [product.PartNumber, value], function (validatedQuantity) { if (value != product.quantity()) return; if (validatedQuantity != null && typeof (value) === "string") validatedQuantity = validatedQuantity.toString(); product.quantity(validatedQuantity); product.addedToCart(false); }); }); }); }; site.getAccountDisplayName = function (account, formatString) { if (!formatString) formatString = "{FullAccountNumber} - {PartyName}, {Street1}"; var replacements = [ "AccountNumber", "FullAccountNumber", "PartyName", "Street1", "Street2", "Street3", "Street4", "City", "State", "PostalCode", "Country", "PartyName", "LocationId", "CustomerCategory" ]; for (var ndx = 0; ndx < replacements.length; ndx++) { formatString = formatString.replaceAll("{" + replacements[ndx] + "}", "{" + ndx + "}"); } if (account == null) return; var formatArgs = replacements.select(function (attr) { return ko.utils.unwrapObservable(account[attr]); }); return formatString.format.apply(formatString, formatArgs); }; site.isAccountIbd = function (account) { return account != null && (account.Region == "10" || account.Region == "10SMP" || (account.Region && account.Region.startsWith("IBD")) || (account.CustomerCategory && account.CustomerCategory.startsWith("IBD"))); }; site.getDefaultFormattedBillToDisplayName = function (billToAccount) { if (billToAccount == null) return; var showCustomerCategory = session.country == "US" && !site.isAccountIbd(billToAccount); var formatString = "{FullAccountNumber}: {PartyName}"; if (showCustomerCategory && !!billToAccount.CustomerCategory) formatString += " - {CustomerCategory}"; return site.getAccountDisplayName(billToAccount, formatString); }; site.prepareDropdownAccounts = function (accountList, formatString) { if (!core.isArray(accountList)) return; if (!formatString) formatString = "{FullAccountNumber} - {PartyName}, {Street1}"; var replacements = [ "AccountNumber", "FullAccountNumber", "PartyName", "Street1", "Street2", "Street3", "Street4", "City", "State", "PostalCode", "Country", "PartyName", "LocationId", "CustomerCategory" ]; for (var ndx = 0; ndx < replacements.length; ndx++) { formatString = formatString.replaceAll("{" + replacements[ndx] + "}", "{" + ndx + "}"); } accountList.forEach(function (account) { if (account == null) return; var formatArgs = replacements.select(function (attr) { return ko.utils.unwrapObservable(account[attr]); }); var displayName = formatString.format.apply(formatString, formatArgs); account.displayName = ko.observable(displayName); }); }; site.loadAccounts = function (callback, formatString) { core.get("/services/accounts/", function (accounts) { if (accounts != null) accounts.forEach(function (account) { site.prepareDropdownAccounts(account.ShipToAccounts, formatString); }); if (callback instanceof Function) callback(accounts); }); }; site.prepareQuickAdd = function (vm) { vm.hasImages = ko(true); vm.source = ko(); vm.description = ko(); vm.handleFavoriteButton = function (data) { if (data.loadingFavorite()) return; if (data.favorite() == null ? data.Favorite : data.favorite()) vm.removeFromFavorites(data); else vm.addToFavorites(data); }; vm.addToFavorites = function (product) { product.loadingFavorite(true); var dto = { ItemGuid: product.Id || product.ItemGuid, TypeId: product.CartItemTypeId } core.post("/services/estore/cart/favorites/add/", dto, function (favorites) { if (favorites != null) { session.carts.favorites(favorites); product.favorite(true); product.loadingFavorite(false); } }); }; vm.removeFromFavorites = function (product) { if (!product) return; var item = session.carts.favorites().find(function (value) { return value.ItemGuid == product.ItemGuid; }); if (!item) return; product.loadingFavorite(true); core.delete("/services/estore/cart/favorites/remove/", [item.ItemID], function (favorites) { session.carts.favorites(favorites); if (!session.carts.favorites().find(function (value) { return value.ItemGuid == product.ItemGuid; })) { product.favorite(false); } product.loadingFavorite(false); }); }; vm.quickAddBulk = function (product, callback, ignoreModalBump) { product.loadingBulkAdd(true); if (!product.quantity()) product.quantity(1); var bulkProduct = { CartItemTypeId: product.CartItemTypeId, IsParent: true, IsPatient: false }; if (site.willBumpCartContents(bulkProduct, session.carts.primary()) && !ignoreModalBump) { site.showModalBump(vm.quickAddBulk, null, [product, callback, true]); product.loadingBulkAdd(false); } else { var dto = { ItemGuid: product.Id || product.ItemGuid, Quantity: product.quantity(), TypeId: product.CartItemTypeId }; if (!dto.ItemGuid) dto.ItemGuid = product.ItemGuid; core.post("/services/estore/cart/add/bulk/", dto, function (carts) { if (carts.Primary && carts.Primary.length) { site.prepareCartProducts(carts.Primary); } session.carts.primary(carts.Primary); session.carts.hasPatientProducts(carts.HasPatientProducts); session.carts.hasSavedItems(carts.HasSavedItems); if (callback instanceof Function) { callback(); } else { product.addedToCart(true); product.loadingBulkAdd(false); } }); } }; vm.zoomImage = function (product) { vm.source(product.ImageUrl); vm.description(product.Description); modal.show($('#modalZoom')); }; site.register("stackedProduct", vm, function (params) { this.product = params.product; this.hasImages = params.hasImages; this.isFavorite = params.isFavorite; }); site.register("gridProduct", vm, function (params) { this.product = params.product; }); }; site.prepareCartProducts = function (products) { products.forEach(function (product) { product.isDeleted = ko(product.Quantity == 0); product.favorite = ko(ko.unwrap(product.favorite) || product.Favorite); product.loadingFavorite = ko(ko.unwrap(product.loadingFavorite)); product.quantity = ko(ko.unwrap(product.quantity) || product.Quantity); product.isQuantityUpdated = ko(ko.unwrap(product.isQuantityUpdated)); product.isMovingCarts = ko(ko.unwrap(product.isMovingCarts)); }); }; site.prepareLoginPage = function (vm) { vm = core.ko({ userName: null, password: null, emailAddress: null, phoneNumber: session.supportPhoneNumber, submitting: false, error: ko(false, function (isError) { if (isError) { vm.hideLoginTimeoutMessage(); vm.submitting(false); site.focus("password"); } }), showLoginError: function (errorMessage) { if (!!errorMessage) { vm.loginErrorMessage(errorMessage); } vm.error(true); }, logIn: function () { if (vm.submitting()) return; vm.submitting(true); vm.error(false); vm.loginErrorMessage(null); document.forms[0].submit(); vm.loginTimeoutMessageTimeout(setTimeout(vm.toggleLoginTimeoutMessage, 7000)); /* 7 second timeout */ }, toggleLoginTimeoutMessage: function () { vm.loginTimeoutMessage(text('Please wait while we access your account information. This may take up to one minute.')); }, hideLoginTimeoutMessage: function () { vm.loginTimeoutMessage(null); var loginTimerId = vm.loginTimeoutMessageTimeout(); if (loginTimerId) clearTimeout(loginTimerId); vm.loginTimeoutMessageTimeout(null); }, loginErrorMessage: ko(), loginTimeoutMessage: ko(), loginTimeoutMessageTimeout: ko(), }, vm); }; site.prepareOrderList = function (vm) { site.register("orderListTable", vm, function (params) { this.orders = params.orders; this.captionText = params.captionText; this.loadingData = params.loading; }); // ATTN: New International vm.showPizzaTracker = ko(["US", "IT", "AU", "NZ", "UK", "CO"].contains(session.country)); vm.isCustomOrder = function (order) { if (order.orderType) { return !["standard order aid", "miscellaneous"].contains(order.orderType.trim().toLowerCase()); } return (order.userName && !["stock"].contains(order.userName.trim().toLowerCase())) && (!order.make || !["standard", "replacement"].contains(order.make.trim().toLowerCase())); }; vm.hearingAidHistoryUrl = "/my-account/hearing-aid-history/detail"; vm.orderTrackingUrl = "/my-account/order-tracking"; vm.orderTrackingLinks = [ { name: "Fedex", isMatch: function (shipType) { return shipType.startsWith('FEDEX'); }, linkTemplate: "https://www.fedex.com/fedextrack/?tracknumbers={0}" }, { name: "USPS", isMatch: function (shipType) { return shipType == "MAIL:"; }, linkTemplate: "https://tools.usps.com/go/TrackConfirmAction_input?qtc_tLabels1={0}" }, { name: "ICS", isMatch: function (shipType) { return shipType.startsWith('ICS'); }, linkTemplate: "http://www.icscourier.ca/online-services/tracking.aspx?trackNums={0}" }, { name: "UPS", isMatch: function (shipType) { return shipType.startsWith('UPS'); }, linkTemplate: "https://wwwapps.ups.com/WebTracking/track?track=yes&trackNums={0}" } ]; }; // #endregion // #region Page Components $.fn.dropdownHover = function () { if ('ontouchstart' in document) return this; site.hoverMenus = site.hoverMenus.add(this.parent()); return this.each(function () { if ($(this).hasClass('hover-off')) { return true; } var menu = $(this); var host = menu.parent(); var timer; function open(e) { if (!host.hasClass('open') && !menu.is(e.target)) return true; window.clearTimeout(timer); site.hoverMenus.find(':focus').blur(); site.hoverMenus.removeClass('open'); menu.attr('aria-expanded', 'true'); host.addClass('open'); } function close() { timer = window.setTimeout(function () { menu.attr('aria-expanded', 'false'); host.removeClass('open'); }, 250); } menu.hover(open); host.hover(open, close); }); }; site.dropdownClick = function (target, event) { if ($(target).attr('aria-expanded') == "true") { hijax(event); event.stopPropagation(); } }; site.lightbox = function (data, event) { var target = $(event.currentTarget); var modal = $(target.data("target")); var frame = $(target.data("target") + " iframe")[0]; frame.src = $(event.currentTarget).data("toggle"); modal.on('hide.bs.modal', function () { frame.src = ""; }) modal.modal(); }; site.slider = function () { if (window.callPhantom) return; $("#slider").bxSlider({ pause: 6000, speed: 900, randomStart: true, auto: true, autoHover: true, slideMargin: 1 }); }; // Paging var paging = { next: function (pager) { pager.moveNext(); site.scrollTop(); }, previous: function (pager) { pager.movePrevious(); site.scrollTop(); }, move: function (pager, index) { pager.moveTo(index); site.scrollTop(); }, showPage: function (index, results) { return (Math.abs(results.currentPage() - index - 1) < 4) || (results.currentPage() < 4 && index < 7) || (results.pageCount() - results.currentPage() < 4 && index > results.pageCount() - 8); } }; // #endregion // #region Utilities site.getMenuId = function (name) { if (!name) return ""; return name.replace(/ /g, '-').toLowerCase() + '-menu'; }; site.validate = function (validate, errors, submitting) { if (submitting()) return; validate(true); if (errors()) { site.firstError() return true; } else { submitting(true); validate(false); return false; } }; site.firstError = function () { var errors = $('.has-error input, .has-error textarea, .has-error .form-control, .has-warning input'); if (errors.length) { var element = $(errors[0]); core.scrollIntoView(element, function () { if (site.sizeClass() != "xs") element.focus().select(); }); } else { errors = $('.has-error'); if (errors.length) core.scrollIntoView($(errors[0])); } }; site.scrollTop = function (animate) { var element = $("body, html"); if (animate) { element.animate({ scrollTop: 0 }); } else { element.scrollTop(0); } $("#scroll-wrapper").scrollLeft(0); $("#myaccount-slider").scrollTop(0); } site.focus = function (id) { $("#" + id).focus().select(); }; site.hideMyAccountSlider = function () { var myAccountSlider = $('#myaccount-slider'); if (myAccountSlider.length && myAccountSlider[0].style.display != "none") myAccountSlider.slideToggle(); }; site.hideNavigationSlider = function () { var navigationSlider = $('#search-slider'); if (navigationSlider.length && navigationSlider[0].style.display != "none") navigationSlider.slideToggle(); }; core.onUnauthorized = function () { signIn(); }; site.defaultCountry = function () { return constants.countries.find(function () { return this.code == session.country || this.altCode == session.country; }); }; site.cleanIdText = function (str) { if (null == str || 1 > str.length) { return str; } return str.replaceAll('-', '').replaceAll(' ', '').replace(/\s*\(.*?\)\s*/g, ''); }; // #endregion // #region Cookies site.cookieBannerEnabled = function () { return !['AU', 'CO', 'NZ', 'UK', 'DE', 'FR', 'IT'].contains(session.country); }; site.noRushBannerEnabled = function () { return false; }; site.checkCookiesEnabled = function () { core.setCookie("cookieTest", true); if (!core.getCookie("cookieTest")) { $("#enableCookiesModal").modal(); } core.setCookie("cookieTest", "", -1); }; site.dismissCookieBanner = function () { core.setCookie("hideCookieBanner", true, 365); site.cookieBannerVisible(!core.getCookie("hideCookieBanner")); }; site.dismissNoRushBanner = function () { site.noRushBannerVisible(false); }; // #endregion site.navigate = function (url) { if (window.rxApp) { window.rxApp.navigate(url); } else { site.go(url); } }; // #region Hijax site.hijax = function (event) { var e = (typeof (event) == "undefined") ? window.event : event; if (typeof (e) == "undefined") return; if (e.which === 2) return true; var element = $(e.target ? e.target : e.srcElement); var href = element.attr("href"); var target = element.attr("target"); if (!href) { element = $(element).parent(); href = element.attr("href"); target = element.attr("target"); if (!href) { element = $(element).parent(); href = element.attr("href"); target = element.attr("target"); if (!href) return; } } if (href == "#") return; if (href.startsWith("mailto:") || href.startsWith("tel:") || href.startsWith("javascript:")) return true; var css = element.attr("class"); if (css && css.contains("fancybox")) { site.trackEvent("Media", href); return true; } if (!target) { site.navigate(href); if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } else { site.trackAnalytics(href); } }; var hijax = site.hijax; // #endregion // #region Google Analytics site.initiateAnalytics = function () { if (session.siteNumber == 1) { site.tracker = 'UA-60835129-5'; site.config = 'G-4TJPTBWK8F'; site.trackingSite = 'StarkeyPro'; } else if (session.siteNumber == 2) { site.tracker = 'UA-1574299-3'; site.config = 'G-JZ37258RFJ'; site.trackingSite = 'AudibelPro'; } else if (session.siteNumber == 3) { site.tracker = 'UA-12251821-1'; site.config = 'G-GFZEX0FY8S'; site.trackingSite = 'NuEarPro'; } else { site.tracker = null; site.config = null; } //Below is the tracker for rollup site.rollUpTracker = 'UA-22251115-1'; if (!window.callPhantom) { // load Telium scripts if applicable if (session.siteNumber == 1) $.getScript("//tags.tiqcdn.com/utag/starkey/starkeypro.com/prod/utag.js"); if (session.siteNumber == 2) $.getScript("//tags.tiqcdn.com/utag/starkey/audibelpro.com/prod/utag.js"); if (session.siteNumber == 3) $.getScript("//tags.tiqcdn.com/utag/starkey/nuearpro.com/prod/utag.js"); if (['UK', 'DE', 'FR', 'IT'].contains(session.country)) $.getScript( "//tags.tiqcdn.com/utag/starkey/starkeypro-eu/prod/utag.js", () => { if (!core.getCookie("isConsent")) utag.gdpr.showConsentPreferences() $(".button").click(core.setCookie("isConsent", true, 365)) } ); } } site.trackAnalytics = function (url, event) { if (window.callPhantom) return; site.initiateAnalytics(); if (["FR", "DE", "IT", "UK"].contains(session.country)) return; if (event || url.startsWith("http") || url.lastIndexOf(".") > url.lastIndexOf("/")) { site.trackEvent("Link", url); } else { window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); if (site.config) { gtag('config', site.config); gtag("event", "page_view", { 'dimension1': session.shippingAccount, 'dimension2': session.userName == null ? null : site.maskEmailAddress(session.userName), 'dimension3': session.userGuid ? session.userGuid : "(Not Logged In)" }); } if (site.tracker) { gtag("event", "page_view", { 'send_to': site.tracker, 'dimension1': session.shippingAccount, 'dimension2': session.userName == null ? null : site.maskEmailAddress(session.userName), 'dimension3': session.userGuid ? session.userGuid : "(Not Logged In)" }); } gtag("event", "page_view", { 'send_to': site.rollUpTracker, 'dimension1': session.shippingAccount, 'dimension2': session.userName == null ? null : site.maskEmailAddress(session.userName), 'dimension3': session.userGuid ? session.userGuid : "(Not Logged In)" }); }; }; site.trackEvent = function (action, label) { if (window.callPhantom) return; site.initiateAnalytics(); if (["FR", "DE", "IT", "UK"].contains(session.country)) return; if (!label) label = ''; window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); if (site.config) { gtag('config', site.config); gtag("event", action, { 'event_category': site.trackingSite, 'event_label': label, 'dimension1': session.shippingAccount, 'dimension2': session.userName == null ? null : site.maskEmailAddress(session.userName), 'dimension3': session.userGuid ? session.userGuid : "(Not Logged In)" }); } if (site.tracker) { gtag("event", action, { 'send_to': site.tracker, 'event_category': site.trackingSite, 'event_label': label, 'dimension1': session.shippingAccount, 'dimension2': session.userName == null ? null : site.maskEmailAddress(session.userName), 'dimension3': session.userGuid ? session.userGuid : "(Not Logged In)" }); } gtag("event", action, { 'send_to': site.rollUpTracker, 'event_category': site.trackingSite, 'event_label': label, 'dimension1': session.shippingAccount, 'dimension2': session.userName == null ? null : site.maskEmailAddress(session.userName), 'dimension3': session.userGuid ? session.userGuid : "(Not Logged In)" }); }; site.maskEmailAddress = function (emailAddress) { if (emailAddress.indexOf('@')) { var email_address, email_length = ''; email_address = emailAddress.split("@"); email_length = email_address[0].length; for (var i = 1; i < email_length - 1; i++) { email_address[0] = email_address[0].replace(email_address[0][i], '*'); } return email_address[0] + '@' + email_address[1]; } return emailAddress; } // #endregion // #region Site Navigation site.go = function (page, target) { if (!page) page = "/"; page = page.replace("estore/hearing-aids-and-earmolds/", "estore/"); page = page.replace("estore/accessories/", "estore/"); page = page.replace("estore/common-supplies/", "estore/"); var queryIndex = page.indexOf("?"); var path = queryIndex > 0 ? page.substring(0, queryIndex) : page; var spaPrefix = (site.prefix ? site.prefix : "") + "/prosite"; if (!page.startsWith("/") && !target && (page.startsWith("https://") || page.contains("estore.")) || page.startsWith(spaPrefix)) { site.trackAnalytics(page); window.location.href = page; } else if (target || page.startsWith("http://") || path.lastIndexOf(".") > path.lastIndexOf("/")) { site.trackAnalytics(page); if (page.contains('/audiology-on-demand') && checkSessionCountry() && window.location.href.includes(orderPrefix)) { let path = window.location.origin; let prefix = path.includes(dashOrderPrefix) ? dashOrderPrefix : orderPrefix; page = path.replace(prefix, '') + page; } window.open(page, target); } else { if (site.prefix && page.startsWith("/my-account") || page.startsWith("/login")) { page = site.prefix + page; } if (typeof (history.pushState) != "undefined" && !window.rxApp) { history.pushState(null, null, page); site.runRoute(); } else { var newUrl = "/#!{0}".format(page.substring(1)); if (page.startsWith("/government")) { newUrl = "/government/#!{0}".format(page.substring(12)); } else if (page.startsWith("/students-faculty")) { newUrl = "/students-faculty/#!{0}".format(page.substring(18)); } else if (page.startsWith("/starkey-select-network")) { newUrl = "/starkey-select-network/#!{0}".format(page.substring(24)); } else if (page.startsWith("/starkey-hearing-alliance")) { newUrl = "/starkey-hearing-alliance/#!{0}".format(page.substring(26)); } if (newUrl.endsWith("#!")) { newUrl = newUrl.substring(0, newUrl.indexOf("#!")); } else if (window.rxApp && newUrl.contains("#!")) { newUrl = newUrl.replace("#!", ""); } if (newUrl.startsWith(window.location.pathname) && window.location.href.endsWith(newUrl)) { site.runRoute(); } else { window.location.href = newUrl; } } } }; site.redirectToProfile = function (route, session) { return site.getProfileRedirectRouteOrDefault(route, session) != null; }; site.getProfileRedirectRouteOrDefault = function (route, session) { var queries = []; var restrictedRoute = route.startsWith("/my-account") && !route.startsWith("/my-account/my-profile"); if (session.country == "CO") { restrictedRoute = restrictedRoute || route.startsWith("/estore"); if (restrictedRoute && !session.patientConsent) { queries.push("missingDataAuthCO=true"); } } var profileIncomplete = !session.phoneNumber; if (restrictedRoute && profileIncomplete) queries.push("incomplete=true"); if (queries.length) return "/my-account/my-profile?{0}".format(queries.join("&")); return null; }; site.redirectToProfileOld = function (route, session) { var restrictedRoute = route.startsWith("/my-account") && !route.startsWith("/my-account/my-profile"); var profileIncomplete = !session.phoneNumber; if (session.siteNumber == 75) { restrictedRoute = restrictedRoute || route.startsWith("/estore"); profileIncomplete = profileIncomplete || !session.patientConsent; } return restrictedRoute && profileIncomplete; }; site.loadSpa = function (route) { if (site.prefix === null) { return false; } var spaPrefix = (site.prefix ? site.prefix : "") + "/prosite"; if (route.startsWith(spaPrefix)) { if (!location.pathname.startsWith(spaPrefix)) { window.location.href = route; } return true; } } site.createElementFromHTML = function (htmlString) { // Convert an html string into an HTML/DOM element. var div = document.createElement('div'); div.innerHTML = htmlString.trim(); var fchild = div.firstChild; return fchild; } site.runRoute = function (url) { site.documentReady(false); site.loading = true; site.spinnerTimer = setTimeout(function () { if (site.loading) { site.spinner = true; $("html").addClass("wait"); } }, 1000); core.abortRequests(); var route = site.getRoute(url); if (site.loadSpa(route)) { site.removeIsBusy(); return; } if (route.startsWith("/services/")) { window.location.href = route; site.removeIsBusy(); return; } var isEstore = route.startsWith("/estore") && route != "/estore/account-not-eligible"; if ((route.contains("/prosite") || isEstore || (site.sessionCookieExists && route.endsWith("/"))) && core.getCookie(loggingInCookie) != null) { core.setCookie(loggingInCookie, "false", 1); } $("#mobileSpin").fadeTo(null, 0.4); core.get("/services/session/access?route={0}", [route], function (result) { session = JSON.parse(result); if (session.InsiteToken !== undefined && session.InsiteToken !== "" && (session.billingAccount === "" || session.billingAccount === undefined)) { core.setCookie("noBillTo", "true", 1); site.logOut(); return; } if (core.getCookie("noBillTo") === "true") { site.noAccountForLoginError(true); } let isMiracleEarDomain = window.location.href.includes(miracleEarPrefix); if (site.msalError) { handleInteractionRequiredError(); } site.brandPage(); site.knockoutSession(); window.ignoreLoad = false; if (!!window.appInsights) { if (session && session.account) { if (!core.getCookie("ai_authUser")) { window.appInsights.setAuthenticatedUserContext(session.userGuid); } } else if (core.getCookie("ai_authUser")) { window.appInsights.clearAuthenticatedUserContext(); } } if (checkSessionCountry()) { let prefix = window.location.origin.includes(dashOrderPrefix) ? dashOrderPrefix : orderPrefix; site.logoRoute = window.location.origin.replace(prefix, ''); } let isOrderPrefix = window.location.href.includes(orderPrefix); let hasToRedirect = sessionStorage.getItem("hasToRedirect") === 'true'; if (checkSessionCountry()) { if ((route === '/products/product-support/manuals-literature' || route === '/products/product-support/product-faqs' || route === '/privacy-policy' || route === '/get-help/help-center' || route === '/contact-us') && isOrderPrefix === true) { resetURL(); } else if (((route === '/login' && hasToRedirect)) && isOrderPrefix === true) { resetURL(); sessionStorage.setItem("hasToRedirect", "false"); } else if (route === '/' && isOrderPrefix && !JSON.parse(result).userName) { site.go('/login?/estore'); } else if (route === '/' && isOrderPrefix && JSON.parse(result) && JSON.parse(result).userName) { const eStoreRoute = site.hasFeature('CX 2019') ? '/prosite/estore' : '/estore'; site.go(eStoreRoute); } else if (route === '/' && isMiracleEarDomain && JSON.parse(result) && JSON.parse(result).userName) { site.go('/prosite/estore'); } } if (isEstore && session && (session.country != "US" && session.estoreEligible === false)) { site.go("/estore/account-not-eligible"); } else if (!session.access) { if (session.account) { site.go("/not-available"); } else { signIn(); } } else if (session.userReview && route != "/my-account/manage-users") { site.userReview = session.userReview; site.go("/my-account/manage-users"); } else if (site.redirectToProfile(route, session)) { site.go(site.getProfileRedirectRouteOrDefault(route, session)); } else { site.trackAnalytics(route); if (session.resource.contains(".html")) { core.get(session.resource, function (html) { core.template("#page", html.replace(site.rscript, "")); html.match(site.rscript).forEach(function (script) { var s = document.createElement("script"); var s2 = site.createElementFromHTML(script); if (s2.hasAttributes()) { // 121176 - If the HTML in script has attributes, e.g "