// Copyright @ SurveyOL.com. All rights reserved.
var $sog = $sog || {};
var $sogTimeout;
// Default is false
$sog.isStorageDisabled = false;
$sog.isCookieDisabled = false;
$sog.maxLoadTime = 5000; 
$sog.enabledDebug = false;

$sog.init = function () {
    $(document).on("touchstart", function () {
        //$sog.setDebugMessage("touchstart");
        $sog.touchmoving = false;
    }).on("touchmove", function () {
        //$sog.setDebugMessage("touchmove");
        $sog.touchmoving = true;
    }).on("touchend", function () {
        //$sog.setDebugMessage("touchend");
        // Delay trigger upon moving
        setTimeout(function () {
            $sog.touchmoving = false;
        }, 200);
    });

    if ($sog.getUrlParameterByKey("sodebug") === "100") {
        $sog.enabledDebug = true;
    }
};

$sog.actions = {
    "chatgpt": "BPE", 
    "multipleLanguage": "PE",
    "googleAnalytics": "BPE", 
    "hubspot": "BPE",
    "salesforce": "E",
    "apiAccess": "PE", 
    // Question types
    "multiple-choice-type": "FBPE",
    "dropdown-type": "FBPE",
    "textbox-type": "FBPE",
    "comment-box-type": "FBPE",
    "star-rating-type": "FBPE",
    "nps-type": "FBPE",
    "image-choice-type": "BPE",
    "scale-type": "FBPE",
    "slider-type": "FBPE",
    "datetime-type": "FBPE",
    "contact-type": "FBPE",
    "textbox-list-type": "FBPE",
    "matching-type": "BPE",
    "ranking-type": "BPE",
    "cascading-menu-type": "BPE",
    "grid-multiple-choice-type": "BPE",
    "grid-dropdown-type": "BPE",
    "file-upload-type": "PE",
    "text-type": "FBPE",
    "image-type": "BPE",
    "text-ab-type": "PE",
    "image-ab-type": "PE",
    // Survey builder
    "advancedThemes": "BPE",
    "advancedEditor": "BPE",
    "customTemplates": "BPE",
    "transferSurvey": "BPE",
    "shareSurvey": "PE",
    "responseQuota": "PE",
    "exportSurvey": "PE", 
    "importSurvey": "PE", 
    // Customization & branding
    "allowAutofill": "BPE",
    "allowAutosave": "BPE",
    "addLogo": "PE",
    "removeBrandFooter": "BPE",
    "customFooter": "PE",
    "progressBar": "FBPE",
    "skipLogic": "BPE",
    "piping": "PE",
    "randomization": "PE",
    "customPages": "PE",
    "customButtons": "PE",
    "customMessages": "PE",
    "variables": "PE",
    // Distribution
    "customWebLinks": "BPEM",
    "emailCollector": "BPEM",
    "smsCollector": "BPEM",
    "addressBook": "BPE",
    "customEmails": "PE",
    "reminders": "PE",
    "websiteEmbedding": "FBPE",
    "kioskMode": "PE",
    "offlineMode": "PE",
    "whiteLabelMode": "PE",
    // Response management
    "notifications": "BPE",
    "testResponses": "PE",
    "responseTags": "PE",
    "responseComments": "PE",
    // Analytics & reporting
    "exportData": "BPE",
    "reportingValues": "BPE",
    "resultFilters": "FBPE",
    "resultAbFilters": "PE",
    "sentimentAnalysis": "BPE",
    "crossTabs": "PE"
};

$sog.embeddingModes = ["Inline", "Popup", "Left", "Right", "Bottom", "Full"];

$sog.embeddingIcons = {
    "Inline": "embedding-inline.png",
    "Popup": "embedding-popup.png",
    "Left": "embedding-left.png",
    "Right": "embedding-right.png",
    "Bottom": "embedding-bottom.png",
    "Full": "embedding-full.png"
};

$sog.containsNonLatinCodepoints = function (s) {
    return /[^\u0000-\u00ff]/.test(s);
};

$sog.getExportPdfCss = function (content) {
    var hasNonLatin = $sog.containsNonLatinCodepoints(content);
    var css = $sog.exportPdfCss.replace("{{font}}", !hasNonLatin ? "\"Helvetica Neue\", Helvetica, Arial, sans-serif, Helvetica !important" : "SimSun");
    return css;
};

$sog.exportPdfCss = "body, div { font-family: {{font}}; font-size: 16px; line-height: 1.428571429; } " +
    "tr { page-break-inside: avoid; } td { padding: 5px; } thead { display: table-header-group; } tfoot { display: table-row-group; }" +
    "h1 { padding-top: 20px !important;  font-size: 40px !important; text-transform: uppercase; text-align: center !important; }" +
    "h2 { padding-top: 20px !important;  font-size: 20px !important; text-align: center !important; }" +
    "h3 { text-align: center; display: block !important; font-size: 20px; margin: 0px !important; padding: 10px 0 20px 0; } " +
    ".bold { font-weight: bold !important; } .font24 { font-size: 24px !important;} .font30 { font-size: 30px !important;} .font36 { font-size: 36px !important;} .font48 { font-size: 48px !important;}" +
    ".padding5 { padding: 5px !important; } .padding10 { padding: 10px !important; } .padding20 { padding: 20px !important; } .padding-r10 { padding-right: 10px !important; }" +
    ".padding-t5 { padding-top: 5px !important; } .padding-t20 { padding-top: 20px !important; } .padding-h10 { padding-left: 10px !important; padding-right: 10px !important; }" +
    ".padding-h15 { padding-left: 15px !important; padding-right: 15px !important; } .padding-h35 { padding-left: 35px !important; padding-right: 35px !important; }" +
    ".padding-r15 { padding-right: 15px !important; } .padding-b10 { padding-bottom: 10px !important; } .padding-b15 { padding-bottom: 15px !important; }" +
    ".margin-v5 { margin-top: 5px !important; margin-bottom: 5px !important;} .margin-v15 { margin-top: 15px !important; margin-bottom: 15px !important;} .padding-l30 {padding-left: 30px !important;}" +
    ".section-header { font-size: 18px; }" +
    ".answer-head { padding-top: 20px !important; }" +
    ".so-gray { background-color: gray; color: #fff; }" +
    ".so-inner-block { padding: 10px 0; }" +
    ".no-print { display: none; }" +
    ".inline-block { display: inline-block; }" +
    ".relative { position: relative; }" +
    ".absolute { position: absolute; }" +
    ".stats-on-right { position: absolute; display: inline-block; padding: 10px; }" +
    ".grid-col-label, .grid-row-cell { text-align:center; padding: 5px; } .grid-report-table { width: 100%; }" +
    ".so-tag-green { background-color: green; color: #fff; font-size: 12px; padding: 0 3px; margin-right: 5px; display: inline-block; }" +
    ".so-tag-orange { background-color: orange; color: #fff; font-size: 12px; padding: 0 3px; margin-right: 5px; display: inline-block; }" +
    ".so-tag-red { background-color: #ff6f61; color: #fff; font-size: 12px; padding: 0 3px; margin-right: 5px; display: inline-block; }" +
    ".image-box { position: relative; border: solid 1px lightgray; background-color: #eee; width: 280px; height: 280px; text-align: center; }" +
    ".image-box-i { border: 0px !important; background-color: transparent !important; width: 80px; height: 80px; }" +
    ".image-preview { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; max-width: 278px; max-height: 278px; }" +
    ".image-i { max-width: 48px !important; max-height: 48px !important; }" +
    ".crosstab-table { border-collapse: collapse; width: 100%; border: solid 1px gray;}" +
    ".crosstab-table th, .crosstab-table td { border: solid 1px gray; min-width: 30px; padding: 5px;}" +
    ".block-normal { padding: 10px; } .valign-top { vertical-align: top; } .align-center { text-align: center !important; } .align-right { text-align: right !important; }" + 
    ".nps-cell { width: 9%;min-width: 20px;height: 40px;border: 1px solid gray;text-align: center; } .nps-table, .nps-label { width: 750px;}" +
    ".page-break-inside-avoid { page-break-inside: avoid; } .page-break-before-always { page-break-before: always; }" + 
    "input[type=text], input[type=password] { width: 750px;margin: 0px;padding: 11px;height: 46px; } textarea { padding: 11px;width: 750px; height: 92px;}" +
    ".fa.icon24 { font-size: 24px !important;text-align: center; } .fa-2 { font-size: 3em !important; width: 50px; text-align: center;}" +
    ".choice-ticker {position: absolute;top: 4px;left: 5px;} .choice-type { font-size: 16px;position: relative;}";

$sog.exportWordCss = "body { font-family: \"Helvetica Neue\", Helvetica, Arial, sans-serif !important; font-size: 14px; line-height: 1.428571429; } " +
    "div { padding-top: 5px; padding-bottom: 5px; } td { padding: 5px; }" +
    "thead { display: table-header-group; } tfoot { display: table-row-group; } tr { page-break-inside: avoid; }" +
    "h1 { margin-top: 0px !important; font-size: 30px !important; text-transform: uppercase; text-align: center !important; }" +
    "h2 { margin-top: 0px !important; font-size: 20px !important; text-align: center !important; }" +
    "h3 { text-align: center; display: block !important; font-size: 20px; margin: 0px !important;}" +
    ".padding-r15 { padding-right: 15px !important; } .padding-b15 { padding-bottom: 15px !important; }" +
    ".margin-v15 { margin-top: 15px !important; margin-bottom: 15px !important;}" +
    "#titleArea { margin-bottom: 50px; }" +
    ".overview-section, .question { margin-bottom: 50px; }" +
    ".section-header { font-size: 18px; } .padding 10 { padding: 10px !important; }.so-gray { background-color: gray; color: #fff; }" +
    ".grid-col-label, .grid-row-cell { text-align:center; padding: 5px; } h3 { text-align:center; }" +
    ".crosstab-table { border-collapse: collapse; width: 100%; border: solid 1px gray;}" +
    ".crosstab-table th, .crosstab-table td { border: solid 1px gray; min-width: 30px; padding: 5px;}";

$sog.invalidUrlPatterns = ["[^\"]+amazonaws.com[^\"]+", "[^\"]+googleapis.com[^\"]+", "[^\"]+appspot.com[^\"]+", "[^\"]+oraclecloud.com[^\"]+"];

$sog.isAbType = function (type) {
    if (type === "text-ab-type" || type === "image-ab-type") {
        return true;
    } else {
        return false;
    }
};

$sog.canEmbedIntoEmail = function (type) {
    if (type === "multiple-choice-type" || type === "nps-type" || type === "star-rating-type") {
        return true;
    } else {
        return false;
    }
};

$sog.isBot = function () {
    var isBot = /bot|crawler|spider|crawling|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|facebookexternalhit/i.test(navigator.userAgent);
    return isBot;
};

$sog.allowAction = function (allowed) {
    var msg;
    var accountType = $sog.getAccountType() !== null ? $sog.getAccountType() : $sog.sources.free;
    if (allowed.indexOf(accountType.charAt(0)) === -1) {
        if (allowed.indexOf("B") > -1) {
            msg = $sog.messages.basicRequired;
        } else if (allowed.indexOf("P") > -1) {
            msg = $sog.messages.proRequired;
        } else if (allowed.indexOf("E") > -1) {
            msg = $sog.messages.enterpriseRequired;
        }
    } else if (allowed.indexOf("M") > -1 && accountType.indexOf("Trial") > -1) {
        msg = $sog.messages.paidAccountRequired;
    }
    return msg;
};

$sog.compactDisplay = function (value, maxLength) {
    var v = value.length > maxLength ? value.substring(0, maxLength - 3) + "..." : value;
    return v;
};

$sog.getWordArray = function (s) {
    var wordArray = [];
    if (s) {
        s = s.replace(/(^\s*)|(\s*$)/gi, ""); //exclude  start and end white-space
        s = s.replace(/[ ]{2,}/gi, " "); //2 or more space to 1
        s = s.replace(/\n /, "\n"); //exclude newline with a start spacing
        wordArray = s.split(' ').filter(function (str) { return str !== ""; });
    }
    return wordArray;
};

$sog.countWords = function (s) {
    var count = $sog.getWordArray(s).length;
    return count;
};

$sog.getEllipsedPhrase = function (s, topN) {
    var wordArray = $sog.getWordArray(s);
    var newPhrase = wordArray.length > topN ? wordArray.slice(0, topN).join(" ") + "..." : s;
    return newPhrase;
};

$sog.countExtraPoints = function (s) {
    var count = 0;
    if (s) {
        if ($sog.countWords(s) > $sog.sources.wordsPerPoint) {
            count = Math.round($sog.countWords(s) / $sog.sources.wordsPerPoint) - 1;
        }
    }
    return count;
};

$sog.decodeHtml = function (html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
};

$sog.fillValues = function (source, key, value) {
    if (source) {
        var matches = source.match("{{" + key + "}}", "gi");
        if (matches) {
            for (var i = 0; i < matches.length; i++) {
                source = source.replace(matches[i], value);
            }
        }
    }
    return source;
};

$sog.getUrlParameterByKey = function (key, path) {
    key = key.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var rgx = new RegExp("[\\?&]" + key + "=([^&#]*)", "gi");
    var matched = path !== undefined ? rgx.exec(path) : rgx.exec(location.search);
    var dataValue = matched === null ? "" : decodeURIComponent(matched[1].replace(/\+/gi, " "));
    return dataValue;
};

$sog.getUrlParas = function () {
    var paras = [];
    window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
        paras.push({ name: key, value: value });
      }
    );
    return paras;
};

$sog.getUrlWithoutDomain = function () {
    return window.location.pathname + window.location.search + window.location.hash;
};

$sog.getDomain = function () {
    return window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
};

$sog.getUrlDomain = function (url) {
    var urlLocation = new URL(url);
    return urlLocation.protocol + '//' + urlLocation.hostname + (urlLocation.port ? ':' + urlLocation.port : '');
};

$sog.getUrlWithoutParameter = function () {
    return window.location.protocol + '//' + window.location.host + window.location.pathname;
};

$sog.getUrlFileName = function (url, length) {
    var fileName = url.substring(url.lastIndexOf('/') + 1);
    if (length !== undefined && fileName.length > length) {
        if (fileName.lastIndexOf(".") > 0) {
            var ext = fileName.substring(fileName.lastIndexOf('.'), fileName.length);
            var main = fileName.substring(0, fileName.lastIndexOf('.'));
            if (length - ext.length > 0) {
                main = main.substring(0, length - ext.length - 2);
            }
            fileName = main + ".." + ext;
        } 
        fileName = fileName.substring(0, length);
    }
    return fileName;
};

$sog.getPropertyLength = function (jsonData) {
    var keys = [];
    $.each(jsonData, function (key, value) {
        keys.push(key);
    });
    return keys.length;
};

$sog.filterControl = function (control, value) {
    var c;
    for (var i = 0; i < control.length; i++) {
        if (control.eq(i).val() === value) {
            c = control.eq(i);
            break;
        }
    }
    return c;
};

$sog.toBoolean = function (value) {
    if (typeof value == "boolean") {
        return value;
    } else {
        if (value && (value.toLowerCase() == "true" || value == 1 || value == "1")) {
            return true;
        } else {
            return false;
        }
    }
};

$sog.getEditableContent = function ($this) {
    return '<span style="color:gray;">' + $this.attr("placeholder") + '</span>';
};

$sog.hasValidContent = function ($this) {
    return $.trim($this.html()) != $sog.getEditableContent($this) && $this.html().length > 0;
};

$sog.setUnclaimedSurvey = function (guid, title) {
    var unclaimedSurveyJson = { guid: guid, title: title };
    unclaimedSurvey = JSON.stringify(unclaimedSurveyJson);
    $sog.setSessionStorageItem($sog.storageKeys.unclaimedSurvey, unclaimedSurvey);
};

$sog.setLastSaveTime = function () {
    $sog.setSessionStorageItem($sog.storageKeys.lastSaveTime, new Date());
};

$sog.getLastSaveTime = function () {
    return $sog.getSessionStorageItem($sog.storageKeys.lastSaveTime);
};

$sog.setLastUnsavedResponse = function (unsavedResponse) {
    $sog.setLocalStorageItem($sog.storageKeys.lastUnsavedResponse, unsavedResponse);
};

$sog.getLastUnsavedResponse = function () {
    return $sog.getLocalStorageItem($sog.storageKeys.lastUnsavedResponse);
};

$sog.removeLastUnsavedResponse = function () {
    $sog.removeLocalStorageItem($sog.storageKeys.lastUnsavedResponse);
};

$sog.setLastUnsavedQuestion = function (unsavedQuestion) {
    $sog.setSessionStorageItem($sog.storageKeys.lastUnsavedQuestion, JSON.stringify(unsavedQuestion));
};

$sog.getLastUnsavedQuestion = function () {
    return $sog.getSessionStorageItem($sog.storageKeys.lastUnsavedQuestion);
};

$sog.removeLastUnsavedQuestion = function () {
    $sog.removeSessionStorageItem($sog.storageKeys.lastUnsavedQuestion);
};

$sog.setLastErrorPage = function () {
    $sog.setSessionStorageItem($sog.storageKeys.lastErrorPage, window.location.href);
};

$sog.getLastErrorPage = function () {
    return $sog.getSessionStorageItem($sog.storageKeys.lastErrorPage);
};

$sog.getUnclaimedSurvey = function () {
    var unclaimedSurvey = $sog.getSessionStorageItem($sog.storageKeys.unclaimedSurvey);
    if (unclaimedSurvey) {
        return JSON.parse(unclaimedSurvey);
    } else {
        return null;
    }
};

$sog.getUnclaimedSurveyGuid = function () {
    var survey = $sog.getUnclaimedSurvey();
    return survey ? survey.guid : null;
};

$sog.getUnclaimedSurveyTitle = function () {
    var survey = $sog.getUnclaimedSurvey();
    return survey ? survey.title : null;
};

$sog.removeUnclaimedSurvey = function () {
    $sog.removeSessionStorageItem($sog.storageKeys.unclaimedSurvey);
};

$sog.getBrowserMemory = function () {
    var browserMemory = $sog.getLocalStorageItem($sog.storageKeys.browserMemory);
    if (browserMemory) {
        browserMemoryJson = JSON.parse(browserMemory);
    } else {
        // Whether the Remember Me is checked
        browserMemoryJson = { isLocalProfile: true };
    }
    return browserMemoryJson;
};

$sog.getAccountProfile = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    if (browserMemoryJson.isLocalProfile) {
        return this.getLocalProfile();
    } else {
        return this.getSessionProfile();
    }
};

$sog.getLocalProfile = function () {
    var localProfile = $sog.getLocalStorageItem($sog.storageKeys.accountProfile);
    var localProfileJson = {};
    if (localProfile) {
        localProfileJson = JSON.parse(localProfile);
    }
    return localProfileJson;
};

$sog.getSessionProfile = function () {
    var sessionProfile = $sog.getSessionCookieItem($sog.storageKeys.accountProfile);
    var sessionProfileJson = {};
    if (sessionProfile) {
        sessionProfileJson = JSON.parse(sessionProfile);
    }
    return sessionProfileJson;
};

$sog.getAccountColors = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.colors;
};

$sog.getAccountAddOns = function () {
    accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.addOns;
};

$sog.accountHasThankYouEmailEnabled = function () {
    var enabled = false;
    var addOns = $sog.getAccountAddOns();
    if (addOns && addOns.indexOf($sog.sources.thankYouEmail) >= 0) {
        enabled = true;
    }
    return enabled;
};

$sog.accountHasSalesforceEnabled = function () {
    var enabled = false;
    var addOns = $sog.getAccountAddOns();
    if (addOns && addOns.indexOf($sog.sources.salesforce) >= 0) {
        enabled = true;
    }
    return enabled;
};

$sog.accountHasSalesforceRefreshToken = function () {
    accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.hasSalesforceRefreshToken;
};

$sog.accountHasHubspotRefreshToken = function () {
    accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.hasHubspotRefreshToken;
};

$sog.getAccountTeamUsers = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.teamUsers;
};

$sog.getBrowserCoupon = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    return browserMemoryJson.coupon;
};

$sog.getBrowserEmail = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    return browserMemoryJson.email;
};

$sog.getBrowserUnregisteredEmail = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    return browserMemoryJson.registered ? null : browserMemoryJson.email;
};

$sog.getBrowserAccountType = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    var type = browserMemoryJson.accountType;
    //TODO: retire trial in sources
    if (type === $sog.sources.trial || !type) {
        type = $sog.sources.basicTrial;
    }
    return type;
};

$sog.getBrowserSocialPortal = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    return browserMemoryJson.socialPortal;
};

$sog.getBrowserLinkedInState = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    return browserMemoryJson.linkedInState;
};

$sog.getAccountEmail = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.email;
};

$sog.getAccountFirstName = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.firstName;
};

$sog.getAccountLastName = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.lastName;
};

$sog.getAccountCompanyName = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.companyName;
};

$sog.getAccountIndustry = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.industry;
};

$sog.getAccountTimezone = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.timezone;
};

$sog.getAccountType = function () {
    var accountProfileJson = $sog.getAccountProfile();
    if (accountProfileJson.type === undefined || accountProfileJson.type === $sog.sources.trial) {
        accountProfileJson.type = $sog.sources.basicTrial;
    }
    return accountProfileJson.type;
};

$sog.isProOrAboveType = function () {
    var type = $sog.getAccountType();
    return type === $sog.sources.pro || type === $sog.sources.enterprise;
};

$sog.getAccountExpirationHours = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.expirationHours;
};

$sog.getAccountProvider = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.provider;
};

$sog.getAccountGuid = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.guid;
};

$sog.getAccountIsSub = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.isSub;
};

$sog.getAccountDesignDetailedView = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.designDetailedView;
};

$sog.getAccountSettings = function () {
    var accountProfileJson = $sog.getAccountProfile();
    var allowShare = accountProfileJson.allowShare != null ?
        accountProfileJson.allowShare : true;
    var allowTransfer = accountProfileJson.allowTransfer != null ?
        accountProfileJson.allowTransfer : true;
    var settingsJson = { allowShare: allowShare, allowTransfer: allowTransfer };
    return settingsJson;
};

$sog.getUuid = function () {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;

    // rfc4122, version 4 form
    var r;
    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';
    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
            r = 0 | Math.random() * 16;
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
    }
    return uuid.join('');
};

$sog.getAccountToken = function () {
    var accountProfileJson = $sog.getAccountProfile();
    return accountProfileJson.token;
};
$sog.getEmailsJson = function (recipients) {
    var json = [];
    var emails = recipients.split(/,|;| /);
    for (var i = 0; i < emails.length; i++) {
        if ($sog.validateEmail($.trim(emails[i]))) {
            json.push({ email: $.trim(emails[i]) });
        }
    }
    return json;
};
$sog.getPhoneNumbersJson = function (recipients) {
    var json = [];
    var phoneNumbers = recipients.split(/,|;| /);
    for (var i = 0; i < phoneNumbers.length; i++) {
        if ($sog.validateUSPhoneNumber2($.trim(phoneNumbers[i]))) {
            json.push({ phone: $.trim(phoneNumbers[i]) });
        }
    }
    return json;
};

$sog.hasInvalidEmail = function (recipients) {
    var flag = false;
    var emails = recipients.split(/,|;| /);
    for (var i = 0; i < emails.length; i++) {
        if (emails[i] != "" && !$sog.validateEmail($.trim(emails[i]))) {
            flag = true;
            break;
        }
    }
    return flag;
};

$sog.hasAccountEmail = function (recipients) {
    var flag = false;
    var emails = recipients.split(/,|;| /);
    for (var i = 0; i < emails.length; i++) {
        if ($.trim(emails[i]) == $sog.getAccountEmail()) {
            flag = true;
            break;
        }
    }
    return flag;
};

$sog.nullToEmpty = function (content) {
    if (content === null || content === undefined) {
        content = "";
    }
    return content;
};

$sog.removeAccountProfile = function () {
    $sog.removeSessionStorageItem($sog.storageKeys.accountProfile);
    $sog.removeLocalStorageItem($sog.storageKeys.accountProfile);
    $sog.removeSessionCookieItem($sog.storageKeys.accountProfile);
};

$sog.removeBrowserMemory = function () {
    $sog.removeLocalStorageItem($sog.storageKeys.browserMemory);
};

$sog.removeBrowserCoupon = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.coupon = null;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.removeBrowserEmail = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.email = null;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.removeBrowserAccountType = function () {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.accountType = null;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.setTransferredMessage = function (message) {
    $sog.setSessionStorageItem($sog.storageKeys.transferredMessage, message);
};

$sog.getTransferredMessage = function () {
    return $sog.getSessionStorageItem($sog.storageKeys.transferredMessage);
};

$sog.removeTransferredMessage = function () {
    $sog.removeSessionStorageItem($sog.storageKeys.transferredMessage);
};

$sog.setTempUrl = function (url) {
    $sog.setSessionStorageItem($sog.storageKeys.tempUrl, url);
};

$sog.getTempUrl = function () {
    return $sog.getSessionStorageItem($sog.storageKeys.tempUrl);
};

$sog.removeTempUrl = function () {
    $sog.removeSessionStorageItem($sog.storageKeys.tempUrl);
};

$sog.setBrowserMemory = function (isLocalProfile, email, registered) {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.isLocalProfile = isLocalProfile;
    browserMemoryJson.email = email;
    browserMemoryJson.registered = registered;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.setBrowserCoupon = function (coupon) {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.coupon = coupon;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.setBrowserEmail = function (email, registered) {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.email = email;
    browserMemoryJson.registered = registered;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.setBrowserAccountType = function (type) {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.accountType = type;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.setBrowserSocialPortal = function (portal) {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.socialPortal = portal;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.setBrowserLinkedInState = function (state) {
    var browserMemoryJson = $sog.getBrowserMemory();
    browserMemoryJson.linkedInState = state;
    $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
};

$sog.setAccountProfile = function (account, token, provider) {
    var browserMemoryJson = $sog.getBrowserMemory();
    if (browserMemoryJson.isLocalProfile) {
        if (!$sog.isCookieDisabled) {
            $sog.removeSessionCookieItem($sog.storageKeys.accountProfile);
        }
        var localProfileJson = $sog.getLocalProfile();
        localProfileJson = $sog.setAccountProfileAttributes(localProfileJson, account, token, provider);
        $sog.setLocalStorageItem($sog.storageKeys.accountProfile, JSON.stringify(localProfileJson));
    } else {
        if (!$sog.isStorageDisabled) {
            $sog.removeLocalStorageItem($sog.storageKeys.accountProfile);
        }
        var sessionProfileJson = $sog.getSessionProfile();
        sessionProfileJson = $sog.setAccountProfileAttributes(sessionProfileJson, account, token, provider);
        $sog.setSessionCookieItem($sog.storageKeys.accountProfile, JSON.stringify(sessionProfileJson));
    }
    if (account && account.email) {
        // Set email in browser memory
        browserMemoryJson.email = account.email;
        $sog.setLocalStorageItem($sog.storageKeys.browserMemory, JSON.stringify(browserMemoryJson));
    }
};

$sog.setAccountProfile2 = function (profileJson) {
    var browserMemoryJson = $sog.getBrowserMemory();
    if (browserMemoryJson.isLocalProfile) {
        $sog.setLocalStorageItem($sog.storageKeys.accountProfile, JSON.stringify(profileJson));
    } else {
        $sog.setSessionCookieItem($sog.storageKeys.accountProfile, JSON.stringify(profileJson));
    }
};

$sog.getAccountResultFilters = function (surveyGuid) {
    var resultFilters;
    var profileJson = $sog.getAccountProfile();
    if (profileJson.resultRules !== undefined && profileJson.resultRules.length > 0) {
        for (var i = 0; i < profileJson.resultRules.length; i++) {
            if (profileJson.resultRules[i].surveyGuid === surveyGuid) {
                resultFilters = profileJson.resultRules[i].resultFilters;
                break;
            }
        }
    }
    return resultFilters;
};

$sog.setAccountResultFilters = function (surveyGuid, resultFilters) {
    var profileJson = $sog.getAccountProfile();
    var exists = false;
    if (profileJson.resultRules === undefined) {
        profileJson.resultRules = [];
    }
    if (profileJson.resultRules.length > 0) {
        for (var i = 0; i < profileJson.resultRules.length; i++) {
            if (profileJson.resultRules[i].surveyGuid === surveyGuid) {
                profileJson.resultRules[i].resultFilters = resultFilters;
                break;
            }
        }
    }
    if (!exists) {
        profileJson.resultRules.push({ surveyGuid: surveyGuid, resultFilters: resultFilters });
    }
    $sog.setAccountProfile2(profileJson);
};

$sog.setAccountHubspotRefreshToken = function (hasRefreshToken) {
    var profileJson = $sog.getAccountProfile();
    profileJson.hasHubspotRefreshToken = hasRefreshToken;
    $sog.setAccountProfile2(profileJson);
};

$sog.setAccountToken = function (token) {
    $sog.setAccountProfile(null, token, null);
};

$sog.setAccountProvider = function (provider) {
    $sog.setAccountProfile(null, null, provider);
};

$sog.setAccountProfileAttributes = function (profileJson, account, token, provider) {
    if (account) {
        if (account.email) {
            profileJson.email = account.email;
        }
        if (account.guid) {
            profileJson.guid = account.guid;
        }
        if (account.profile.allowShare !== null && account.profile.allowTransfer !== null) {
            profileJson.allowShare = account.profile.allowShare;
            profileJson.allowTransfer = account.profile.allowTransfer;
        }
        if (account.profile) {
            profileJson.designDetailedView = account.profile.designDetailedView;
            profileJson.addOns = account.profile.addOns;
            profileJson.hasSalesforceRefreshToken = account.profile.hasSalesforceRefreshToken;
            profileJson.hasHubspotRefreshToken = account.profile.hasHubspotRefreshToken;
        }
        if (account.firstName !== null && account.lastName !== null) {
            profileJson.firstName = account.firstName;
            profileJson.lastName = account.lastName;
        }
        if (account.companyName !== null) {
            profileJson.companyName = account.companyName;
        }
        if (account.industry !== null) {
            profileJson.industry = account.industry;
        }
        if (account.timezone) {
            profileJson.timezone = parseFloat(account.timezone);
        }
        if (account.type) {
            profileJson.type = account.type;
            profileJson.expirationHours = null;
        }
        if (account.expirationHours !== null) {
            profileJson.expirationHours = account.expirationHours;
        }
        if (account.teamUsers) {
            profileJson.teamUsers = account.teamUsers;
        }
        if (account.isSub) {
            profileJson.isSub = account.isSub;
        }
    }
    if (token) {
        profileJson.token = token;
    }
    if (provider !== null && provider !== undefined) {
        profileJson.provider = provider;
    }
    return profileJson;
};

$sog.setPreferences = function (key, value) {
    var prefs = $sog.getLocalStorageItem($sog.storageKeys.preferences);
    var prefsJson = prefs === null ? {} : JSON.parse(prefs);
    prefsJson[key] = value;
    $sog.setLocalStorageItem($sog.storageKeys.preferences, JSON.stringify(prefsJson));
};

$sog.getPreferences = function (key) {
    var prefs = $sog.getLocalStorageItem($sog.storageKeys.preferences);
    return prefs !== null ? JSON.parse(prefs)[key] : null;
};

$sog.refactorContent = function (content) {
    content = $sog.removeInvalidUrls(content);
    content = $sog.setCompanyName(content);
    content = $sog.addNfRel(content);
    return content;
};

$sog.removeInvalidUrls = function (content) {
    if (content) {
        for (var i = 0; i < $sog.invalidUrlPatterns.length; i++) {
            var rgx = new RegExp("(href=\")" + $sog.invalidUrlPatterns[i] + "(\")", "gi");
            content = content.replace(rgx, "$1#$2" + " title=\"Invalid URL\"");
        }
    }
    return content;
};

$sog.addNfRel = function (content) {
    var ctn = $("<div/>").html(content);
    ctn.find("a").each(function () {
        $(this).attr("rel", "noopener noreferrer nofollow");
    });
    return ctn.html();
};

$sog.setCompanyName = function (content) {
    if (content) {
        var companyName = $sog.getAccountCompanyName();
        if (companyName) {
            content = content.replace(/{{CompanyName\|[^}]+}}/g, companyName);
        } else {
            var p = new RegExp(/{{CompanyName\|(.*?)}}/g);
            var m = p.exec(content);
            if (m !== null) {
                var match1 = m[1];
                content = content.replace(p, match1);
            }
        }
    }
    return content;
};

$sog.setLanding = function (templateSurveyGuid, surveyGuid, collectorGuid) {
    var landingJson = { templateSurveyGuid: templateSurveyGuid, surveyGuid: surveyGuid, collectorGuid: collectorGuid };
    $sog.setLocalStorageItem($sog.storageKeys.landing, JSON.stringify(landingJson));
};

$sog.getLanding = function () {
    var landing = $sog.getLocalStorageItem($sog.storageKeys.landing);
    if (landing) {
        return JSON.parse(landing);
    } else {
        return null;
    }
};

$sog.addColorToProfile = function (color) {
    var added = false;
    var browserMemoryJson = $sog.getBrowserMemory();
    if (browserMemoryJson.isLocalProfile) {
        if (!$sog.isStorageDisabled) {
            $sog.removeSessionStorageItem($sog.storageKeys.accountProfile);
        }
        var localProfileJson = $sog.getLocalProfile();
        if (localProfileJson.colors == undefined) {
            localProfileJson.colors = [];
        }
        if (localProfileJson.colors.indexOf(color) == -1) {
            localProfileJson.colors.push(color);
            added = true;
        }
        $sog.setLocalStorageItem($sog.storageKeys.accountProfile, JSON.stringify(localProfileJson));
    } else {
        if (!$sog.isStorageDisabled) {
            $sog.removeLocalStorageItem($sog.storageKeys.accountProfile);
        }
        var sessionProfileJson = $sog.getSessionProfile();
        if (sessionProfileJson.colors == undefined) {
            sessionProfileJson.colors = [];
        }
        if (sessionProfileJson.colors.indexOf(color) == -1) {
            sessionProfileJson.colors.push(color);
            added = true;
        }
        $sog.setSessionStorageItem($sog.storageKeys.accountProfile, JSON.stringify(sessionProfileJson));
        return added;
    }
};

$sog.storageKeys = {
    "accountProfile": "accountProfile",
    "browserMemory": "browserMemory", // Local
    "landing": "landing", // Local
    "lastErrorPage": "lastErrorPage", // Local
    "lastSaveTime": "lastSaveTime", // Last save attempt time for auto-save
    "lastUnsavedQuestion": "lastUnsavedQuestion", // Session
    "lastUnsavedResponse": "lastUnsavedResponse", // Local
    "offlineResponses": "offlineResponses{key}", // Local
    "preferences": "preferences", // Local
    "transferredMessage": "transferredMessage", // Session
    "unclaimedSurvey": "unclaimedSurvey", // Session
    "logKeys": "logKeys",
    "tracingGroupKey": "tracingGroupKey" // Group key for tracing
};

$sog.choices = [
    "Yes, No",
    "Female, Male",
    "Extremely satisfied, Very satisfied, Somewhat satisfied, Not so satisfied, Not at all satisfied",
    "Extremely well, Very well, Somewhat well, Not so well, Not at all well",
    "Excellent, Above average, Average, Below average, Poor",
    "Strongly agree, Agree, Neither agree nor disagree, Disagree, Strongly disagree",
    "Very easy, Easy, Neither easy nor difficult, Difficult, Very difficult",
    "Under 18, 18 - 24, 25 - 34, 35 - 44, 45 - 54, 55 - 64, 65 or above",
    "Less than high school diploma, High school diploma or equivalent, Some college but no degree, Associate degree, Bachelor's degree, Post-graduate degree",
    "True, False",
    "Yes, No but considered, No and not considered",
    "Always, Often, Sometimes, Rarely, Never",
    "Very likely, Likely, Neither likely nor unlikely, Unlikely, Very unlikely",
    "A great deal, A lot, A moderate amount, A little, Not at all",
    "Exceeded expectations, Met expectations, Below expectations",
    "Serious problem, Moderate problem, Minor problem, Not at all a problem",
    "Single, Married, Separated, Windowed, Divorced",
    "Esstential, High priority, Medium priority, Low priority, Not a priority",
    "Definitely need, Probably need, Neutral, Probably don't need, Definitely don't need",
    "Major affect, Moderate affect, Neutral, Minor affect, No affect",
    "Strongly favor, Somewhat favor, Neutral, Somewhat oppose, Strongly oppose",
    "Very desirable, Desirable, Neutral, Undesirable, Very undesirable",
    "Extremely convenient, Very convenient, Somewhat convenient, Not so convenient, Not at all convenient",
    "Extremely helpful, Moderately helpful, Somewhat helpful, Not so helpful, Not at all helpful",
    "Extremely concerned, Moderately concerned, Somewhat concerned, Slightly concerned, Not at all concerned",
    "Extremely important, Moderately important, Somewhat important, Slightly important, Not at all important",
    "Very comfortable, Somewhat comfortable, Neither comfortable nor uncomfortable, Somewhat uncomfortable, Very uncomfortable",
    "Absolutely appropriate, Appropriate, Neutral, Inappropriate, Absolutely inappropriate",
    "Perfectly acceptable, Acceptable, Neutral, Unacceptable, Totally unacceptable",
    "Much better, Better, About the same, Worse, Much worse",
    "Extremely effective, Very effective, Somewhat effective, Not so effective, Not at all effective",
    "White, Black or African American, Hispanic or Latino, Asian, American Indian or Alaska Native, Native Hawaiian or other Pacific Islander, Another race",
    "Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday",
    "January, February, March, April, May, June, July, August, September, October, November, December",
    "Under $25,000, Between $25,000 and $49,999, Between $50,000 and $74,999, Between $75,000 and $99,999, Between $100,000 and $150,000, Over $150,000",
    "Word of mouth, Radio, TV, Email, Mailing, Search engine, Social media"
];

$sog.choicesSpecial = {
    "US States": "Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, District of Columbia, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina, South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming",
    "US State Abbreviations": "AK, AL, AR, AZ, CA, CO, CT, DC, DE, FL, GA, HI, IA, ID, IL, IN, KS, KY, LA, MA, MD, ME, MI, MN, MO, MS, MT, NC, ND, NE, NH, NJ, NM, NV, NY, OH, OK, OR, PA, RI, SC, SD, TN, TX, UT, VA, VT, WA, WI, WV, WY"
};

$sog.imageChoices = [
    "Thumb up, Thumb down",
    "Sad face, Normal face, Happy face"
];

$sog.abuseWords = ["payment", "invoice", "remittance", "password"];

$sog.messages = {
    "accountInformationSaved": "The account information changes have been saved.",
    "anonymousResponsesSaved": "The anonymous responses setting has been saved.",
    "autofillSaved": "The autofill option has been turned {0}.",
    "autosaveSaved": "The autosave option has been turned {0}.",
    "atLeastOneChoice": "Please enter at least 1 choice.",
    "atLeastOneElement": "Please enter at least 1 field.",
    "atLeastOneQuestion": "Please select at least 1 question.",
    "atLeastOneRow": "Please enter at least 1 row.",
    "atLeastTwoChoices": "Please enter at least 2 choices.",
    "atLeastOneColumn": "Please enter at least 1 column.",
    "atLeastTwoColumns": "Please enter at least 2 columns.",
    "atLeastTwoPages": "Please select at least 2 pages.",
    "atLeastTwoQuestions": "Please select at least 2 questions.",
    "basicExpired": "Your Basic subscription has expired. You need to re-subscribe or upgrade to continue.",
    "basicRequired": "A basic or higher level subscription is required.",
    "collectorDeleted": "The collector has been deleted.",
    "colorThemeSaved": "Your new color theme has been saved.",
    "colorThemeDeleted": "The theme has been deleted.",
    "confidenceInclusive": "Inconclusive. More responses are required to get a conclusive confidence level.",
    "confidenceSuggestion": "More responses are suggested.",
    "contactsDeleted": "All your contacts have been deleted.",
    "convertedToFree": "Your account has been converted to a FREE account.",
    "canNotDeletedNonEmptyCollector": "The collector contains responses, and cannot be deleted.",
    "canNotTransferToSelf": "You cannot transfer the survey to yourself.",
    "canNotSkipToSamePage": "You cannot skip to the same page.",
    "choiceRndSaved": "The choice randomization options have been saved.",
    "closedAccount": "Account is permanently closed.",
    "copiedToClipboard": "The link has been copied to clipboard. You can use it to distribute your survey.",
    "copiedInstallationCodes": "The installation codes has been copied to clipboard. You can paste it to the desired place of your web page.",
    "couldNotLoadImage": "The image could not be loaded.",
    "couldNotSignInWithSocialAccount": "It appears you couldn't sign in with {0}. Please use another way to sign in.",
    "couponApplied": "Your coupon {0} has been applied!",
    "csvExported": "Your CSV file is ready.",
    "customizedButtonsSaved": "Customized buttons have been saved.",
    "customizedMessagesSaved": "Customized messages have been saved.",
    "createResponses": "Results can be found under \"Results\".", 
    "dateRangeIsRequired": "Please specify the date range.",
    "declinedEmail": "The email address you entered is not eligible for verification.",
    "defaultFileTypeMessage": "Only {0} files are supported.",
    "defaultInvalidFileTypeMessage": "Only PDF, DOCX, DOC, XLSX, XLS, PNG, JPG, JPEG, GIF files are supported.",
    "deletingTestResponses": "Deleting test responses",
    "disallowTransfer": "Sorry but the account you entered does not allow transferred surveys.",
    "disallowShare": "Sorry but the account you entered does not allow shared surveys.",
    "displayFormatSaved": "The display format has been saved.",
    "displayOptionsSaved": "The display options have been saved.",
    "duplicateEmail": "Looks like you've got duplicate emails.",
    "dailyEmailLimitReached": "You have reached your daily sending limit of {0} emails.",
    "monthlyEmailLimitReached": "You have reached your monthly sending limit of {0} emails.",
    "dailySmsLimitReached": "You have reached your daily sending limit of {0} SMS messages.",
    "monthlySmsLimitReached": "You have reached your monthly sending limit of {0} SMS messages.",
    "emailInvitationScheduled": "{0} will be scheduled.",
    "emailInvitationSent": "{0} will be added to a queue for sending out shortly.",
    "emailInvitationSubject": "We want your opinion",
    "emailInvitationMessage": "We are conducting a survey and we want your opinion. Please click the button below to start the survey. Your participation would be appreciated.",
    "emailSaved": "The email change has been saved.",
    "emailSendingFrozen": "You have 25+ opted out or bounced email invitations within 48 hours. Your sending capability is temporarily frozen.",
    "emailUsed": "The entered email was used by another contact.",
    "emptyTitle": "Every survey needs a title.",
    "emptyAuthorName": "Please enter your name.",
    "emptyOrganizationName": "Please enter your organization's name.",
    "emptyName": "Please enter the name.",
    "emptyWebsiteAddress": "Please enter your website address.",
    "endDateEarlierThanStartDate": "The End Date must come after the Start Date.",
    "endPagesSaved": "Customized end pages have been saved.",
    "enterpriseExpired": "Your Enterprise subscription has expired. You need to re-subscribe to continue.",
    "enterpriseRequired": "An enterprise subscription is required.",
    "estimatedTime": "Estimated Completion: around {0}",
    "exceedsMaxFileUploads": "Please select no more than 9 files.",
    "excelExported": "If your browser couldn't open .XLSX excel files, share it with Microsoft Excel or Google Numbers.",
    "existsEmail": "Account exists. Please sign in.",
    "expiredCouponCode": "Your coupon code is expired.",
    "filesDragTip": "or drag and drop files here",
    "filesDropTip": "drop files here!",
    "footerBrandSaved": "The brand footer changes has been saved.",
    "footerSaved": "The custom footer changes has been saved.",
    "generatingResponses": "Generating responses",
    "hasDuplicateChoices": "Looks like you've got some duplicate choices.",
    "incorrectEmail": "Please enter a correct email address.",
    "incorrectPassword": "Please enter a correct password.",
    "invalidAbTestFilter": "Sorry, this survey doesn't contain any A/B test.",
    "invalidAuthentication": "It appears that your action may not be considered legitimate.",
    "invalidCondition": "Please provide a valid condition for {0}.",
    "invalidCouponCode": "Your coupon code is invalid.",
    "invalidEmail": "That email address appears invalid.",
    "invalidErrorMessage": "Please enter a valid error message.",
    "invalidFileFormat": "Please upload a file with a valid format.",
    "invalidFileType": "Please upload a file in a valid format.",
    "invalidFileSize": "Please upload a file less than 10MB.",
    "invalidHyperlink": "Please remove the invalid hyperlinks from the file.",
    "invalidImageType": "Please upload an image in png, jpg, jpeg, or gif format.",
    "invalidImageSize": "Please upload an image less than 5MB.",
    "invalidCharacterRange": "Please enter a valid character count range.",
    "invalidCompanyName": "Please enter your organization name.",
    "invalidIndustry": "Please enter your industry.",
    "invalidInvitationDate": "Please pick your invitation date & time.",
    "invalidFirstName": "Please enter your first name.",
    "invalidLastName": "Please enter your last name.",
    "invalidNumber": "Please enter a number less than or equal to 1000.",
    "invalidPhoneNumber": "The phone number must be in the format 212-123-4567. US phone numbers only.",
    "invalidCommentTitle": "Please enter your comment title.",
    "invalidInputLength": "Your input length is too long.",
    "invalidKioskRedirectionSeconds": "Please enter a valid number of seconds on the end page before redirection.",
    "invalidKioskInactivityMinutes": "Please enter a valid number of inactive minutes before resetting.",
    "invalidLink": "The provided link is invalid or expired. Redirected to the home page.",
    "invalidLinkWithNewUrl": "The provided link is invalid or expired. Did you mean: <a href=\"{0}\">{0}</a>.",
    "invalidNumberRange": "Please enter a valid number range.",
    "invalidPassword": "At least 8 characters including 1 letter and 1 number.",
    "invalidQuestionText": "Please enter your question.",
    "invalidQuestionLength": "Your question should not exceed 3500 characters.",
    "invalidRecipients": "Please pick your recipients.",
    "invalidReminderDate": "Please pick your reminder date.",
    "invalidRndChoiceQuestion": "Please add questions to your survey first.",
    "invalidRndQuestion": "Please add more questions to your survey first.",
    "invalidRndPage": "Please add more pages to your survey first.",
    "invalidText": "Please enter your text.",
    "invalidTextLength": "Your text should not exceed 3500 characters.",
    "invalidAbTextLength": "Your text length is too long.",
    "invalidTitle": "Please enter your title.",
    "invalidLabel": "Please enter the $type label.",
    "invalidOtherLabel": "Please enter the label for the \"Other\" answer option.",
    "invalidImageUrl": "Please enter a valid URL address for the image.",
    "invalidImageUrlOrUpload": "Please upload an image or enter a valid URL address.",
    "invalidAbTest": "Each variation should be different.",
    "invalidAlreadyTakenRedirectionSeconds": "Please enter a valid number of seconds on the Already Taken page before redirection.",
    "invalidAlreadyTakenRedirectUrl": "Please enter a valid redirect URL for the Already Taken page.",
    "invalidClosedRedirectionSeconds": "Please enter a valid number of seconds on the Closed page before redirection.",
    "invalidClosedRedirectUrl": "Please enter a valid redirect URL for the Closed page.",
    "invalidCode": "The code you entered is invalid.",
    "invalidDisqualificationRedirectionSeconds": "Please enter a valid number of seconds on the Disqualification page before redirection.",
    "invalidDisqualificationRedirectUrl": "Please enter a valid redirect URL for the Disqualification page.",
    "invalidPercentageNumber": "The percentage should be between 0 and 100.",
    "invalidPercentageTotal": "The total percentage should be 100.",
    "invalidSpot": "Please choose a new spot.",
    "invalidQuotaReachedRedirectionSeconds": "Please enter a valid number of seconds on the Quota Reached page before redirection.",
    "invalidQuotaReachedRedirectUrl": "Please enter a valid redirect URL for the Quota Reached page.",
    "invalidUrl": "Please enter a valid web address.",
    "invalidUserFirstName": "Please enter first name.",
    "invalidUserLastName": "Please enter last name.",
    "invalidUserRole": "Please select a role.",
    "invalidWebLink": "At least 7 characters. Can contain letters, numbers, -(dash) or _(underscore).",
    "invalidWordRange": "Please enter a valid word count range.",
    "invalidMinMaxNumbers": "The minimum number must be less than the maximum number.",
    "invalidLargeStepNumber": "The step number is too large.",
    "invalidNonPositiveStepNumber": "The step number must be greater than 0.",
    "invalidThankYouRedirectionSeconds": "Please enter a valid number of seconds on the Thank You page before redirection.",
    "invalidThankYouRedirectUrl": "Please enter a valid redirect URL for the Thank You page.",
    "invalidThankYouRecipientEmail": "Please enter a valid recipient email.",
    "invalidThankYouEmailSubject": "Please enter your email subject.",
    "invalidThankYouEmailBody": "Please enter your email body.",
    "invitationAccepted": "You have accepted the team invitation.",
    "invitationMessageMaxLen": "Message should contain no more than 10,000 characters.",
    "isAccountEmail": "Please enter an email address other than yours.",
    "jsonExported": "Your JSON file is ready.",
    "languageSaved": "The default language been saved.",
    "linkExpired": "Sorry but your link has expired. Please contact us at contact@surveyol.com.",
    "loaderMaxTime": "the request takes {0}+ seconds.",
    "loading": "Loading",
    "noEmailChanges": "Looks like you didn't want to change your email address?",
    "notificationsSaved": "The notifications have been saved.",
    "missingFileTypes": "Please specify the allowed file types.",
    "missingInvalidFileTypeMessage": "Please enter the error message.",
    "multiChoiceSymbolTypeSaved": "The multiple choice symbol type has been saved.",
    "notExistsEmail": "Account doesn't exist. Please create your account.",
    "textboxStyleSaved": "The textbox & comment box style has been saved.",
    "pageRndSaved": "The page randomization options have been saved.",
    "pageDescriptionMaxLen": "Description should contain no more than 3000 characters.",
    "pageTitleMaxLen": "Title should contain no more than 100 characters.",
    "paidAccountRequired": "A paid account is required.",
    "processing": "Processing",
    "proRequired": "A pro or higher level subscription is required.",
    "questionRndSaved": "The question randomization options have been saved.",
    "questionsAdded": "The questions have been added to your survey.",
    "questionSkipped": "This question was skipped.",
    "quoteRequested": "Thank you for your submission. We'll contact you soon.",
    "registeredAccount": "Sorry but this email address has another registered account.",
    "responseDeleted": "The response has been deleted.",
    "responsesDeleted": "The responses have been cleared.",
    "resetPasswordEmailSent": "We just sent you an email. If you don't receive anything within 3 minutes, first check your spam folder and then try again.",
    "saving": "Saving",
    "designViewSaved": "The design view change has been saved.",
    "settingsSaved": "The setting changes have been saved.",
    "smsInvitationMessage": "{{sender}} sent you a survey. Please click the link.",
    "smsQuotaReached": "{0} will be sent. You have reached your {1} daily SMS sending limit.",
    "smsInvitationScheduled": "{0} will be scheduled.",
    "smsInvitationSent": "{0} will be added to a queue for sending out shortly.",
    "storageDisabled": "The localStorage/sessionStorage & cookies are disabled or unsupported.",
    "surveyTitleMaxLen": "Title should contain no more than 100 characters.",
    "pdfExported": "If your browser couldn't open .PDF files, share it with Adobe Acrobat Reader.",
    "planExpirationDays": "Your {0} will expire in {1} days.",
    "planExpirationHour": "Your {0} will expire in 1 hour.",
    "planExpirationHours": "Your {0} will expire in {1} hours.",
    "pptExported": "Your PowerPoint file is ready. View on computers for the best user experience.",
    "proExpirationDays": "Your Pro subscription will expire in {0} days.",
    "proExpirationHour": "Your Pro subscription will expire in 1 hour.",
    "proExpirationHours": "Your Pro subscription will expire in {0} hours.",
    "proExpired": "Your Pro subscription has expired. You need to re-subscribe to continue.",
    "questionMoved": "Your question has been moved.",
    "responseQuotaSaved": "The response quota have been saved.",
    "sameSpot": "Please choose a spot other than your current one.",
    "stillPrefix": "Still ",
    "suggested": "Suggested: ",
    "surveyIncompleteToBeClaimed": "Your survey is ready. Just sign in or create your free account to continue.",
    "surveyDeleted": "Did you delete the survey by accident?",
    "surveyCopied": "You have successfully copied the survey.",
    "surveyIncentive": "By taking the survey, you would receive a gift card.",
    "surveyInstructions": "We are conducting a survey and we want your opinion. Please click the button below to start the survey. Your participation would be appreciated.",
    "surveyShared": "You have successfully shared the survey.",
    "surveyTransferred": "You have successfully transferred the survey.",
    "surveyImported": "You have successfully imported the survey.",
    "templateDeleted": "You have successfully deleted the template.",
    "templatePublished": "You have successfully published the template.",
    "templateSaved": "You have successfully saved the template.",
    "testResponsesDeleted": "The test responses have been cleared.",
    "testResponsesCreated": "The test responses have been created.",
    "titleUsed": "The entered title was used.",
    "trialConvertedToFree": "Your account has been converted to a FREE account. Please sign in again.",
    "trialExtended": "Your free trial has been extended. Please sign in again.",
    "trialExpired": "Your free trial has expired. You need to subscribe to continue.",
    "unregisteredEmail": "The email address {0} has not been registered.",
    "undeletableColorTheme": "The color theme is used by {0} and cannot be deleted.",
    "unmatchedPasswords": "The passwords don't match.",
    "urlUsed": "The entered URL was used.",
    "viewResults": "View Results",
    "viewDashboard": "Dashboard",
    "wordExported": "If your document is opened in protected view, embedded images may not display properly. You can click on \"Enable Editing\" in Microsoft Word to fix it."    
};

$sog.positions = {
    "left": "left",
    "right": "right",
    "top": "top",
    "bottom": "bottom",
    "behind": "behind",
    "none": "none",
    "both": "both",
    "all": "all",
    "cover": "cover",
    "repeat": "repeat"
};
$sog.mimeTypes = {
    "PDF": "pdf",
    "DOCX": "wordprocessing",
    "DOC": "msword",
    "XLSX": "spreadsheet",
    "XLS": "ms-excel",
    "PNG": "png",
    "JPG": "jpeg",
    "JPEG": "jpeg",
    "GIF": "gif",
    "SVG": "svg+xml"
};
$sog.sources = {
    "abTest": "abTest",
    "activateAccount": "Activate your account",
    "additionalComments": "Additional Comments:",
    "admin": "Admin",
    "all": "all",
    "alpha": "alpha",
    "address": "Address",
    "analyst": "Analyst",
    "annual": "Annual",
    "moveQuestion": "Move Questions",
    "autoFetchInterval": 15000,
    "autoFetchTimeout": 600000,
    "avg": "avg",
    "average": "Average:",
    "basic": "Basic",
    "basicSubscription": "Basic Subscription",
    "basicTrial": "Basic Trial",
    "bounced": "Bounced",
    "box": "box",
    "button": "Button",
    "buttonsMessages": "Buttons & Message",
    "buy": "Buy",
    "center": "center",
    "classic": "classic",
    "collectors": "Collectors",
    "colorThemes": "Colors & Fonts",
    "compact": "compact",
    "completeAllCaps": "COMPLETE",
    "complete": "Complete",
    "completed": "Completed",
    "column": "Column",
    "coupon": "coupon",
    "clicked": "Clicked",
    "clientApi": "clientApi",
    "clientApiVariableType": "clientApiVariableType",
    "clientApiVariableValue": "clientApiVariableValue",
    "collaborator": "collaborator",
    "collaborators": "collaborators",
    "colorThemeUsedCount": "Used by {0} surveys",
    "colorThemeUsedCountSingle": "Used by 1 survey",
    "created": "Created",
    "createSurvey": "Create Survey",
    "createCustomerSatisfactionSurvey": "Create customer satisfaction survey",
    "defaultStar": 5,
    "design": "Design",
    "delete": "Delete",
    "disabled": "Disabled",
    "disqualificationPage": "D",
    "disqualified": "DISQUALIFIED",
    "download": "Download",
    "downloadAndShare": "Download & Share",
    "done": "Done",
    "editDesign": "Design Editor",
    "email": "email",
    "emails": "emails",
    "emailCollector": "Email",
    "emailCollectorNonAnonymous": "Off, include emails and browser/IP information",
    "emailInvitationButtonText": "Begin Survey",
    "emailInvitationButtonColor": "#009473",
    "embeddingButtonText": "Begin Survey",
    "embeddingButtonColor": "#009473",
    "enabled": "Enabled",
    "exit": "Exit",
    "existsEmail": "existsEmail",
    "endOfSurvey": "E",
    "enterprise": "Enterprise",
    "enterpriseMinUserCount": 2,
    "enterpriseMaxUserCount": 26,
    "enterpriseSubscription": "Enterprise subscription",
    "enterpriseTrial": "Enterprise Trial",
    "extremelyLikely": "Extremely likely",
    "features": "Features",
    "filterByResponseStatus": "Filter by Response Status:",
    "filterBySurveyCollector": "Filter by Collector:",
    "filterByQuestionAnswers": "Filter by Question & Answers:",
    "filterByTimePeriod": "Filter by Time Period:",
    "filterByAbTest": "Filter by A/B Test",
    "findMore": "Find more",
    "flip": "flip",
    "free": "Free",
    "freeTrial": "free trial",
    "fullAccess": "Full Access",
    "generator": "generator",
    "hide": "Hide",
    "highest": "Highest:",
    "hubspot": "hubspot",
    "imagePlaceholder": "[Image]",
    "imageThumbMaxWidth": 240,
    "imageThumbMaxHeight": 120,
    "imagePreviewMaxWidth": 280,
    "imagePreviewMaxHeight": 280,
    "incomplete": "INCOMPLETE",
    "inDays": "inDays",
    "inline": "Inline",
    "lastChanceToUndelete": "Last Chance to Undelete",
    "left": "left",
    "line": "line",
    "lowest": "Lowest:",
    "maxCascadingLevel": 4,
    "maxFileUploads": 9,
    "maxLowNps": 6,
    "maxNps": 10,
    "maxQuestionLength": 3500,
    "median": "Median:",
    "mobileSmsCollector": "Mobile SMS",
    "mobileSmsCollectorNonAnonymous": "Off, include phone #s and browser/IP information",
    "modified": "Modified",
    "monthly": "Monthly",
    "message": "message",
    "messages": "messages",
    "mostComprehensiveAnswer": "Likely most comprehensive:",
    "mostRecentAnswer": "Most recent:",
    "multipleComments": "There are {0} comments.",
    "multipleResponses": "There are {0} responses.",
    "next": "Next",
    "now": "now",
    "npsStart": "How likely is it that you would recommend ",
    "npsEnd": " to a friend or colleague?",
    "noneApplicableQuestions": "There are no applicable questions.",
    "notAtAllLikely": "Not at all likely",
    "notForProfit": "notForProfit",
    "number": "number",
    "off": "off",
    "offlineStorageSizeMaximum": 2000000,
    "onDate": "onDate",
    "oneQuestionAtaTime": "oneQuestionAtaTime",
    "oneQuestionPerScreen": "oneQuestionPerScreen",
    "opened": "Opened",
    "optedOut": "Opted Out",
    "otherDropdown": "OtherDropdown",
    "otherPleaseSpecify": "Other (please specify)",
    "othersWithStar": "Others*",
    "password": "password",
    "page": "page",
    "pageDescriptionMaxLen": 3000,
    "pages": "pages",
    "pageTitleMaxLen": 100,
    "pageType": "P",
    "perMonth": " per month",
    "pick": "Pick",
    "pleaseSpecify": "Please specify.",
    "pleaseSelect": "Please select",
    "popular": "Popular",
    "preview": "Preview",
    "previous": "Previous",
    "primaryAdmin": "Primary Admin",
    "pro": "Pro",
    "proSubscription": "Pro subscription",
    "proTrial": "Pro Trial",
    "purchase": "Purchase",
    "question": "question",
    "questionAnswers": "questionAnswers",
    "questions": "questions",
    "randomize": "randomize",
    "randomization": "Randomization",
    "readSecondsPerPoint": 7,
    "reCaptchaOpenToken": "6LfcrvsmAAAAAIBWU3x6KXdqW-iB9XWRe9NlW3Cq",
    "response": "response",
    "responses": "responses",
    "responseStatus": "responseStatus",
    "reminded": "Reminded",
    "reminder": "reminder",
    "right": "right",
    "rotate": "rotate",
    "row": "Row",
    "salesforce": "salesforce",
    "sample": "Sample",
    "saved": "Saved",
    "scheduled": "Scheduled",
    "sent": "Sent",
    "selected": "selected",
    "sendMoreInvitations": "Upgrade to send more invitations",
    "show": "Show",
    "singleComment": "There is 1 comment.",
    "singleResponse": "There is only 1 response so far.",
    "skipHide": "skipHide",
    "skipLogic": "Branching/Skip Logic",
    "skipTo": "skipTo",
    "small": "small",
    "smallSampleSize": 30,
    "suggestedSampleSize": 100,
    "surveyTitleMaxLen": 100,
    "standard": "standard",
    "standardUser": "Standard User",
    "star": "star",
    "stars": "stars",
    "started": "Started",
    "subscriberSince": "{0} subscriber since {1}",
    "survey": "survey",
    "surveyCollector": "surveyCollector",
    "surveyol": "surveyol",
    "surveys": "surveys",
    "surveyFyiDisplay": "www.survey.fyi",
    "timePeriod": "timePeriod",
    "trialExpiresOn": "Free trial expires on {0}",
    "template": "Template",
    "testResponseGenerator": "Test Response Generator",
    "text": "Text",
    "textQuestionLabel": "Please enter text",
    "thanked": "Thanked",
    "thankYou": "Thank You",
    "thankYouEmail": "thankYouEmail",
    "timeMinute": "{0} minute",
    "timeMinutes": "{0} minutes",
    "timeSeconds": "{0} seconds",
    "thumbPreview": "Thumb Preview",
    "token": "token",
    "trial": "Trial",
    "undelete": "Undelete",
    "undo": "Undo",
    "upgrade": "Upgrade",
    "unlimited": "Unlimited",
    "upload": "upload",
    "url": "url",
    "urlParameters": "URL Parameters",
    "urlVariable": "urlVariable",
    "urlVariableType": "urlVariableType",
    "urlVariableValue": "urlVariableValue",
    "us": "United States",
    "variables": "Variables",
    "viewSubscription": "View subscription",
    "viewDesign": "View Design",
    "viewOnly": "View Only",
    "viewPricing": "View Pricing",
    "webhooks": "Webhooks",
    "webhookValue": "webhookValue",
    "webLinkCollector": "Web Link",
    "websiteEmbeddingCollector": "Website Embedding",
    "wordsPerPoint": 25
};

$sog.iconList = [
    "https://surveyol.blob.core.windows.net/icons/smiling-face-9-48.png",
    "https://surveyol.blob.core.windows.net/icons/muddled-48.png",
    "https://surveyol.blob.core.windows.net/icons/sad-13-48.png",
    "https://surveyol.blob.core.windows.net/icons/thumb-up-48.png",
    "https://surveyol.blob.core.windows.net/icons/thumb-down-48.png",
    "https://surveyol.blob.core.windows.net/icons/sign-yes-48.png",
    "https://surveyol.blob.core.windows.net/icons/sign-no-48.png",
    "https://surveyol.blob.core.windows.net/icons/flag-48.png",
    "https://surveyol.blob.core.windows.net/icons/flag-bw-48.png",
    "https://surveyol.blob.core.windows.net/icons/switch-on-48.png",
    "https://surveyol.blob.core.windows.net/icons/switch-off-48.png",
    "https://surveyol.blob.core.windows.net/icons/star-48.png",
    "https://surveyol.blob.core.windows.net/icons/star-alt-48.png",
    "https://surveyol.blob.core.windows.net/icons/flower-48.png",
    "https://surveyol.blob.core.windows.net/icons/snow-flake-48.png",
    "https://surveyol.blob.core.windows.net/icons/heart-48.png",
    "https://surveyol.blob.core.windows.net/icons/love-22-48.png",
    "https://surveyol.blob.core.windows.net/icons/heart-broken-4-48.png",
    "https://surveyol.blob.core.windows.net/icons/key-48.png",
    "https://surveyol.blob.core.windows.net/icons/keyring-48.png",
    "https://surveyol.blob.core.windows.net/icons/lock-48.png",
    "https://surveyol.blob.core.windows.net/icons/lock-open-48.png",
    "https://surveyol.blob.core.windows.net/icons/shield-48.png",
    "https://surveyol.blob.core.windows.net/icons/shield-no-48.png",
    "https://surveyol.blob.core.windows.net/icons/shield-yes-48.png",
    "https://surveyol.blob.core.windows.net/icons/sign-left-48.png",
    "https://surveyol.blob.core.windows.net/icons/sign-right-48.png",
    "https://surveyol.blob.core.windows.net/icons/sign-up-48.png",
    "https://surveyol.blob.core.windows.net/icons/sign-down-48.png",
    "https://surveyol.blob.core.windows.net/icons/user-female-48.png",
    "https://surveyol.blob.core.windows.net/icons/user-female-alt-48.png",
    "https://surveyol.blob.core.windows.net/icons/user-male-48.png",
    "https://surveyol.blob.core.windows.net/icons/user-male-alt-48.png",
    "https://surveyol.blob.core.windows.net/icons/bullish-48.png",
    "https://surveyol.blob.core.windows.net/icons/bearish-48.png",
    "https://surveyol.blob.core.windows.net/icons/biotech-1-48.png",
    "https://surveyol.blob.core.windows.net/icons/biohazard-1-48.png",
    "https://surveyol.blob.core.windows.net/icons/empty_filter-48.png",
    "https://surveyol.blob.core.windows.net/icons/filled_filter-48.png",
    "https://surveyol.blob.core.windows.net/icons/settings-86-48.png",
    "https://surveyol.blob.core.windows.net/icons/engineering-3-48.png",
    "https://surveyol.blob.core.windows.net/icons/services-9-48.png",
    "https://surveyol.blob.core.windows.net/icons/in_transit-48.png",
    "https://surveyol.blob.core.windows.net/icons/shipped-1-48.png",
    "https://surveyol.blob.core.windows.net/icons/picture-46-48.png",
    "https://surveyol.blob.core.windows.net/icons/gallery-17-48.png",
    "https://surveyol.blob.core.windows.net/icons/organization-5-48.png",
    "https://surveyol.blob.core.windows.net/icons/library-90-48.png",
    "https://surveyol.blob.core.windows.net/icons/folder-223-48.png",
    "https://surveyol.blob.core.windows.net/icons/opened_folder-48.png",
    "https://surveyol.blob.core.windows.net/icons/left-13-48.png",
    "https://surveyol.blob.core.windows.net/icons/right-12-48.png",
    "https://surveyol.blob.core.windows.net/icons/expand-2-48.png",
    "https://surveyol.blob.core.windows.net/icons/collapse-48.png",
    "https://surveyol.blob.core.windows.net/icons/previous-8-48.png",
    "https://surveyol.blob.core.windows.net/icons/next-17-48.png",
    "https://surveyol.blob.core.windows.net/icons/sms-9-48.png",
    "https://surveyol.blob.core.windows.net/icons/mms-48.png",
    "https://surveyol.blob.core.windows.net/icons/comments-15-48.png",
    "https://surveyol.blob.core.windows.net/icons/about-5-48.png",
    "https://surveyol.blob.core.windows.net/icons/info-57-48.png",
    "https://surveyol.blob.core.windows.net/icons/data_sheet-48.png",
    "https://surveyol.blob.core.windows.net/icons/grid-3-48.png",
    "https://surveyol.blob.core.windows.net/icons/bar_chart-48.png",
    "https://surveyol.blob.core.windows.net/icons/area_chart-48.png",
    "https://surveyol.blob.core.windows.net/icons/scatter_plot-48.png",
    "https://surveyol.blob.core.windows.net/icons/heat_map-48.png",
    "https://surveyol.blob.core.windows.net/icons/workflow-48.png",
    "https://surveyol.blob.core.windows.net/icons/mind_map-48.png",
    "https://surveyol.blob.core.windows.net/icons/timeline-2-48.png",
    "https://surveyol.blob.core.windows.net/icons/list-14-48.png",
    "https://surveyol.blob.core.windows.net/icons/flow_chart-48.png",
    "https://surveyol.blob.core.windows.net/icons/parallel_tasks-48.png",
    "https://surveyol.blob.core.windows.net/icons/genealogy-48.png",
    "https://surveyol.blob.core.windows.net/icons/advertising-4-48.png",
    "https://surveyol.blob.core.windows.net/icons/speaker-28-48.png",
    "https://surveyol.blob.core.windows.net/icons/search-189-48.png",
    "https://surveyol.blob.core.windows.net/icons/calendar-128-48.png",
    "https://surveyol.blob.core.windows.net/icons/conference_call-48.png",
    "https://surveyol.blob.core.windows.net/icons/calculator-114-48.png",
    "https://surveyol.blob.core.windows.net/icons/synchronize-4-48.png",
    "https://surveyol.blob.core.windows.net/icons/graduation_cap-48.png",
    "https://surveyol.blob.core.windows.net/icons/bookmark-28-48.png",
    "https://surveyol.blob.core.windows.net/icons/support-9-48.png",
    "https://surveyol.blob.core.windows.net/icons/sports_mode-48.png",
    "https://surveyol.blob.core.windows.net/icons/contacts-56-48.png",
    "https://surveyol.blob.core.windows.net/icons/music-223-48.png",
    "https://surveyol.blob.core.windows.net/icons/electronics-1-48.png",
    "https://surveyol.blob.core.windows.net/icons/start-9-48.png",
    "https://surveyol.blob.core.windows.net/icons/clapperboard-4-48.png",
    "https://surveyol.blob.core.windows.net/icons/alarm_clock-48.png",
    "https://surveyol.blob.core.windows.net/icons/love-21-48.png",
    "https://surveyol.blob.core.windows.net/icons/cool-17-48.png",
    "https://surveyol.blob.core.windows.net/icons/anger-1-48.png",
    "https://surveyol.blob.core.windows.net/icons/cold-2-48.png",
    "https://surveyol.blob.core.windows.net/icons/cold-3-48.png",
    "https://surveyol.blob.core.windows.net/icons/angel-18-48.png",
    "https://surveyol.blob.core.windows.net/icons/devil-15-48.png",
    "https://surveyol.blob.core.windows.net/icons/ninja-7-48.png",
    "https://surveyol.blob.core.windows.net/icons/monster-10-48.png",
    "https://surveyol.blob.core.windows.net/icons/uncomfortable-48.png",
    "https://surveyol.blob.core.windows.net/icons/cancel-19-48.png"];

$sog.enContents = {
    "done": "Done",
    "previous": "Previous",
    "next": "Next",
    "exit": "Exit",
    "invalidAnswer": "The answer is invalid.",
    "requiredAnswer": "This question requires an answer.",    
    "thankYouPage": "Thank you for taking this survey.",
    "disqualificationPage": "Thanks for your time! We're sorry you don't qualify for this survey.",
    "alreadyTakenPage": "You have already taken this survey.",
    "closedPage": "This survey is currently closed. Please contact the author of this survey for further assistance.",
    "quotaReachedPage": "Thanks for your time! We're sorry the maximum number of responses has been met.",
    "npsStart": "How likely is it that you would recommend ",
    "npsEnd": " to a friend or colleague?",
    "thisCompany": "this company",
    "thisBrand": "this brand",
    "thisProduct": "this product",
    "thisService": "this service",
    "npsLeftLabel": "Not at all likely",
    "npsRightLabel": "Extremely likely"
};

$sog.esContents = {
    "done": "Listo",
    "previous": "Ant.",
    "next": "Sig.",
    "exit": "Salida",
    "invalidAnswer": "La respuesta no es válida.",
    "requiredAnswer": "Esta pregunta requiere una respuesta.",
    "thankYouPage": "Gracias por realizar esta encuesta.",
    "disqualificationPage": "¡Gracias por tu tiempo! Lamentamos que no califique para esta encuesta.",
    "alreadyTakenPage": "Ya ha realizado esta encuesta.",
    "closedPage": "Este estudio está actualmente cerrado. Comuníquese con el autor de esta encuesta para obtener más ayuda.",
    "quotaReachedPage": "¡Gracias por tu tiempo! Lamentamos que se haya alcanzado el número máximo de respuestas.",
    "npsStart": "¿Qué posibilidades hay de que recomiende ",
    "npsEnd": " a un amigo o colega?",
    "thisCompany": "esta compañía",
    "thisBrand": "esta marca",
    "thisProduct": "este producto",
    "thisService": "este servicio",
    "npsLeftLabel": "Nada probable",
    "npsRightLabel": "extremadamente probable"
};

$sog.frContents = {
    "done": "Terminé",
    "previous": "Préc.",
    "next": "Suiv.",
    "exit": "Sortie ",
    "invalidAnswer": "La réponse est invalide.",
    "requiredAnswer": "Cette question nécessite une réponse.",
    "thankYouPage": "Merci d'avoir répondu à cette enquête.",
    "disqualificationPage": "Merci pour votre temps! Nous sommes désolés que vous ne soyez pas admissible à cette enquête.",
    "alreadyTakenPage": "Vous avez déjà répondu à cette enquête.",
    "closedPage": "Cette enquête est actuellement fermée. Veuillez contacter l'auteur de cette enquête pour obtenir de l'aide.",
    "quotaReachedPage": "Merci pour votre temps! Désolé, le nombre maximum de réponses a été atteint.",
    "npsStart": "Quelle est la probabilité que vous recommandiez ",
    "npsEnd": " à un ami ou à un collègue?",
    "thisCompany": "cette entreprise",
    "thisBrand": "cette marque",
    "thisProduct": "ce produit",
    "thisService": "ce service",
    "npsLeftLabel": "Pas du tout probable",
    "npsRightLabel": "Extrêmement probable"
};

$sog.deContents = {
    "done": "Fertig",
    "previous": "Zurück",
    "next": "Weiter",
    "exit": "Ausgang",
    "invalidAnswer": "Die Antwort ist ungültig.",
    "requiredAnswer": "Diese Frage erfordert eine Antwort.",
    "thankYouPage": "Vielen Dank, dass Sie an dieser Umfrage teilgenommen haben.",
    "disqualificationPage": "Vielen Dank für Ihre Zeit! Es tut uns leid, dass Sie sich nicht für diese Umfrage qualifizieren.",
    "alreadyTakenPage": "Sie haben diese Umfrage bereits durchgeführt.",
    "closedPage": "Diese Umfrage ist derzeit geschlossen. Bitte kontaktieren Sie den Autor dieser Umfrage für weitere Unterstützung.",
    "quotaReachedPage": "Vielen Dank für Ihre Zeit! Es tut uns leid, dass die maximale Anzahl von Antworten erreicht wurde.",
    "npsStart": "Wie wahrscheinlich ist es, dass Sie ",
    "npsEnd": " einem Freund oder Kollegen empfehlen?",
    "thisCompany": "diese Firma",
    "thisBrand": "diese Marke",
    "thisProduct": "dieses Produkt",
    "thisService": "dieser Service",
    "npsLeftLabel": "Überhaupt nicht wahrscheinlich",
    "npsRightLabel": "Sehr wahrscheinlich"
};


$sog.ctContents = {
    "done": "完成",
    "previous": "上一頁",
    "next": "下一頁",
    "exit": "退出",
    "invalidAnswer": "答案無效。",
    "requiredAnswer": "這個問題需要一個答案。",
    "thankYouPage": "感謝您參加這項調查。",
    "disqualificationPage": "謝謝你的時間！很抱歉，您沒有參加此調查的資格。",
    "alreadyTakenPage": "您已經參加了這項調查。",
    "closedPage": "這項調查目前已關閉。請與該調查的管理員聯繫以獲取進一步的幫助。",
    "quotaReachedPage": "謝謝你的時間！很抱歉，我們已達到最大的答複數。",
    "npsStart": "您向朋友或同事推薦",
    "npsEnd": "的可能性有多大?",
    "thisCompany": "這家公司",
    "thisBrand": "這個品牌",
    "thisProduct": "這個產品",
    "thisService": "這個服務",
    "npsLeftLabel": "完全不可能",
    "npsRightLabel": "極有可能"
};

$sog.csContents = {
    "done": "完成",
    "previous": "上一页",
    "next": "下一页"
};

$sog.itContents = {
    "done": "Fine",
    "previous": "Prec.",
    "next": "Succ."
};

$sog.poContents = {
    "done": "Concluído",
    "previous": "Anter.",
    "next": "Próx."
};

$sog.ruContents = {
    "done": "Готово",
    "previous": "Предыд.",
    "next": "След."
};

$sog.arContents = {
    "done": "تم",
    "previous": "السابق",
    "next": "التالي"
};

$sog.tips = {
    "clientApiVariableValue": "Optional - the default value if the API connection timed out.",
    "collaboration": "To add collaborators, go to the Dashboard page and follow the instructions.",
    "flip": "For example, \"1,2,3,4\" can be flipped to \"4,3,2,1\".",
    "imageSmallView": "Select this option to limit the overall format size",
    "rotate": "For example, \"1,2,3,4\" can be rotated to \"2,3,4,1\", then to \"3,4,1,2\".",
    "variableName": "Contains only letters and numbers. No spaces.",
    "urlVariableType": "Used when the value comes from URL parameters.",
    "clientApiVariableType": "Used when the value comes from a client API URL.",
    "urlVariableValue": "Optional - the default value if the value didn't get passed from URL.",
    "webhookValue": "Optional - the default value if the value didn't get passed from Webhook.",
    "webhookUrl": "A URL that returns a value in string or JSON format.",
    "skipTo": "Takes effect when a respondent clicks the Next or Done button.",
    "oneQuestionAtaTime": "Sets focus on one question at a time and grays out other questions.",
    "oneQuestionPerScreen": "Force to display one question only per screen and hide other questions.",
    "privacy": "A footer statement of \"We Protect Your Privacy\" will be added.",
    "surveyAppraisal": "Request advice from SurveyOL professionals to optimize your survey.",
    "testResponses": "Responses will feature randomly generated contents so you can see what your report/responses page looks like prior to releasing your survey."
};

$sog.questionTypes = {
    "multiple-choice-type": "Multiple Choice",
    "image-choice-type": "Image Choice",
    "dropdown-type": "Dropdown",
    "textbox-type": "Textbox",
    "comment-box-type": "Comment Box",
    "nps-type": "Net Promoter&reg; Score",
    "star-rating-type": "Star Rating",
    "scale-type": "Scale",
    "slider-type": "Slider",
    "ranking-type": "Ranking",
    "datetime-type": "Date / Time",
    "contact-type": "Contact",
    "file-upload-type": "File Upload",
    "cascading-menu-type": "Cascading Menu",
    "textbox-list-type": "Textbox List",
    "matching-type": "Matching",
    "grid-multiple-choice-type": "Grid - Multiple Choice",
    "grid-dropdown-type": "Grid - Dropdown",
    "text-type": "Text",
    "image-type": "Image",
    "text-ab-type": "Text A/B Test",
    "image-ab-type": "Image A/B Test"
};
$sog.questionTypeAliases = {
    "Multiple Choice": ["Multiple"],
    "Image Choice": ["Images"],
    "Dropdown" : null,
    "Textbox": ["Single Line"],
    "Comment Box": ["Comment", "Multiline", "Paragraph"],
    "Net Promoter&reg; Score": ["NPS"],
    "Star Rating": ["Star", "Rating"],
    "Scale": ["Scales", "Likert Scale", "Likert Scales"],
    "Slider": null,
    "Ranking": ["Rank Order"],
    "Matching": ["Match"],
    "Date / Time": ["Date", "Time"],
    "Contact": ["Contact Information", "Contact Info"],
    "File Upload": ["Upload", "Image Upload"],
    "Cascading Menu": ["Cascading"],
    "Textbox List": ["Multiple Textbox", "Multiple Textboxes", "Textboxes"],
    "Grid - Multiple Choice": ["Multiple Grid", "Grid Multiple"],
    "Grid - Dropdown": ["Dropdown Grid", "Grid Dropdown"],
    "Text": null,
    "Image": null,
    "Text A/B Test": ["Text A/B"],
    "Image A/B Test": ["Image A/B"]
};
$sog.acceptResponse = {
    "multiple-choice-type": true,
    "image-choice-type": true,
    "dropdown-type": true,
    "textbox-type": true,
    "comment-box-type": true,
    "nps-type": true,
    "star-rating-type": true,
    "scale-type": true,
    "slider-type": true,
    "ranking-type": true,
    "datetime-type": true,
    "contact-type": true,
    "file-upload-type": true,
    "cascading-menu-type": true,
    "textbox-list-type": true,
    "matching-type": true,
    "grid-multiple-choice-type": true,
    "grid-dropdown-type": true,
    "text-type": false,
    "image-type": false,
    "text-ab-type": false,
    "image-ab-type": false
};
$sog.customOutline = {
    "multiple-choice-type": true,
    "image-choice-type": true,
    "dropdown-type": true,
    "textbox-type": false,
    "comment-box-type": false,
    "nps-type": true,
    "star-rating-type": true,
    "scale-type": true,
    "slider-type": true,
    "ranking-type": true,
    "datetime-type": true,
    "contact-type": false,
    "file-upload-type": true,
    "cascading-menu-type": false,
    "textbox-list-type": false,
    "matching-type": true,
    "grid-multiple-choice-type": true,
    "grid-dropdown-type": true,
    "text-type": true,
    "image-type": true,
    "text-ab-type": true,
    "image-ab-type": true
};

$sog.requiresBasic = {
    "multiple-choice-type": false,
    "image-choice-type": false,
    "dropdown-type": false,
    "textbox-type": false,
    "comment-box-type": false,
    "star-rating-type": true,
    "nps-type": true,
    "scale-type": true,
    "slider-type": true,
    "ranking-type": true,
    "datetime-type": true,
    "contact-type": true,
    "file-upload-type": true,
    "cascading-menu-type": true,
    "textbox-list-type": true,
    "matching-type": true,
    "grid-multiple-choice-type": true,
    "grid-dropdown-type": true,
    "text-type": true,
    "image-type": true,
    "text-ab-type": true,
    "image-ab-type": true
};
$sog.requiresPro = {
    "multiple-choice-type": false,
    "image-choice-type": false,
    "dropdown-type": false,
    "textbox-type": false,
    "comment-box-type": false,
    "star-rating-type": false,
    "nps-type": false,
    "scale-type": false,
    "slider-type": false,
    "ranking-type": false,
    "datetime-type": false,
    "contact-type": false,
    "file-upload-type": true,
    "cascading-menu-type": true,
    "textbox-list-type": false,
    "matching-type": true,
    "grid-multiple-choice-type": false,
    "grid-dropdown-type": false,
    "text-type": false,
    "image-type": false,
    "text-ab-type": true,
    "image-ab-type": true
};

$sog.canRandomize = {
    "multiple-choice-type": true,
    "image-choice-type": true,
    "dropdown-type": true,
    "textbox-type": false,
    "comment-box-type": false,
    "nps-type": false,
    "star-rating-type": false,
    "scale-type": false,
    "slider-type": false,
    "ranking-type": true,
    "datetime-type": false,
    "contact-type": false,
    "cascading-menu-type": false,
    "file-upload-type": false,
    "textbox-list-type": false,
    "matching-type": false,
    "grid-multiple-choice-type": false,
    "grid-dropdown-type": false,
    "text-type": false,
    "image-type": false,
    "text-ab-type": false,
    "image-ab-type": false
};
$sog.hasMultiChoiceSymbol = {
    "multiple-choice-type": true,
    "image-choice-type": true,
    "dropdown-type": false,
    "textbox-type": false,
    "comment-box-type": false,
    "nps-type": false,
    "star-rating-type": false,
    "scale-type": false,
    "slider-type": false,
    "ranking-type": false,
    "datetime-type": false,
    "contact-type": false,
    "file-upload-type": false,
    "cascading-menu-type": false,
    "textbox-list-type": false,
    "matching-type": false,
    "grid-multiple-choice-type": true,
    "grid-dropdown-type": false,
    "text-type": false,
    "image-type": false,
    "text-ab-type": false,
    "image-ab-type": false
};
$sog.hasTextboxStyle = {
    "multiple-choice-type": true,
    "image-choice-type": false,
    "dropdown-type": true,
    "textbox-type": true,
    "comment-box-type": true,
    "nps-type": false,
    "star-rating-type": false,
    "scale-type": false,
    "slider-type": true,
    "ranking-type": false,
    "datetime-type": true,
    "contact-type": true,
    "file-upload-type": false,
    "cascading-menu-type": false,
    "textbox-list-type": true,
    "matching-type": false,
    "grid-multiple-choice-type": false,
    "grid-dropdown-type": true,
    "text-type": false,
    "image-type": false,
    "text-ab-type": false,
    "image-ab-type": false
};
$sog.hasReportingValues = {
    "multiple-choice-type": true,
    "image-choice-type": true,
    "dropdown-type": true,
    "textbox-type": false,
    "comment-box-type": false,
    "nps-type": false,
    "star-rating-type": false,
    "scale-type": false,
    "slider-type": false,
    "ranking-type": false,
    "datetime-type": false,
    "contact-type": false,
    "file-upload-type": false,
    "cascading-menu-type": false,
    "textbox-list-type": false,
    "matching-type": false,
    "grid-multiple-choice-type": false,
    "grid-dropdown-type": true,
    "text-type": false,
    "image-type": false,
    "text-ab-type": false,
    "image-ab-type": false
};
$sog.canAnalyzeSentiments = {
    "multiple-choice-type": false,
    "image-choice-type": false,
    "dropdown-type": false,
    "textbox-type": true,
    "comment-box-type": true,
    "nps-type": false,
    "star-rating-type": false,
    "scale-type": false,
    "slider-type": false,
    "ranking-type": false,
    "datetime-type": false,
    "contact-type": false,
    "file-upload-type": false,
    "cascading-menu-type": false,
    "textbox-list-type": false,
    "matching-type": false,
    "grid-multiple-choice-type": false,
    "grid-dropdown-type": false,
    "text-type": false,
    "image-type": false,
    "text-ab-type": false,
    "image-ab-type": false
};
$sog.contactElements = [
    { type: "Name", label: "Name", visibility: true },
    { type: "Company", label: "Company", visibility: true },
    { type: "Title", label: "Title", visibility: true },
    { type: "Address", label: "Address", visibility: true },
    { type: "Address 2", label: "Address 2", visibility: true },
    { type: "City/Town", label: "City/Town", visibility: true },
    { type: "State/Province", label: "State", visibility: true },
    { type: "Zip/Postal Code", label: "Zip Code", visibility: true },
    { type: "Country", label: "Country", visibility: false },
    { type: "Email", label: "Email", visibility: true },
    { type: "Phone", label: "Phone", visibility: true }
];

$sog.operatorRequireAnswer = {
    "is": true,
    "isNot": true,
    "isAnyOf": true,
    "isNotAnyOf": true,
    "containsAnyOf": true,
    "isBetween": true,
    "isGreaterThan": true,
    "isGreaterThanOrEqualTo": true,
    "isLessThan": true,
    "isLessThanOrEqualTo": true,
    "contains": true,
    "startsWith": true,
    "endsWith": true,
    "isAnswered": false,
    "isNotAnswered": false
};

$sog.defaultColors = ["#ff0000", "#ffff00", "#00ff00", "#00ffff", 
    "#ff00ff", "#0000ff", "#000080", "#008080", 
    "#008000", "#800080", "#800000", "#808000", 
    "#808080", "#c0c0c0", "#000000", "#ffffff"];

$sog.starColors = ["#F5A623", "#C1403D", "#4A90E2", "#009473", "#5F4B8B", "#000000"];

$sog.starPngs = ["star-yellow.png", "star-red.png", "star-blue.png", "star-green.png", "star-purple.png", "star-black.png"];

$sog.invitationButtonColors = ["#009473", "#C1403D", "#F5A623", "#4A90E2", "#5F4B8B", "#333333"];

$sog.embeddingButtonColors = ["#009473", "#C1403D", "#F5A623", "#4A90E2", "#5F4B8B", "#333333"];

$sog.chartColors = ["#7cb5ec", "#434348", "#90ed7d", "#f7a35c", "#8085e9", "#f15c80", "#e4d354", "#2b908f", "#f45b5b", "#91e8e1"];

$sog.pantoneColors = ["#0F4C81", "#FF6F61", "#5F4B8B", "#88B04B", "#92A8D1", "#F7CAC9", "#955251", "#B163A3", "#009473", "#DD4124", "#D94F70",
    "#45B5AA", "#F0C05A", "#5A5B9F", "#9B1B30", "#DECDBE", "#53B0AE", "#E2583E", "#7BC4C4", "#BF1932", "#C74375", "#9BB7D4"];

$sog.x11Colors = {
    "pink": "#ffc0cb", "lightpink": "#ffb6c1", 
    "hotpink": "#ff69b4", "deeppink": "#ff1493", "palevioletred": "#db7093", "mediumvioletred": "#c71585",
    "lightsalmon": "#ffa07a", "salmon": "#fa8072", "darksalmon": "#e9967a", "lightcoral": "#f08080", 
		"indianred": "#cd5c5c", "crimson": "#dc143c", "firebrick": "#b22222", "darkred": "#8b0000", "red": "#c1403d",
    "orangered": "#ff4500", "tomato": "#ff6347", "coral": "#ff7f50", "darkorange": "#ff8c00", "orange": "#ffa500",
    "yellow": "#ffff00", "lightyellow": "#ffffe0", "lemonchiffon": "#fffacd", "lightgoldenrodyellow": "#fafad2", 
    "papayawhip": "#ffefd5", "moccasin": "#ffe4b5", "peachpuff": "#ffdab9", 
    "palegoldenrod": "#eee8aa", "khaki": "#f0e68c", "darkkhaki": "#bdb76b", "gold": "#ffd700",
    "cornsilk": "#fff8dc", "blanchedalmond": "#ffebcd", "bisque": "#ffe4c4", "navajowhite": "#ffdead", "wheat": "#f5deb3", 
    "burlywood": "#deb887", "tan": "#d2b48c", "rosybrown": "#bc8f8f", "sandybrown": "#f4a460",
    "goldenrod": "#daa520", "darkgoldenrod": "#b8860b", "peru": "#cd853f", "chocolate": "#d2691e", 
    "saddlebrown": "#8b4513", "sienna": "#a0522d", "brown": "#a52a2a", "maroon": "#800000",
    "darkolivegreen": "#556b2f", "olive": "#808000", "olivedrab": "#6b8e23", "yellowgreen": "#9acd32", "limegreen": "#32cd32", 
    "lime": "#00ff00", "lawngreen": "#7cfc00", "chartresue": "#7fff00", 
    "greenyellow": "#adff2f", "springgreen": "#00ff7f", "mediumspringgreen": "#00fa9a", "lightgreen": "#90ee90",
    "palegreen": "#98fb98", "darkseagreen": "#8fbc8f", "mediumaquamarine": "#66cdaa",
    "mediumseagreen": "#3cb371", "seagreen": "#we8b57", "forestgreen": "#228b22", "green": "#008000", "darkgreen": "#006400",
    "aqua": "#00ffff", "cyan": "#00ffff", "lightcyan": "#e0ffff", "paleturquoise": "#afeeee", "aquamargine": "#7fffd4", 
    "turquoise": "#40e0d0", "mediumturquoise": "#48d1cc", "darkturquoise": "#00ced1", 
    "lightseagreen": "#20b2aa", "cadetblue": "#5f9ea0", "darkcyan": "#008b8b", "teal": "#008080",
    "lightsteelblue": "#b0c4de", "powderblue": "#b0e0e6", "lightblue": "#add8e6", "skyblue": "#87ceeb", 
    "lightskyblue": "#87cefa", "deepskyblue": "#00bfff", "dodgerblue": "#1e90ff", "cornflowerblue": "#6495ed", "steelblue": "#4682b4", 
    "royalblue": "#4169e1", "blue": "#0000ff", "mediumblue": "#0000cd","darkblue": "#00008b", "navy": "#000080", "midnightblue": "#191970",
    "lavender": "#e6e6fa", "thistle": "#d88fd8", "plum": "#dda0dd", "violet": "#ee82ee", "orchid": "#da70d6", 
    "fuchsia": "#ff00ff", "magenta": "#ff00ff", "mediumorchid": "#ba55d3", "mediumpurple": "#9370db", "blueviolet": "#8a2be2",
    "darkviolet": "#9400d3", "darkorchid": "#9932cc", "darkmagenta": "#8b008b", "purple": "#800080", "indigo": "#4b0082", 
    "darkslateblue": "#4b3d8b", "slateblue": "#6a5acd", "mediumslateblue": "#7b68ee",
    "white": "#ffffff", "snow": "#fffafa", "honeydew": "#f0fff0", "mintcream": "#f5fffa", "azure": "#f0ffff", "aliceblue": "#f0f8ff", 
    "ghostwhite": "#f8f8ff", "whitesmoke": "#f5f5f5", "seashell": "#fff5ee", "beige": "#f5f5dc",
    "oldlace": "#fdf5e6", "floralwhite": "#fffaf0", "ivory": "#fffff0", "antiquewhite": "#faebd7", "linen": "#faf0e6", 
    "lavenderblush": "#fff0f5", "mistyrose": "#ffe4e1",
    "gainsboro": "#dcdcdc", "lightgray": "#d3d3d3", "silver": "#c0c0c0", "darkgray": "#a9a9a9", "gray": "#808080", "dimgray": "#696969", 
    "lightslategray": "#778899", "slategray": "#708090", "darkslategray": "#2f4f4f", "black": "#000000" 
};

$sog.copyToClipboard = function (text, callback) {
    var isValid = false;
    if (window.clipboardData && window.clipboardData.setData) {
        // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
        var r = clipboardData.setData("Text", text);
        if (callback) {
            callback();
        }
        isValid = true;
    }
    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            var r2 = document.execCommand("copy");  // Security exception may be thrown by some browsers.
            if (callback) {
                callback();
            }
            isValid = true;
        }
        catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            $sog.logError(ex.message);
        }
        finally {
            document.body.removeChild(textarea);
        }
    }
    return isValid;
};

$sog.getQuestionTypeKey = function (value) {
    var key;
    if (value) {
        for (var one in $sog.questionTypes) {
            if ($sog.questionTypes.hasOwnProperty(one)) {
                if ($sog.questionTypes[one].toLowerCase() == value.toLowerCase()) {
                    key = one;
                    break;
                }
            }
        }
    }
    return key;
};

$sog.runTouchstartOrEvent = function (e, func) {
    if (e && e.type === "touchstart") {
        setTimeout(function () {
            if (!$sog.touchmoving) {
                func(e);
            }
        }, 200);
    } else if (e) {
        e.preventDefault();
        func(e);
    } else {
        func();
    }
};

$sog.arrayHasContent = function (arr) {
    var flag = false;
    if (arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i]) {
                flag = true;
                break;
            }
        }
    }
    return flag;
};

$sog.getQuestionTypeKeyMatched = function (value) {
    var type;
    if (value) {
        for (var one in $sog.questionTypeAliases) {
            if (value.toLowerCase() === one.toLowerCase()) {
                type = one;
                break;
            }
            if (type === undefined) {
                var aliases = $sog.questionTypeAliases[one];
                if (aliases) {
                    for (var i = 0; i < aliases.length; i++) {
                        if (value.toLowerCase() === aliases[i].toLowerCase()) {
                            type = one;
                            break;
                        }
                    }
                }
            }
        }
    }
    return $sog.getQuestionTypeKey(type);
};

$sog.getSingularOrPluralPhase = function (number, singularWord, pluralWord) {
    var message;
    if (number === 1) {
        message = number + " " + singularWord;
    } else {
        message = number + " " + pluralWord;
    }
    return message;
};

$sog.getEstimatedTimeDisplay = function (secs) {
	var display;
	var minutes = Math.floor(secs / 60);
    var seconds = secs % 60;
    if (minutes === 0) {
        display = seconds + "s";
    } else if (seconds !== 0) {
		display = minutes + "m " + seconds + "s";
	} else {
		display = minutes + "m";
	}
	return display;
};

$sog.round5 = function (x) {
    return x % 5 >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
};

$sog.levenshtein = function (a, b) {
    var tmp;
    if (a.length === 0) { return b.length; }
    if (b.length === 0) { return a.length; }
    if (a.length > b.length) { tmp = a; a = b; b = tmp; }

    var i, j, res, alen = a.length, blen = b.length, row = Array(alen);
    for (i = 0; i <= alen; i++) { row[i] = i; }

    for (i = 1; i <= blen; i++) {
        res = i;
        for (j = 1; j <= alen; j++) {
            tmp = row[j - 1];
            row[j - 1] = res;
            res = b[i - 1] === a[j - 1] ? tmp : Math.min(tmp + 1, Math.min(res + 1, row[j] + 1));
        }
    }
    return res;
};
$sog.getLocationOrigin = function () {
    if (!window.location.origin) {
        window.location.origin = window.location.protocol + "//" + window.location.hostname +
            (window.location.port ? ':' + window.location.port : '');
    }
    return window.location.origin;
};

$sog.getLastPart = function (url) {
    return url.match(/([^\/#]*)\/*$/)[1].split("?")[0];
};

// Get last part of URL prior to any parameter
$sog.getLastPartOfUrl = function () {
    return window.location.href.match(/([^\/#]*)\/*$/)[1].split("?")[0];
};

$sog.loadingMessage = function (element, message, numberOfDots, numberOfLoop) {
    if (isNaN(numberOfDots)) {
        numberOfDots = 0;
        numberOfLoop = 0;
    }
    element.html(message + Array(numberOfDots + 1).join("."));
    if (numberOfDots >= 3) {
        numberOfDots = 0;
    } else {
        numberOfDots += 1;
    }
    numberOfLoop += 1;
    if (numberOfLoop < 30) {
        setTimeout(function () {
            $sog.loadingMessage(element, message, numberOfDots, numberOfLoop);
        }, 1000);
    }
};

$sog.logMessage = function (content, user, label, paras) {
    //$.ajax({
    //    method: "POST",
    //    url: label === "error" ? "/system/adderrorlog" : "/system/addinfolog",
    //    data: JSON.stringify({ projectKey: "surveyol", content: content, user: user, label: label, paras: paras }),
    //    contentType: 'application/json; charset=utf-8',
    //    dataType: 'json'
    //});
};

$sog.getCountry = function (callback) {
    $.ajax({
        method: "GET",
        url: "/system/getIpStack",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json'
    }).done(function (result) {
        if (result && result.flag && callback) {
            var ipStack = JSON.parse(result.ipStack);
            callback(ipStack.country_name);
        }
    });
};

$sog.logError = function (content, paras) {
    var user = JSON.stringify({ email: $sog.getAccountEmail() });
    $sog.logMessage(content, user, "error", paras);
};

$sog.logInfo = function (content, paras) {
    var user = JSON.stringify({ email: $sog.getAccountEmail() });
    $sog.logMessage(content, user, "info", paras);
};

$sog.setGroupKey = function (groupKey) {
    var logKeysItem = $sog.getLocalStorageItem($sog.storageKeys.logKeys);
    var logKeys = !logKeysItem ? {} : JSON.parse(logKeysItem);
    logKeys.groupKey = groupKey;
    $sog.setLocalStorageItem($sog.storageKeys.logKeys, JSON.stringify(logKeys));
};

$sog.getGroupKey = function () {
    var logKeysItem = $sog.getLocalStorageItem($sog.storageKeys.logKeys);
    var logKeys = !logKeysItem ? {} : JSON.parse(logKeysItem);
    return logKeys.groupKey;
};

$sog.isNotSocialSignInUrl = function (pageReferrer) {
    if (pageReferrer.indexOf("https://www.linkedin.com/uas/login") === -1 &&
        pageReferrer.indexOf("https://api.twitter.com/oauth/authenticate") === -1) {
        return true;
    } else {
        return false;
    }
};

$sog.getLogRootReferrer = function (pageReferrer) {
    var logKeysItem = $sog.getLocalStorageItem($sog.storageKeys.logKeys);
    var logKeys = !logKeysItem ? {} : JSON.parse(logKeysItem);
    if (logKeys.rootReferrer && pageReferrer) {
        // Replace if pageReferrer is external
        var currentDomain = $sog.getDomain();
        if (pageReferrer.indexOf(currentDomain) === -1 && $sog.isNotSocialSignInUrl(pageReferrer)) {
            logKeys.rootReferrer = { url: pageReferrer, date: (new Date()).toJSON() };
            $sog.setLocalStorageItem($sog.storageKeys.logKeys, JSON.stringify(logKeys));
        }
    } else if (pageReferrer) {
        // Replace
        logKeys.rootReferrer = { url: pageReferrer, date: (new Date()).toJSON() };
        $sog.setLocalStorageItem($sog.storageKeys.logKeys, JSON.stringify(logKeys));
    }
    if (logKeys.rootReferrer && logKeys.rootReferrer.url && logKeys.rootReferrer.url.length > 100) {
        logKeys.rootReferrer.url = logKeys.rootReferrer.url.substring(0, 100);
    }
    return logKeys.rootReferrer;
};

$sog.getLogReferrer = function () {
    var pageReferrer = $("#referrer").val();
    if (pageReferrer && pageReferrer.length > 100) {
        pageReferrer = pageReferrer.substring(0, 100);
    }
    var rootReferrer = $sog.getLogRootReferrer(pageReferrer);
    var logReferrer = { pageReferrer: pageReferrer, rootReferrer: rootReferrer };
    return logReferrer;
};

$sog.getLogBrowserLabel = function () {
    var label = JSON.stringify({
        cookieDisabled: $sog.isCookieDisabled.toString(), storageDisabled: $sog.isStorageDisabled.toString(), userAgent: navigator.userAgent
    });
    return label;
};

$sog.logData = function (content, data) {
    var user = JSON.stringify({ email: $sog.getAccountEmail() });
    $sog.logMessage(content, user, "info", data);
};

$sog.setLocalStorageItem = function (key, value) {
    try {
        window.localStorage.setItem(key, value);
    } catch (ex) {}
};

$sog.setSessionStorageItem = function (key, value) {
    try {
        window.sessionStorage.setItem(key, value);
    } catch (ex) { }
};

$sog.logActivity = function (content, customKey1, customLabel1, async) {
    async = async !== undefined ? async: true;
    var userKey = $sog.getAccountGuid();
    var groupKey = $sog.getGroupKey();
    var customKey2 = "Referrer";
    var customLabel2 = JSON.stringify($sog.getLogReferrer());
    var customKey3 = "Browser";
    var customLabel3 = $sog.getLogBrowserLabel();
    var customKey4, customLabel4, customKey5, customLabel5;
    var tstart = new Date();
    $.ajax({
        method: "POST",
        url: "/system/activity",
        async: async,
        data: JSON.stringify({
            content: content, label: "activity", userKey: userKey, groupKey: groupKey,
            customKey1: customKey1, customLabel1: customLabel1,
            customKey2: customKey2, customLabel2: customLabel2,
            customKey3: customKey3, customLabel3: customLabel3,
            customKey4: customKey4, customLabel4: customLabel4,
            customKey5: customKey5, customLabel5: customLabel5
        }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json'
    }).done(function (result) {
        var tend = new Date();
        $sog.setLocalStorageItem("LogActivityAsyncProcessed", new Date().toString() + " " + (tend - tstart).toString());
        if (result && result.flag) {
            if (result.groupKey !== groupKey) {
                $sog.setGroupKey(result.groupKey);
            }
            if (result.denied) {
                window.location.href = "/denied";
            }
        } else {
            console.log("Could not add log");
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        if (async) {
            $sog.logActivity(content, customKey1, customLabel1, false);
        }
    });
};

$sog.isInteger = function (value) {
    return /^\d+$/.test(value);
};

$sog.isValidUrl = function (url) {
    if (!url || (url.toLowerCase().indexOf("http://") == -1 && url.toLowerCase().indexOf("https://") == -1)) {
        return false;
    } else {
        return true;
    }    
};

$sog.hasVirtualDuplicates = function (array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = $.trim($sog.decodeHtml(array[i]));
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
};

$sog.isValidUrlOrMailAddress = function (url) {
    if ($sog.isValidUrl(url) || url.indexOf("mailto:") === 0) {
        return true;
    } else {
        return false;
    }
};

$sog.isVirtuallySame = function (v1, v2) {
    if (v1 == v2 || v1.toString().replace(/(\r\n|\n|\r)/gm, "") === v2.toString().replace(/(\r\n|\n|\r)/gm, "")) {
        return true;
    } else {
        return false;
    }
};

$sog.setCookie = function (cname, cvalue, exdays) {
    if (exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;secure;samesite=strict;"; 
    } else {
        document.cookie = cname + "=" + cvalue + ";path=/;secure;samesite=strict;";
    }
};

$sog.getCookie = function (cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
};

$sog.removeCookie = function (cname) {
    document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;secure;samesite=strict;";
};

$sog.getLocalStorageItem = function (key) {
    return $sog.getStorageItem(key, true);
};

$sog.getSessionStorageItem = function (key) {
    return $sog.getStorageItem(key, false);
};

$sog.getSessionCookieItem = function (key) {
    return $sog.getCookieItem(key, false);
};

$sog.getStorageItem = function (key, rememberMe) {
    var v = null;
    if (!$sog.isStorageDisabled) {
        try {
            v = rememberMe ? window.localStorage.getItem(key) : window.sessionStorage.getItem(key);
        } catch (ex) {
            $sog.isStorageDisabled = true;
        }
    }
    if ($sog.isStorageDisabled & !$sog.isCookieDisabled) {
        try {
            v = $sog.getCookie(key);
        } catch (ex) {
            $sog.isCookieDisabled = true;
            $sog.logInfo($sog.messages.storageDisabled);
        }
    }
    return v;
};

$sog.getCookieItem = function (key, rememberMe) {
    var v = null;
    if (!$sog.isCookieDisabled) {
        try {
            v = $sog.getCookie(key);
        } catch (ex) {
            $sog.isCookieDisabled = true;
        }
    }
    if ($sog.isCookieDisabled & !$sog.isStorageDisabled) {
        try {
            v = rememberMe ? window.localStorage.getItem(key) : window.sessionStorage.getItem(key);
        } catch (ex) {
            $sog.isStorageDisabled = true;
            $sog.logInfo($sog.messages.storageDisabled);
        }
    }
    return v;
};

$sog.setLocalStorageItem = function (key, value) {
    $sog.setStorageItem(key, value, true);
};

$sog.setSessionStorageItem = function (key, value) {
    $sog.setStorageItem(key, value, false);
};

$sog.setLocalCookieItem = function (key, value) {
    $sog.setCookieItem(key, value, true);
};

$sog.setSessionCookieItem = function (key, value) {
    $sog.setCookieItem(key, value, false);
};

$sog.setStorageItem = function (key, value, rememberMe) {
    if (!$sog.isStorageDisabled) {
        try {
            if (rememberMe) {
                window.localStorage.setItem(key, value);
            } else {
                window.sessionStorage.setItem(key, value);
            }
        } catch (ex) {
            $sog.isStorageDisabled = true;
        }
    }
    if ($sog.isStorageDisabled && !$sog.isCookieDisabled) {
        try {
            if (rememberMe) {
                $sog.setCookie(key, value, 365);
            } else {
                $sog.setCookie(key, value);
            }
        } catch (ex) {
            $sog.isCookieDisabled = true;
            $sog.logInfo($sog.messages.storageDisabled);
        }
    }
};

$sog.setCookieItem = function (key, value, rememberMe) {
    if (!$sog.isCookieDisabled) {
        try {
            if (rememberMe) {
                $sog.setCookie(key, value, 365);
            } else {
                $sog.setCookie(key, value);
            }
        } catch (ex) {
            $sog.isCookieDisabled = true;
        }
    }
    if ($sog.isCookieDisabled && !$sog.isStorageDisabled) {
        try {
            if (rememberMe) {
                window.localStorage.setItem(key, value);
            } else {
                window.sessionStorage.setItem(key, value);
            }
        } catch (ex) {
            $sog.isStorageDisabled = true;
            $sog.logInfo($sog.messages.storageDisabled);
        }
    }
};

$sog.redirect = function (url) {
    setTimeout(function () {
        window.location.href = url;
    }, 50);
};

$sog.removeLocalStorageItem = function (key) {
    $sog.removeStorageItem(key, true);
};

$sog.removeSessionStorageItem = function (key) {
    $sog.removeStorageItem(key, false);
};

$sog.removeSessionCookieItem = function (key) {
    $sog.removeCookieItem(key, false);
};

$sog.removeStorageItem = function (key, rememberMe) {
    if (!$sog.isStorageDisabled) {
        try {
            if (rememberMe) {
                window.localStorage.removeItem(key);
            } else {
                window.sessionStorage.removeItem(key);
            }
        } catch (ex) {
            $sog.isStorageDisabled = true;
        }
    }
    if ($sog.isStorageDisabled && !$sog.isCookieDisabled) {
        try {
            $sog.removeCookie(key);
        } catch (ex) {
            $sog.isCookieDisabled = true;
            $sog.logInfo($sog.messages.storageDisabled);
        }
    }
};

$sog.removeCookieItem = function (key, rememberMe) {
    if (!$sog.isCookieDisabled) {
        try {
            $sog.removeCookie(key);
        } catch (ex) {
            $sog.isCookieDisabled = true;
        }
    }
    if ($sog.isCookieDisabled && !$sog.isStorageDisabled) {
        try {
            if (rememberMe) {
                window.localStorage.removeItem(key);
            } else {
                window.sessionStorage.removeItem(key);
            }
        } catch (ex) {
            $sog.isStorageDisabled = true;
            $sog.logInfo($sog.messages.storageDisabled);
        }
    }
};

$sog.isJson = function (o) {
    var isJson = false;
    try {
        var json = JSON.parse(o);
        isJson = typeof(json) === "object";
    } catch (ex) { }
    return isJson;
};

$sog.removeLeadingAndTrailingBreaks = function (string) {
    var regex = /^\s*(?:<br\s*\/?\s*>)+|(?:<br\s*\/?\s*>)+\s*$/gi;
    string = $.trim(string).replace(regex, '');
    var regex2 = /^\s*(?:<div><br\s*\/?\s*><\/div>)+|(?:<div><br\s*\/?\s*><\/div>)+\s*$/gi;
    string = $.trim(string).replace(regex2, '');
    string = $.trim(string).replace(/(&nbsp;|&nbsp;\s)*$/, "");
    return string;
};

$sog.replaceForeignCharacters = function (string) {
    try {
        string = string.replace(/[^ -~]+/g, "");
    } catch (ex) { }
    return string;
};

$sog.stripHtmlTags = function (html) {
    html = $sog.removeLeadingAndTrailingBreaks(html);
    var stripped = html.replace(/<.*?>/ig, "");
    return stripped;
};

// Convert HTML to text, line breaks to spaces
$sog.htmlToText = function (html) {
    html = $sog.removeLeadingAndTrailingBreaks(html);
    html = html.replace(/<(div|p|br).*?>/ig, "\n");
    html = html.replace(/<\/(div|p|br)>/ig, "\n");
    html = html.replace(/<(img|a).*?>/ig, " ");
    html = html.replace(/<.*?>/ig, "");
    html = html.replace(/(\r|\n|\r\n)\s*(\r|\n|\r\n)?/g, " ");
    html = $.trim(html);
    html = $("<div/>").html(html).text();
    return html;
};

$sog.hasParagraphs = function (html) {
    var matches = html.match(/<\/(div|p|br)>/ig);
    if (matches && matches.length > 1) {
        return true;
    } else {
        return false;
    }
};

$sog.sanitizeHtml2 = function (html) {
    html = $sog.removeLeadingAndTrailingBreaks(html);
    // Keep other HTML tags
    var sanitized = html.replace(/(\<\/?.+?\>)/ig, function ($1) {
        return $sog.sanitizeTag($1);
    });
    return html;
};

$sog.sanitizeTag = function (tagContainer) {
    var tagMatch = /\<\/?([a-zA-Z0-9]+)/ig.exec(tagContainer);
    if (tagMatch != null && tagMatch.length > 1 && $sog.acceptedTags[tagMatch[1]]) {
        if (tagContainer.indexOf("</") == 0) {
            return "</" + tagMatch[1] + ">";
        } else {
            var sanitized = tagContainer.replace(/(\s[a-zA-Z0-9]+="[^"]+")/ig, function ($1, $2, $3, $4) {
                var santizedAttributes = $sog.sanitizeAttributes(tagMatch[1], $2);
                return santizedAttributes;
            });
            return sanitized;
        }
    } else {
        return "";
    }
};

$sog.sanitizeAttributes = function (tagName, attributes) {
    var acceptedAttrs = $sog.acceptedTags[tagName];
    if (acceptedAttrs != null && acceptedAttrs.length > 0) {
        var sanitized = attributes.replace(/(\s[a-zA-Z0-9]+=".+")/ig, function ($1, $2) {
            return $sog.sanitizeAttribute(tagName, $2);
        });
        return sanitized;
    } else {
        return "";
    }
};

$sog.sanitizeAttribute = function (tagName, attribute) {
    var acceptedAttrs = $sog.acceptedTags[tagName];
    if (acceptedAttrs != null && acceptedAttrs.length > 0) {
        var sanitized = attribute.replace(/\s([a-zA-Z0-9]+)=".+"/ig, function ($1, $2) {
            if (acceptedAttrs.indexOf($2) !== -1) {
                return attribute;
            } else {
                return "";
            }
        });
        return sanitized;
    } else {
        return "";
    }
};

$sog.acceptedTags = {
    "b": [],
    "i": [],
    "u": [],
    "font": ["color"],
    "span": ["style"],
    "br": [],
    "div": []
};

$sog.getImageWith = function (imageUrl) {
    $("<img>").attr("src", imageUrl).load(function () {
        var realWidth = this.width;
        var realHeight = this.height;
        return new { width: realWidth, height: realHeight };
    });
};

$sog.validateImageUrl = function (imageUrl) {
    var re = /^(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))$/i;
    return re.test(imageUrl);
};

$sog.validateWordUrl = function (url) {
    var re = /^(http)?s?:?(\/\/[^"']*\.(?:doc|docx))$/i;
    return re.test(url);
};

$sog.validateExcelUrl = function (url) {
    var re = /^(http)?s?:?(\/\/[^"']*\.(?:xls|xlsx))$/i;
    return re.test(url);
};

$sog.validatePdfUrl = function (url) {
    var re = /^(http)?s?:?(\/\/[^"']*\.(?:pdf))$/i;
    return re.test(url);
};

$sog.validateEmail = function (email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
};

$sog.validatePassword = function (password) {
    var re = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
    return re.test(password);
};

$sog.validateElementNumber = function (element) {
    var min = element.attr("min");
    var max = element.attr("max");
    var v = element.val();
    if (!$sog.validateNumber(v) || (min !== undefined && parseInt(v) < min)
        || (max !== undefined && parseInt(v) > parseInt(max))) {
        var newValue = v.substring(0, v.length - 1);
        element.val(newValue);
        element.select();
    }
};

$sog.validateNumber = function (number) {
    var re = /^\d+$/;
    return re.test(number);
};

$sog.validateDate = function (date) {
    var re = /^([1-9]|0[1-9]|1[0-2])\/([1-9]|0[1-9]|1\d|2\d|3[01])\/\d{4}$/;
    return re.test(date);
};

$sog.validateQxPara = function (para) {
    var re = /^Q\d+$/gi;
    return re.test(para);
};

$sog.validateTime = function (time) {
    var re = /^([1-9]|0[1-9]|1[0-2]):(\d|[0-5]\d)$/;
    return re.test(time);
};

$sog.validateHexColor = function(color) {
    var re = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
    return re.test(color);
};

$sog.validateString = function (value) {
    var re = /^([A-z]+)$/;
    return re.test(value);
};


$sog.validateNumber = function (value) {
    var re = /^([0-9]+)$/;
    return re.test(value);
};

$sog.validateUrl = function (value) {
    var re = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/;
    return re.test(value);
};

$sog.validateUSZipCode = function (value) {
    var re = /^\d{5}([\-]\d{4}){0,1}$/;
    return re.test(value);
};

$sog.validateUSPhoneNumber = function (value) {
    var re = /^((\(\d{3}\) ?)|(\d{3}[-\s]))?\d{3}[-\s]\d{4}$/;
    return re.test(value);
};

// Last dash or space is optional
$sog.validateUSPhoneNumber2 = function (value) {
    var re = /^((\(\d{3}\) ?)|(\d{3}[-\s]?))?\d{3}[-\s]?\d{4}$/;
    return re.test(value);
};

$sog.removeNonDigits = function (value) {
    var re = value.replace(/\D/g, '');
    return re;
};

$sog.validateWebLinkKey = function (value) {
    if (value.length < 7 || value.length > 100) {
        return false;
    } else {
        var re = /^([A-z0-9\-_]+)$/;
        return re.test(value);
    }
};

$sog.getHexColor = function (color) {
    if (color && $sog.validateString(color)) {
        var hex = $sog.x11Colors[color.toLowerCase()];
        return hex;
    } else {
        return "";
    }
};

$sog.validateRgbFormat = function(value) {
    var re = /^rgb\(\d{1,3},\s?\d{1,3},\s?\d{1,3}\)$/;
    return re.test(value);
};

$sog.formatHexColor = function (color) {
    if ($sog.validateRgbFormat(color))
    {
        var matches = color.match(/\d+/gi);
        return "#" + parseInt(matches[0]).toString(16).padLeft(2) + parseInt(matches[1]).toString(16).padLeft(2) +
            parseInt(matches[2]).toString(16).padLeft(2);
    } else if ($sog.validateHexColor(color)) {
        return color;
    } else {
        return $sog.getHexColor(color);
    }
};

$sog.formatRgbaColor = function (color, opacity) {
    if ($sog.validateRgbFormat(color)) {
        var matches = color.match(/\d+/gi);
        color = "rgba(" + parseInt(matches[0]) + "," + parseInt(matches[1]) + "," +
            parseInt(matches[2]) + "," + opacity + ")";
    } else {
        if (!$sog.validateHexColor(color)) {
            color = $sog.getHexColor(color);
        }
        if (color !== "") {
            var rgba = $sog.convertHexToRgb(color);
            color = "rgba(" + rgba.r + "," + rgba.g + "," +
                rgba.b + "," + opacity + ")";
        }
    }
    return color;
};

$sog.formatInputName = function (name) {
    var cleanName = name.toLowerCase();
    // Remove foreign characters and non-alphanumeric characters
    cleanName = cleanName.replace(/[^a-z0-9]/g, ''); 
    cleanName = cleanName.substring(0, 255);
    return cleanName;
};

$sog.convertHexToRgb = function(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
};

$sog.displayDateWithToday = function (localDate) {
    var td = new Date();
    var withinToday = "";
    var diffSeconds = Math.floor((td - localDate) / 1000); // Seconds
    if (diffSeconds < 60) {
        withinToday = "less than 1 minute ago";
    } else if (diffSeconds < 60 * 2) {
        withinToday = "1 minute ago";
    } else if (diffSeconds < 60 * 3) {
        withinToday = "2 minutes ago";
    } else if (diffSeconds < 60 * 60) {
        withinToday = "a few minutes ago";
    } else if (diffSeconds < 60 * 60 * 2) {
        withinToday = "1 hour ago";
    } else if (localDate.getFullYear() === td.getFullYear() && localDate.getMonth() === td.getMonth()
        && localDate.getDate() === td.getDate()) {
        withinToday = "today";
    }
    return withinToday;
};

$sog.getLocalDate = function (stdDate) {
    if (stdDate.toUpperCase().substr(-1) !== "Z") {
        stdDate += "Z";
    }
    var md = new Date(stdDate);
    return md;
};

$sog.displayDateTime = function (dateobj) {
    return $sog.displayDate(dateobj) + " " + $sog.displayTime(dateobj);
};

$sog.displayDate = function (dateobj) {
    return (dateobj.getMonth() + 1) + "/" + dateobj.getDate() + "/" + dateobj.getFullYear();
};

$sog.displayDateUN = function (dateobj) {
    return dateobj.getFullYear() + "/" + (dateobj.getMonth() + 1) + "/" + dateobj.getDate();
};

$sog.displayDateMinFormat = function (dateobj) {
    return dateobj.getFullYear() + "-" + (dateobj.getMonth() + 1).toString().padLeft(2) + "-" + dateobj.getDate().toString().padLeft(2);
};

$sog.displayInputDate = function (yyyymmdd) {
    var dis = "";
    var parts = yyyymmdd.split("-");
    if (parts.length === 3) {
        dis = parts[1] + "/" + parts[2] + "/" + parts[0];
    }
    return dis;
};

$sog.displayUtcDateTime = function (inputDateTime) {
    var dt = new Date(inputDateTime);
    var utcHours = dt.getUTCHours();
    var utcTt = utcHours >= 12 ? "PM" : "AM";
    if (utcHours === 0) {
        utcHours = 12;
    } else if (utcHours > 12) {
        utcHours = utcHours - 12;
    }
    var dtString = (dt.getUTCMonth() + 1).toString().padLeft(2) + "/" + dt.getUTCDate().toString().padLeft(2) + "/" + dt.getUTCFullYear() + " " +
        utcHours.toString().padLeft(2) + ":" + dt.getUTCMinutes().toString().padLeft(2) + " " + utcTt;
    return dtString;
};

$sog.setInputDate = function (mmddyyyy) {
    var input = "";
    var parts = mmddyyyy.split("/");
    if (parts.length === 3) {
        input = parts[2] + "-" + parts[0] + "-" + parts[1];
    }
    return input;
};

$sog.displayTime = function (dateobj) {
    var hours = dateobj.getHours();
    var minutes = dateobj.getMinutes();
    var seconds = dateobj.getSeconds();
    var ampm = hours >= 12 ? "PM" : "AM";
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour "0" should be "12"
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    var strTime = hours + ":" + minutes + ":" + seconds + " " + ampm;
    return strTime;
};

$sog.addDateChoices = function (monthElement, dayElement, yearElement) {
    var i;
    var now = new Date();
    monthElement.append($("<option/>").attr("value", "").text("MM"));
    for (i = 1; i <= 12; i++) {
        var monthText = $sog.getTwoDigit(i);
        monthElement.append($("<option/>").attr("value", monthText).text(monthText));
    }
    dayElement.append($("<option/>").attr("value", "").text("DD"));
    for (i = 1; i <= 31; i++) {
        var dayText = $sog.getTwoDigit(i);
        dayElement.append($("<option/>").attr("value", dayText).text(dayText));
    }
    //TODO: extend
    for (i = 1900; i <= 2100; i++) {
        yearElement.append($("<option/>").attr("value", i).text(i));
    }
    yearElement.find("option[value=" + now.getFullYear() + "]").prop("selected", true);
};

$sog.addTimeChoices = function (hourElement, minElement) {
    var i;
    hourElement.append($("<option/>").attr("value", "").text("hh"));
    for (i = 1; i <= 12; i++) {
        var hourText = $sog.getTwoDigit(i);
        hourElement.append($("<option/>").attr("value", hourText).text(hourText));
    }
    minElement.append($("<option/>").attr("value", "").text("mm"));
    for (i = 0; i <= 59; i++) {
        var minText = $sog.getTwoDigit(i);
        minElement.append($("<option/>").attr("value", minText).text(minText));
    }
};

$sog.getTwoDigit = function (i) {
    return i.toString().length === 1 ? "0" + i : i.toString();
};

$sog.randomizeArray = function (array) {
    if (array && array.length > 1) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    return array;
};

$sog.rotateArray = function (array) {
    if (array && array.length > 1) {
        var rnd = Math.floor(Math.random() * array.length);
        for (var i = 0; i < rnd; i++) {
            array.push(array.shift());
        }
    }
    return array;
};

$sog.flipArray = function (array) {
    if (array && array.length > 1) {
        var rnd = Math.floor(Math.random() * 2);
        if (rnd >= 1) {
            array.reverse();
        }
    }
    return array;
};

$sog.scrollTo = function (top) {
    try {
        //window.scrollTo({ top: top, behavior: 'smooth' });
        $("html, body").animate({ scrollTop: top }, "fast");
    } catch (ex) {
        window.scrollTo(0, top);
        $sog.logError(ex.message);
    }
};

$sog.scrollToTop = function () {
    $sog.scrollTo(0);
};

$sog.scrollIntoView = function (element, scroller) {
    var offset = element.offset();
    if (offset !== undefined) {
        offset.left -= 50;
        offset.top -= 50;
        window.scrollTo(offset.left, offset.top);
    }
};

$sog.scrollIntoOneQuestionView = function (element) {
    var offset = element.offset();    
    offset.top -= window.innerHeight * 0.38;
    try {
        $("html, body").animate({ scrollTop: offset.top }, 500);
    } catch (ex) {
        window.scrollTo(0, offset.top);
    }
};

$sog.sortArray = function (array, type) {
    if (type === $sog.sources.randomize) {
        array = $sog.randomizeArray(array);
    } else if (type === $sog.sources.rotate) {
        array = $sog.rotateArray(array);
    } else if (type === $sog.sources.flip) {
        array = $sog.flipArray(array);
    }
    return array;
};

$sog.placeCaretAtEnd = function (el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
};

$sog.setImageMaxWidth = function (element, maxWidth) {
    if (element.width() > maxWidth) {
        var imageHeight = Math.round(element.height() * maxWidth / element.width());
        element.css("width", maxWidth + "px");
        element.css("height", imageHeight + "px");
    }
};

$sog.getFileExtension = function (filename) {
    return /[.]/.exec(filename) ? /[^.]+$/.exec(filename) : "None";
};

// Inactivity timer
$sog.inactivityTime = new Date();
function resetTimer() {
    $sog.inactivityTime = new Date();
}
window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function (name) {
    document.addEventListener(name, resetTimer, true);
});

Date.prototype.yyyymmdd = function () {
    var mm = this.getMonth() + 1;
    var dd = this.getDate();

    return [this.getFullYear(),
        (mm > 9 ? '' : '0') + mm,
        (dd > 9 ? '' : '0') + dd
        ].join('');
};

Date.prototype.mmddyyyy = function () {
    var mm = this.getMonth() + 1;
    var dd = this.getDate();

    return [(mm > 9 ? '' : '0') + mm,
        (dd > 9 ? '' : '0') + dd,
        this.getFullYear()        
        ].join('/');
};

Date.prototype.stdTimezoneOffset = function () {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
};

Date.prototype.dst = function () {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
};

Date.prototype.addDays = function (days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
};
Date.prototype.addMinutes = function (m) {
    this.setTime(this.getTime() + m * 60 * 1000);
    return this;
};
Date.prototype.addDays = function (days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
};
String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined'
          ? args[number]
          : match
        ;
    });
};

String.prototype.padLeft = function (n, str) {
    return Array(n - this.length + 1).join(str || '0') + this;
};

String.prototype.capitalize = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

$sog.arrayMove = function(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr;
};

window.mobilecheck = function () {
    var check = false;
    (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera);
    return check;
};

window.mobileAndTabletcheck = function () {
    var check = false;
    (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera);
    return check;
};

$sog.isIgnorableLog = function (log) {
    var ignorable = false;
    if (log === "Script error.") {
        ignorable = true;
    } else if (log && log.indexOf("Microsoft Internet extensions") > -1) {
        ignorable = true;
    } else if (log && log.indexOf("getReadMode") > -1) {
        ignorable = true;
    }
    return ignorable;
};

$sog.pointerEventToXY = function (e) {
    var out = { x: 0, y: 0 };
    if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') {
        var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
        out.x = touch.pageX;
        out.y = touch.pageY;
    } else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') {
        out.x = e.pageX;
        out.y = e.pageY;
    }
    return out;
};

$sog.autoExpand = function (element) {
    var offset = element.innerHeight() - element.height();
    if (element.innerHeight() < element[0].scrollHeight) {
        // Grow the field
        element.height(element[0].scrollHeight - offset);
    } else {
        if (element[0].scrollHeight > 0) {
            // Temporarily shrink the field then re-set it
            var docY = $(document).scrollTop();
            element.height(1);
            element.height(element[0].scrollHeight - offset);
            $(document).scrollTop(docY);
        } 
    }
};

$sog.getAlphaKeyFromCharCode = function (charCode) {
    var groupCode = Math.floor(charCode / 26);
    var subCode = charCode % 26;
    var alphaKey = String.fromCharCode(subCode + 65);
    if (groupCode > 0) {
        var alphaGroupKey = String.fromCharCode(groupCode - 1 + 65);
        alphaKey = alphaGroupKey + alphaKey;
    }
    return alphaKey;
};

$sog.getTotalLocalStorageSize = function () {
    var totalSize = 0;
    for (var i = 0; i < localStorage.length; i++) {
        var key = localStorage.key(i);
        var value = localStorage.getItem(key);
        // Calculate the size of the key and value in bytes
        var itemSize = (key.length + value.length) * 2; // Assuming 2 bytes per character

        totalSize += itemSize;
    }
    return totalSize;
};

$sog.bytesToSize = function(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    if (bytes === 0) return '0 Byte';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

$sog.openPopup = function (href) {
    // Frame mask
    if (document.querySelectorAll(".sog-frame-mask").length === 0) {
        var solMk = document.createElement("div");
        solMk.setAttribute("class", "sog-frame-mask");
        solMk.style.display = "none";
        solMk.style.position = "fixed";
        solMk.style.left = "0px";
        solMk.style.right = "0px";
        solMk.style.top = "0px";
        solMk.style.bottom = "0px";
        solMk.style.height = "100%";
        solMk.style.margin = "auto";
        solMk.style.textAlign = "center";
        solMk.style.zIndex = "5001";
        solMk.style.backgroundColor = "rgba(0, 0, 0, 0.8)";
        solMk.addEventListener("click", function (e) {
            document.querySelector(".sog-frame-container iframe").setAttribute("src", "");
            document.querySelector(".sog-frame-container").style.display = "none";
            document.querySelector(".sog-frame-mask").style.display = "none";
        });
        document.body.appendChild(solMk);
    }
    // Frame container
    if (document.querySelectorAll(".sog-frame-container").length === 0) {
        var left, top, width, height;
        left = parseInt(window.innerWidth * 0.0625);
        top = parseInt(window.innerHeight * 0.1);
        width = window.innerWidth * 0.85;
        height = window.innerHeight * 0.8;
        var solFrCt = document.createElement("div");
        solFrCt.setAttribute("class", "sog-frame-container");
        solFrCt.style.position = "fixed";
        solFrCt.style.left = "0px";
        solFrCt.style.top = "0px";
        solFrCt.style.zIndex = "5002";
        document.body.appendChild(solFrCt);
        // Frame panel in container
        var solFrPl = document.createElement("div");
        solFrPl.style.position = "absolute";
        solFrPl.style.left = left + "px";
        solFrPl.style.top = top + "px";
        solFrPl.style.width = width + "px";
        solFrCt.appendChild(solFrPl);
        // Frame in frame panel
        var solFr = document.createElement("iframe");
        solFr.style.width = width + "px";
        solFr.style.height = height + "px";
        solFr.style.border = "solid 1px gray";
        solFrPl.appendChild(solFr);
        // Close button in frame panel
        var solCb = document.createElement("button");
        solCb.style.position = "absolute";
        solCb.style.top = "0px";
        solCb.style.right = "0px";
        solCb.style.border = "0";
        solCb.style.padding = "5px";
        solCb.style.cursor = "pointer";
        solCb.innerHTML = '<svg viewPort="0 0 20 20" width="20" height="20"><line x1="2" y1="18" x2="18" y2="2" stroke="white" stroke-width="2" />' +
            '<line x1="2" y1="2" x2="18" y2="18" stroke="white" stroke-width="2" /></svg>';
        solCb.style.transform = "translate(100%, -100%)";
        solCb.style.backgroundColor = "transparent";
        solCb.addEventListener("click", function (e) {
            document.querySelector(".sog-frame-container iframe").setAttribute("src", "");
            document.querySelector(".sog-frame-container").style.display = "none";
            document.querySelector(".sog-frame-mask").style.display = "none";
        });
        solFrPl.appendChild(solCb);
    }
    document.querySelector(".sog-frame-container iframe").setAttribute("src", href);
    document.querySelector(".sog-frame-container").style.display = "";
    document.querySelector(".sog-frame-mask").style.display = "";
};

$sog.setDebugMessage = function (content) {
    if ($sog.enabledDebug) {
        var elements = $(".debugger-container .debugger-element");
        content = elements.length + 1 + ":" + content;
        var element = $("<div/>").addClass("debugger-element inner-block");
        element.text(content);
        $(".debugger-container").append(element).removeClass("nodisp");
    }
};

$sog.showMessage = function (msg, action, hideDuration) {
    clearTimeout($sogTimeout);
    $("#messageContent").html(msg);
    if (action) {
        $("#messageAction").empty().append(action).removeClass("nodisp");
    } else {
        $("#messageAction").empty().addClass("nodisp");
    }
    $("#messageSection").show().removeClass("nodisp");
    var fullWidth = $("header").width();
    var width = $("#messageSection").width();
    var left = Math.floor((fullWidth - width) / 2) - 2;
    $("#messageSection").css("left", left + "px").css("top", 0).hide();
    $("#messageSection").slideDown("slow");
    if (hideDuration) {
        $sogTimeout = setTimeout(function () {
            $sog.hideMessage();
        }, hideDuration);
    }
};

$sog.hideMessage = function () {
    $("#messageSection").slideUp("slow");
};

jQuery.fn.swapWith = function (to) {
    return this.each(function () {
        var copy_to = $(to).clone(true);
        var copy_from = $(this).clone(true);
        $(to).replaceWith(copy_from);
        $(this).replaceWith(copy_to);
    });
};

window.onerror = function (message, file, line, col, error) {
    var log = error && error.stack ? error.stack : message;
    if (log === null || log === undefined) {
        log = "An unexpected error occurs.";
    }
    if (!$sog.isIgnorableLog(log)) { 
        $sog.logError(log);
    }
};

$(function () {
    $sog.init();
});
// Copyright @ Logbrite.com. All rights reserved.
var $logbrite = $logbrite || {};
$logbrite.content = [];
$logbrite.pageKeyExcludes = ["/s/8EF87E3"];

$logbrite.initActivityLog = function () {
    if (!$sog.isBot()) {
        $logbrite.addMajorActivityTracking("enters page " + $logbrite.getPageKey());
    }
};

$logbrite.getPageKey = function () {
    var key = $sog.getUrlWithoutDomain();
    if (key === "" || key === "/") {
        key = $sog.getDomain();
    }
    return key;
};

$logbrite.addMajorActivityTracking = function (title) {
    $logbrite.addActivityTracking(title, true);
    var contentToBeSaved = JSON.stringify($logbrite.content);
    $logbrite.content = [];
    var pageKey = $logbrite.getPageKey();
    if ($logbrite.pageKeyExcludes.indexOf(pageKey) === -1) {
        $sog.logActivity(contentToBeSaved, pageKey, document.title);  
    }
};

$logbrite.addMinorActivityTracking = function (title) {
    $logbrite.addActivityTracking(title, false);
};

$logbrite.addErrorActivityTracking = function (title) {
    $logbrite.addActivityTracking(title, false, "error");
    var contentToBeSaved = JSON.stringify($logbrite.content);
    $logbrite.content = [];
    var pageKey = $logbrite.getPageKey();
    if ($logbrite.pageKeyExcludes.indexOf(pageKey) === -1) {
        $sog.logActivity(contentToBeSaved, $logbrite.getPageKey(), document.title);
    }
};

$logbrite.addActivityTracking = function (title, priority, label) {
    var hasChanged = false;
    try {
        var track = { time: new Date() };
        track.priority = priority;
        if (label) {
            track.label = label;
        }
        var windowSize = { w: window.innerWidth, h: window.innerHeight };
        if (title) {
            track.title = title;
            hasChanged = true;
        }
        if (hasChanged) {
            track.windowSize = windowSize;
            $logbrite.content.push(track);
        }
    } catch (err) {
        console.log(err);
        $sog.logError("addActivityTracking error.", title);
    }
};

$(function () {
    $logbrite.initActivityLog();
});
// Copyright @ SurveyOL.com. All rights reserved.
var $surveyol = $surveyol || {};

$surveyol.executeAction = function (fnAction, allowed) {
    var msg = $sog.allowAction(allowed);
    if (!msg) {
        fnAction();
    } else {
        $sog.showMessage(msg, $surveyol.getUpgradeActions(), 8000);
    }
};

$surveyol.displayElement = function (element, allowed) {
    var msg = $sog.allowAction(allowed);
    if (!msg) {
        element.removeClass("nodisp");
    } else {
        element.addClass("nodisp");
    }
}

$surveyol.getUpgradeActions = function () {
    var upgradeIcon = $("<i/>").addClass("fas fa-rm fa-arrow-circle-up icon14").attr("aria-hidden", "true");
    var upgradeAction = $("<a/>").attr("href", "/subscription").html($sog.sources.upgrade);
    var upgradeBlock = $("<div/>").addClass("inline-block padding-h10").append(upgradeIcon).append(upgradeAction);
    var actionsBlock = $("<div/>").addClass("inline-block").append(upgradeBlock);
    return actionsBlock;
};

$surveyol.setContactEmail = function () {
    var email = "contact" + "@" + "surveyol" + "." + "com";
    $(".contact-email").each(function () {
        $(this).attr("href", "mailto:" + email);
        $(this).html(email);
    });
};

$surveyol.setRememberMe = function () {
    if (!$sog.getBrowserMemory().isLocalProfile) {
        $(".remember-me").prop("checked", false);
    } else {
        $(".remember-me").prop("checked", true);
    }
};

$surveyol.hideLockIcon = function () {
    var accountType = $sog.getAccountType() !== null ? $sog.getAccountType() : $sog.sources.free;
    if (accountType === $sog.sources.free) {
        $(".feature-lock").removeClass("nodisp");
        $(".feature-able").prop("disabled", true);
    } else {
        $(".feature-lock").addClass("nodisp");
        $(".feature-able").prop("disabled", false);
    }
};

$surveyol.hideMobileOnly = function () {
    if (window.mobileAndTabletcheck) {
        $(".mobile-only").removeClass("nodisp");
    } else {
        $(".mobile-only").addClass("nodisp");
    }
};

$surveyol.init = function () {
    $surveyol.setNavMenu();
    $surveyol.setUpgradeLink();
    // Join us
    $(document).on("click", ".btn-join-us", function (e) {
        e.preventDefault();
        var sec = $(this).closest(".call-to-action");
        var email = $.trim(sec.find(".join-us-email").val());
        if (email) {
            window.location.href = "/freeaccount?email=" + email;
        } else {
            window.location.href = "/freeaccount";
        }
    });
    $(document).on("click", "#dismissMessage", function (e) {
        e.preventDefault();
        $sog.hideMessage();
    });
    $(document).on("click", "#dismissInpageMessage", function (e) {
        e.preventDefault();
        $(this).closest(".message-block").remove();
    });
    $(document).on("touchstart click", ".btn-free-trial", function (e) {
        e.preventDefault();
        $sog.removeBrowserMemory();
        $sog.setBrowserAccountType($sog.sources.basicTrial);
        window.location.href = "/freetrial";
        return false;
    });
    $(document).on("click", ".help-icon", function (e) {
        e.preventDefault();
        var ctn = $(this).closest(".help-icon-container");
        var addTip = ctn.find(".so-tipbox").length === 0;
        $(".so-tipbox").remove();
        if (addTip) {
            var tipClass = "so-tipbox so-helptip";
            var tipBox = $("<div/>").attr("class", tipClass)
                .html($sog.tips[ctn.attr("data-value")]);
            ctn.append(tipBox);
            setTimeout(function () {
                $(".so-tipbox").remove();
            }, 8000);
        }
    });
    $(document).on("click", ".help-icon2", function (e) {
        e.preventDefault();
        var ctn = $(this).closest(".help-icon-container");
        var addTip = ctn.find(".so-tipbox").length === 0;
        $(".so-tipbox").remove();
        if (addTip) {
            var position = ctn.attr("data-position");
            var tipClass = "so-tipbox so-helptip";
            if (position === "bottom") {
                tipClass = "so-tipbox so-helptip-bottom";
            } else if (position === "right") {
                tipClass = "so-tipbox so-helptip-right";
            } else if (position === "left") {
                tipClass = "so-tipbox so-helptip-left";
            }
            var tipBox = $("<div/>").attr("class", tipClass)
                .html($sog.tips[ctn.attr("data-value")]);
            if (ctn.attr("data-tipwidth")) {
                tipBox.css("width", ctn.attr("data-tipwidth") + "px");
            }
            ctn.append(tipBox);
            setTimeout(function () {
                $(".so-tipbox").remove();
            }, 8000);
        }
    });
    $(document).on("mouseenter", ".left-menu-item", function () {
        var ctn = $(this).closest(".help-icon-container");
        $(".so-tipbox").remove();
        var position = ctn.attr("data-position");
        var tipClass = "so-tipbox so-helptip";
        if (position === "bottom") {
            tipClass = "so-tipbox so-helptip-bottom";
        } else if (position === "right") {
            tipClass = "so-tipbox so-helptip-right";
        }
        var tipContent = ctn.attr("data-value") ? $sog.tips[ctn.attr("data-value")] : ctn.attr("data-title");
        var tipBox = $("<div/>").attr("class", tipClass).html(tipContent);
        if (ctn.attr("data-tipwidth")) {
            tipBox.css("width", ctn.attr("data-tipwidth") + "px");
        }
        ctn.append(tipBox);
    }).on("mouseleave", ".left-menu-item", function () {
        $(".so-tipbox").remove();
    });
    $(".sign-out").on("click", function (e) {
        e.preventDefault();
        $sog.removeAccountProfile();
        window.location = "/signin";
    });
	$(".body-container").css("min-height", $surveyol.getBodyMinHeight());
	// My Account Menu
    $(".nav-account-icon").on("mouseenter", function () {
        $(".nav-account-menu").toggleClass("show");
    });
    $(".nav-account-menu").on("mouseleave", function () {
        $(".nav-account-menu").toggleClass("show");
    });
    // Nav sub-menu show/hide
    $(document).on("click", ".nav-parent-menu", function (e) {
        e.preventDefault();
        var subnav = $(this).parent().find(".navbar-sub-nav");
        if (subnav.hasClass("nodisp")) {
            $(".navbar-sub-nav").addClass("nodisp");
            subnav.removeClass("nodisp");
        } else {
            $(".navbar-sub-nav").addClass("nodisp");
        }
    });

    if (Modernizr && !Modernizr.touch) {
        $(document).on("mouseenter", ".nav-menu-container", function () {
            $(".navbar-sub-nav").addClass("nodisp");
            $(this).find(".navbar-sub-nav").removeClass("nodisp");
        }).on("mouseleave", ".nav-menu-container", function () {
            $(".navbar-sub-nav").addClass("nodisp");
        });
    }
    $surveyol.setContactEmail();
    $surveyol.enableHeaderShadow();
    $surveyol.setMainShiftSpace();
    $surveyol.setContentEditablePasteRule();
    $surveyol.setSharingLinks();
    $surveyol.legacyBrowserCompatibility();
    $surveyol.browserBackHandler();
};

$surveyol.browserBackHandler = function () {
    if (performance.navigation.type === 2) {
        if (window.location.pathname.indexOf("/design") > 0) {
            window.location.reload(true);
        }
    }
};

$surveyol.setContentEditablePasteRule = function () {
    // Editor paste
    $(document).on('paste', '[contenteditable]', function (e) {
        e.preventDefault();
        var pastedText;
        if ((e.originalEvent || e) &&
            (e.originalEvent || e).clipboardData &&
            (e.originalEvent || e).clipboardData.getData) { // Non-IE browsers
            pastedText = (e.originalEvent || e).clipboardData.getData('text/plain');
        } else if (window.clipboardData && window.clipboardData.getData) { // IE
            pastedText = window.clipboardData.getData('Text');
        }
        if (pastedText) {
            window.document.execCommand('insertText', false, pastedText);
        }
    });
    // Disable drag and drop content
    $(document).on('drop', '[contenteditable]', function (e) {
        e.preventDefault();
        return false;
    });
};

$surveyol.setSharingLinks = function () {
    $(document).on("click", ".share-on-facebook", function (e) {
        if ($(this).attr("href") === "#") {
            e.preventDefault();
            var linkUrl = $(this).attr("data-url") !== undefined ? $(this).attr("data-url") : encodeURIComponent(window.location.href);
            var url = "https://www.facebook.com/sharer.php?u=" + linkUrl;
            $(this).attr("href", url).attr("target", "_blank");
            e.target.click();
        }
    });

    $(document).on("click", ".share-on-twitter", function (e) {
        if ($(this).attr("href") === "#") {
            e.preventDefault();
            var linkUrl = $(this).attr("data-url") !== undefined ? $(this).attr("data-url") : encodeURIComponent(window.location.href);
            var url = "https://twitter.com/intent/tweet/?text=" + linkUrl;
            $(this).attr("href", url).attr("target", "_blank");
            e.target.click();
        }
    });

    $(document).on("click", ".share-on-linkedin", function (e) {
        if ($(this).attr("href") === "#") {
            e.preventDefault();
            var linkUrl = $(this).attr("data-url") !== undefined ? $(this).attr("data-url") : encodeURIComponent(window.location.href);
            var url = "https://www.linkedin.com/sharing/share-offsite/?url=" + linkUrl;
            $(this).attr("href", url).attr("target", "_blank");
            e.target.click();
        }
    });

    $(document).on("click", ".share-via-email", function (e) {
        if ($(this).attr("href") === "#") {
            e.preventDefault();
            var linkUrl = $(this).attr("data-url") !== undefined ? $(this).attr("data-url") : window.location.href;
            var url = "mailto:?subject=Share%20with%20you" + "&body=I%20want%20to%20share%20this%20with%20you%3A%20" + "%0D" + encodeURIComponent(linkUrl) + "%0D%0D";
            $(this).attr("href", url).attr("target", "_blank");
            e.target.click();
        }
    });
    $(document).on("click", ".share-via-sms", function (e) {
        if ($(this).attr("href") === "#") {
            e.preventDefault();
            var linkUrl = $(this).attr("data-url") !== undefined ? $(this).attr("data-url") : window.location.href;
            $(this).attr("href", "sms:?&body=I%20want%20to%20share%20this%20with%20you%3A%20" + "%0D" + encodeURIComponent(linkUrl)).attr("target", "_blank");
            e.target.click();
        }
    });
    // SMS capability
    if (window.mobilecheck()) {
        $(".share-via-sms-container").removeClass("nodisp");
    }
};

$surveyol.popupSurvey = function () {
    //$(document).bind("mouseleave", function (e) {
    //    // Check if popup opened
    //    // Only for non-design pages
    //    if (e.pageY - $(window).scrollTop() <= 1) {
    //        var pathName = window.location.pathname;
    //        if (pathName && pathName.indexOf("/design") === -1) {
    //            var beforeLeavePopped = $sog.getPreferences("beforeLeavePopped");
    //            if (beforeLeavePopped === null || !beforeLeavePopped) {
    //                $sog.setPreferences("beforeLeavePopped", true);
    //                $('#beforeYouLeaveDiv').removeClass("nodisp");
    //            }
    ////        }
    //    }
    //});
    //$(function() {
    //    // Check if popup opened
    //    // Only for non-design pages
    //    var pathName = window.location.pathname;
    //    if (pathName && pathName.indexOf("/design") === -1) {
    //        var firstLoadPopped = $sog.getPreferences("firstLoadPopped");
    //        if (firstLoadPopped === null || !firstLoadPopped) {
    //            $sog.setPreferences("firstLoadPopped", true);
    //            $('#firstLoadDiv').removeClass("nodisp");
    //        }
    //    }
    //});
};

$surveyol.enableHeaderShadow = function () {
    /* Scroll effect for box-shadow on top navigation */
    $(window).scroll(function () {
        $('header').addClass('shadow');
    }).scroll('off', function () {
        clearTimeout($.data(this, 'scrollTimer'));
        $.data(this, 'scrollTimer', setTimeout(function () {
            $('header').removeClass('shadow');
        }, 150));
    });
};

$surveyol.setMainShiftSpace = function () {
    $("main").css("padding-top", $("header").height());
    $(".left-menu,.right-menu").css("top", $("header").height() + "px");
};

$surveyol.legacyBrowserCompatibility = function () {
    if (document.createElement("p").style.flex === undefined) {
        $(".primary-button .button-action").addClass("nodisp");
    }
};

$surveyol.setSubscriptionBar = function () {
    var token = $sog.getAccountToken();
    if (token) {
        var type = $sog.getAccountType();
        var isSub = $sog.getAccountIsSub();
        var hrs = $sog.getAccountExpirationHours();
        var msg, action;
        var planText;
        if (type === $sog.sources.basic) {
            planText = $sog.sources.basicSubscription;
            action = $("<a/>").attr("href", "/myaccount").html($sog.sources.viewSubscription);
        } else if (type === $sog.sources.pro) {
            planText = $sog.sources.proSubscription;
            action = $("<a/>").attr("href", "/myaccount").html($sog.sources.viewSubscription);
        } else if (type === $sog.sources.enterprise) {
            planText = $sog.sources.enterpriseSubscription;
            action = $("<a/>").attr("href", "/myaccount").html($sog.sources.viewSubscription);
        } else if (type === $sog.sources.basicTrial) {
            planText = $sog.sources.freeTrial;
            action = $("<a/>").attr("href", "/subscription").html($sog.sources.activateAccount);
        } else if (type === $sog.sources.proTrial) {
            planText = $sog.sources.freeTrial;
            action = $("<a/>").attr("href", "/subscription").html($sog.sources.activateAccount);
        } else if (type === $sog.sources.enterpriseTrial) {
            planText = $sog.sources.freeTrial;
            action = $("<a/>").attr("href", "/subscription").html($sog.sources.activateAccount);
        }
        //TODO: replace planType; add expired message, retired EnterpriseExpiredMessage
        if (hrs !== undefined && hrs !== null && planText !== undefined) {
            if (Math.ceil(hrs / 24) <= 7) {
                if (Math.ceil(hrs / 24) > 1) {
                    msg = $sog.messages.planExpirationDays.replace("{0}", planText).replace("{1}", Math.ceil(hrs / 24));
                } else if (hrs > 1) {
                    msg = $sog.messages.planExpirationHours.replace("{0}", planText).replace("{1}", hrs);
                } else if (hrs === 1) {
                    msg = $sog.messages.planExpirationHour.replace("{0}", planText);
                } else {
                    window.location.href = "/subscription";
                    return false;
                }
            }         
        }
        if (msg && action) {
            if (isSub) {
                $surveyol.showTrialMessage(msg, null);
            } else {
                $surveyol.showTrialMessage(msg, action);
            }
        }
    }
};

$surveyol.getBodyMinHeight = function () {
    var minH = 0;
    try {
        minH = window.innerHeight - $(".header-container").innerHeight() - $("footer").innerHeight();
    } catch (ex) {
        // Nothing 
    }
    return minH;
};

$surveyol.setUpgradeLink = function () {
    if ($sog.getAccountType() === $sog.sources.basic || $sog.getAccountType() === $sog.sources.pro || $sog.getAccountType() === $sog.sources.enterprise) {
        $(".upgrade-link").addClass("nodisp");
    } else {
        $(".upgrade-link:not(.nav-private)").removeClass("nodisp");
    }
};

$surveyol.isPriorityAccount = function () {
    if ($sog.getAccountType() === $sog.sources.basic || $sog.getAccountType() === $sog.sources.pro || $sog.getAccountType() === $sog.sources.enterprise) {
        return true;
    } else {
        return false;
    }
};

$surveyol.logNotFoundMessage = function () {
    if (document.referrer) {
        $sog.logInfo("404");
    }
};

$surveyol.logInvalidMessage = function () {
    if (document.referrer) {
        $sog.logInfo("Invalid");
    }
};

$surveyol.showTransferredMessage = function () {
    if ($sog.getTransferredMessage()) {
        $sog.hideMessage();
        $sog.showMessage($sog.getTransferredMessage(), null, 5000);
        $sog.removeTransferredMessage();
    }
};

$surveyol.setNavMenu = function () {
    var token = $sog.getAccountToken();
    if (token) {
        $(".nav-public").addClass("nodisp");
        $(".nav-private").removeClass("nodisp");
        $surveyol.setTeamRoleDisplay();
        var email = $sog.getAccountEmail();
        if (email) {
            $(".nav-account-icon").attr("title", email);
        }
        var accountName = $surveyol.getAccountName();
        if (accountName) {
            $(".nav-account-username").text(accountName);
        }
    } else {
        $(".nav-public").removeClass("nodisp");
        if ($(".nav-account-menu > .nav-public").length === 0) {
            $(".nav-account-icon").remove();
        }
        $(".nav-private").addClass("nodisp");
    }
    var pathname = window.location.pathname.toLowerCase();
    $(".desktop-menu").find("a").each(function () {
        if (!$(this).hasClass("sub-menu") && ($(this).attr("href") === pathname || $(this).attr("data-target") === pathname)) {
            $(this).addClass("nav-selected");
        }
    });
};

$surveyol.getAccountName = function () {
    var accountName;
    var firstName = $sog.getAccountFirstName();
    var email = $sog.getAccountEmail();
    if (firstName) {
        accountName = firstName;
    } else if (email) {
        var username = email.substring(0, email.indexOf("@"));
        accountName = username;
    }
    return accountName;
};

$surveyol.setTeamRoleDisplay = function () {
    var role = $surveyol.getTeamRole();    
    if (role === $sog.sources.primaryAdmin) {
        $(".upgrade-link").removeClass("nodisp");
        $(".team-link").removeClass("nodisp");
    } else if (role === $sog.sources.admin) {
        $(".upgrade-link").addClass("nodisp");
        $(".team-link").removeClass("nodisp");
    } else if (role === $sog.sources.standardUser) {
        $(".upgrade-link").addClass("nodisp");
    } else if (role === $sog.sources.analyst) {
        $(".upgrade-link, .template-link, .new-survey-link").remove();
        $("#sampleSurveyInitiator, #sampleSurveys, #createSurveySection, #firstSurveyArea").remove();
        $("#noSurveys").removeClass("nodisp");
        // My account page
        $("#designViewSection, #settingsSection").addClass("nodisp");
        // Template page
        $(".btn-use-template, .btn-launch-template").addClass("nodisp");
    }
};

$surveyol.getTeamRole = function () {
    var role;
    var planType = $sog.getAccountType();
    if (planType === $sog.sources.enterprise || planType === $sog.sources.enterpriseTrial) {
        var teamUsers = $sog.getAccountTeamUsers();
        if (teamUsers !== undefined && teamUsers.length > 0) {
            for (var i = 0; i < teamUsers.length; i++) {
                if (teamUsers[i].email === $sog.getAccountEmail()) {
                    role = teamUsers[i].role;
                    break;
                }
            }
        }
    }
    return role;
};

$surveyol.showSubheader = function (msg, color, bgColor) {
    $("#subheaderSection").html(msg);
    $("#subheaderSection").removeClass("nodisp");
    $("#subheaderSection").css("color", color).css("background", bgColor);
};

$surveyol.showTrialMessage = function (msg, action) {
    $("#trialContent").html(msg);
    $("#trialBar").removeClass("nodisp");
    if (action) {
        $("#trialAction").empty().append(action).removeClass("nodisp");
    } else {
        $("#trialAction").empty().addClass("nodisp");
    }
    $surveyol.setMainShiftSpace();
};

$surveyol.activateVideos = function () {
    $(document).on("click", ".howto-toggle-launch", function (e) {
        e.preventDefault();
        var section = $(this).closest(".survey-creation-workflow");
        var solFrPl = section.find(".surveyol-frpl");
        var solFr = section.find(".howto-frame");
        var solCb = section.find(".howto-close-button");
        var solMk = section.find(".surveyol-mk");
        if (!solFr.hasClass("nodisp")) {
            solCb.addClass("nodisp");
            solFr.addClass("nodisp");
            solMk.addClass("nodisp");
            solFr.attr("src", "");
        } else {
            var embedUrl = "https://www.youtube.com/embed/" + $(this).attr("data-youtube-key");
            solFr.attr("src", embedUrl);
            var left = parseInt(window.innerWidth * 0.125);
            var top = parseInt(window.innerHeight * 0.125);
            var width = window.innerWidth * 0.75;
            var height = window.innerHeight * 0.75;
            solFrPl.css("left", left + "px");
            solFrPl.css("top", top + "px");
            solFr.css("width", width + "px");
            solFr.css("height", height + "px");
            solCb.removeClass("nodisp");
            solFr.removeClass("nodisp");
            solMk.removeClass("nodisp");
        }
    });
};

$.fn.isInViewport = function () {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(function () {
    $surveyol.init();
});
// Copyright @ SurveyOL.com. All rights reserved.
function Loader() {
    this.step = 0;
    this.stepMax = 30;
    this.stepShreshold = 5;
    this.initInterval = 1500;
    this.interval = 1000;
    this.loaderImageWidth = 120;
    this.loaderImageHeight = 120;
    this.isEnd = false;
    this.loaderContainer = $("body").find(".loader-container").eq(0);
    this.loaderContainer.removeClass("nodisp");        
    this.loaderElement = this.loaderContainer.find(".loader-element");
    this.loaderElement.addClass("nodisp");
    this.loaderElement.css("left", parseInt($(window).width() / 2 - this.loaderImageWidth / 2) + "px");
    this.loaderElement.css("top", parseInt($(window).height() / 2 - this.loaderImageHeight / 2) + "px");
    this.sendLogCalled = false;
}

function SetLoader(loader) {
    if (!loader.isEnd) {
        loader.loaderElement.removeClass("nodisp");        
        loader.step += 1;
        if (loader.step < loader.stepMax) {
            setTimeout(function () { SetLoader(loader); }, loader.interval);
            if (!loader.sendLogCalled && loader.step >= loader.stepShreshold) {
                loader.sendLog();
                sendLogCalled = true;
            }
        } else {
            loader.finish();
        }
    } else {
        loader.finish();
    }
}

Loader.prototype.init = function () {
    var $this = this;
    setTimeout(function () { SetLoader($this); }, $this.initInterval);
};

Loader.prototype.takesLonger = function () {
    this.stepShreshold = this.stepShreshold * 2;
};

Loader.prototype.takesVeryLong = function () {
    this.stepShreshold = this.stepShreshold * 20;
    if (this.stepShreshold > this.stepMax) {
        this.stepMax = this.stepShreshold;
    }
};

Loader.prototype.setMethod = function (method, methodData) {
    this.method = method;
    this.methodData = methodData;
};

Loader.prototype.finish = function () {
    this.loaderContainer.addClass("nodisp");
    this.loaderElement.addClass("nodisp");
    this.isEnd = true;
};

Loader.prototype.sendLog = function () {
    var paras = JSON.stringify({ method: this.method, methodData: this.methodData });
    var $this = this;
    $sog.getCountry(function (country) {
        if (country === $sog.sources.us) {
            $sog.logInfo($sog.messages.loaderMaxTime.replace("{0}", $this.stepShreshold), paras);
        }
    });
};
// Copyright @ Satishelp.com. All rights reserved.
function Satishelp() {
    this.messages = {
        "submitted": "Your message has been submitted.",
        "invalidEmail": "Please enter a valid email address.",
        "invalidName": "Please enter your name.",
        "invalidDescription": "Please enter your message description."
    };
    this.sources = {
        "ticket": "<i class=\"fas fa-plus fa-fw\" aria-hidden=\"true\"></i>Feedback",
        "minimize": "<i class=\"fas fa-times fa-fw\" aria-hidden=\"true\"></i>Close",
        "invalidName": "invalidName",
        "invalidEmail": "invalidEmail",
        "invalidDescription": "invalidDescription"
    };
}
   
Satishelp.prototype.addTicket = function (name, email, description) {
    var loader = new Loader();
    loader.setMethod("addticket");
    loader.init();
    var content = {
        name: $.trim(name),
        description: $.trim(description)
    };
    $.ajax({
        method: "POST",
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", "bearer " + $sog.getAccountToken());
        },
        url: "/system/addticket",
        data: JSON.stringify({ email: $.trim(email), content: JSON.stringify(content) }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json'
    }).done(function (result) {
        if (result && result.flag) {
            $("#ticketSection").addClass("nodisp");
            $(".add-ticket").html($satishelp.sources.ticket);
            $("#ticketMessageContent").html($satishelp.messages.submitted);
            $("#ticketMessageSection").removeClass("nodisp");
            setTimeout(function () {
                $("#ticketMessageSection").addClass("nodisp");
                $("#joinUsSection").removeClass("nodisp");
            }, 8000);
            $satishelp.clearTicket();
            $logbrite.addMinorActivityTracking("sends ticket");
        } else {
            $logbrite.addErrorActivityTracking("could not send ticket");
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        $logbrite.addErrorActivityTracking("fails to send ticket");
    }).always(function () {
        loader.finish();
    });
};

Satishelp.prototype.clearTicket = function () {
    $("#ticketName").val("");
    $("#ticketEmail").val("");
    $("#ticketDescription").val("");
    $("#ticketNameFailedMessage").addClass("nodisp");
    $("#ticketNameMessage").removeClass("nodisp");
    $("#ticketEmailFailedMessage").addClass("nodisp");
    $("#ticketEmailMessage").removeClass("nodisp");
    $("#ticketDescriptionFailedMessage").addClass("nodisp");
    $("#ticketDescriptionMessage").removeClass("nodisp");
};

Satishelp.prototype.verifyTicketName = function () {
    var flag = false;
    if ($.trim($("#ticketName").val()) === "") {
        $("#ticketNameFailedMessage").html($satishelp.messages.invalidName);
        $("#ticketNameFailedMessage").removeClass("nodisp");
        $("#ticketNameMessage").addClass("nodisp");
    } else {
        $("#ticketNameFailedMessage").addClass("nodisp");
        $("#ticketNameMessage").removeClass("nodisp");
        flag = true;
    }
    return flag;
};
Satishelp.prototype.verifyTicketEmail = function () {
    var flag = false;
    if (!$sog.validateEmail($.trim($("#ticketEmail").val()))) {
        $("#ticketEmailFailedMessage").html($satishelp.messages.invalidEmail);
        $("#ticketEmailFailedMessage").removeClass("nodisp");
        $("#ticketEmailMessage").addClass("nodisp");
    } else {
        $("#ticketEmailFailedMessage").addClass("nodisp");
        $("#ticketEmailMessage").removeClass("nodisp");
        flag = true;
    }
    return flag;
};
Satishelp.prototype.verifyTicketDescription = function () {
    var flag = false;
    if ($.trim($("#ticketDescription").val()) == "") {
        $("#ticketDescriptionFailedMessage").html($satishelp.messages.invalidDescription);
        $("#ticketDescriptionFailedMessage").removeClass("nodisp");
        $("#ticketDescriptionMessage").addClass("nodisp");
    } else {
        $("#ticketDescriptionFailedMessage").addClass("nodisp");
        $("#ticketDescriptionMessage").removeClass("nodisp");
        flag = true;
    }
    return flag;
};

$(function () {
    // Show ticket section
    $(document).on("click", ".add-ticket", function (e) {
        e.preventDefault();
        if ($("#ticketSection").hasClass("nodisp")) {
            $(".add-ticket").html($satishelp.sources.minimize);
            $("#ticketSection").removeClass("nodisp");
            window.scrollBy(0, 350);
            $logbrite.addMinorActivityTracking("clicks to send ticket");
            $("#joinUsSection").addClass("nodisp");
            $("#ticketName").focus();
        } else {
            $(".add-ticket").html($satishelp.sources.ticket);
            $("#ticketSection").addClass("nodisp");
            $("#joinUsSection").removeClass("nodisp");
        }
    });
    $(document).on("click", ".add-ticket-on-page", function (e) {
        e.preventDefault();
        $(".add-ticket").html($satishelp.sources.minimize);
        $("#ticketSection").removeClass("nodisp");
        $logbrite.addMinorActivityTracking("clicks to send ticket");
        $("#joinUsSection").addClass("nodisp");
        $("#ticketName").focus();
        window.scrollBy(0, 350);
    });

    $("#ticketName").on("input", function () {
        $satishelp.verifyTicketName();
    });
    $("#ticketEmail").on("input", function () {
        $satishelp.verifyTicketEmail();
    });
    $("#ticketDescription").on("input", function () {
        $satishelp.verifyTicketDescription();
    });
    $(document).on("click", ".btn-submit-ticket", function (e) {
        e.preventDefault();
        if ($satishelp.verifyTicketName() && $satishelp.verifyTicketEmail() && $satishelp.verifyTicketDescription()) {
            $satishelp.addTicket($("#ticketName").val(), $("#ticketEmail").val(), $("#ticketDescription").val());
        }
    });
    $(document).on("click", ".btn-cancel-submit-ticket", function (e) {
        e.preventDefault();
        $(".add-ticket").html($satishelp.sources.ticket);
        $("#ticketSection").addClass("nodisp");
        $logbrite.addMinorActivityTracking("cancels sending ticket");
        $satishelp.clearTicket();
        $("#joinUsSection").removeClass("nodisp");
    });
});

var $satishelp = new Satishelp();
// Copyright @ SurveyOL.com. All rights reserved.
function NavMenuHandler() {
    $(document).on("click", ".nav-menu", function (e) {
        e.preventDefault();
        var target = $(this).attr("data-target") + "?guid=" + $sog.getUrlParameterByKey("guid");
        window.location.href = target;
        return false;
    });

    $(document).on("click", ".nav-upgrade", function (e) {
        e.preventDefault();
        var target = "/subscription?url=" + encodeURIComponent(window.location.href);
        window.location.href = target;
        return false;
    });
}

$(function () {
    if (typeof $surveyol !== "undefined") {
        NavMenuHandler();
    } else {
        //TODO: log msg
        var lastErrorPage = $sog.getLastErrorPage();
        if (lastErrorPage !== window.location.href) {
            $sog.setLastErrorPage();
            window.location.reload();
        }
    }
});
