/**
 * Created by ronak on 3/28/18.
 */

var MIN_WIDTH_DESKTOP = 768;

function openWindowWithMenu(loc) {
    var winl = (screen.width-1024)/2;
    var wint = (screen.height-640)/2;
    myRemote = launch(loc,"WindowWithMenu","height=640,width=1024,channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=1,resizable=1,scrollbars=1,status=0,toolbar=1,top="+wint+",left="+winl,"Help");
    window.myRemote.focus();
}

function gotoLoc (loc) {
    var winl = (screen.width-640)/2;
    var wint = (screen.height-750)/2;

    myRemote = launch(loc,"FreeSurveys","height=640,width=750,channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=1,scrollbars=1,status=0,toolbar=0,top=" + wint + ",left=" + winl,"Help");
    window.myRemote.focus();
}

function launch(newURL, newName, newFeatures, orgName) {
    remote = open(newURL, newName, newFeatures);
    if (remote.opener == null)
        remote.opener = window;

    remote.opener.name = orgName;
    return remote;
}

function hideDiv(divID) {
    obj = $('#' + divID);
    if (obj) {
        obj.addClass("hidden");
    }
}

function showDiv(divID) {
    obj = $('#' + divID);
    if (obj) {
        obj.removeClass("hidden");
    }
}

function closeWindow() {
    if (isInternetExplorer()) {
        window.opener='x';
    }
    window.close();
}

function updateLanguageForChainingForTakeSurvey2018(languageID) {
    $('input:hidden[name=externalID]').val(languageID);
}

function checkForInputPlaceholder (element) {
    if ($(element).val().length > 0) {
        $(element).addClass('used');
    } else {
        $(element).removeClass('used');
    }
}

function checkAndAppendAttributes(brandingSurveyFooterClass, footerPartOneClass, surveyFooterClass) {
    $('.' + brandingSurveyFooterClass + ' .' + footerPartOneClass + ' .' + surveyFooterClass).attr('style',
        'display: block !important');
    $('.' + brandingSurveyFooterClass + ' .' + footerPartOneClass + ' .' + surveyFooterClass + ' a').attr('style',
        'text-decoration:none; display: inline !important');
    $('.' + brandingSurveyFooterClass + ' .' + footerPartOneClass + ' .' + surveyFooterClass + ' a span').attr('style',
        'display: inline !important');
}

function checkAndAppendIfAnyTagIsRemoved(poweredByText, footerDiv,
                                         brandingSurveyFooterClass, footerPartOneClass, surveyFooterClass) {
    if ($('.' + brandingSurveyFooterClass + ' .' + footerPartOneClass + ' .' + surveyFooterClass).length <= 0) {
        $('.' + brandingSurveyFooterClass + ' .' + footerPartOneClass).prepend(footerDiv);
    }
    var surveyFooterPoweredByTextWithoutNewLine =
        $('.' + brandingSurveyFooterClass + ' .' + footerPartOneClass + ' .' + surveyFooterClass)
            .html().replace(/\n/g, " ").replace(/&amp;/g, '&');
    if (surveyFooterPoweredByTextWithoutNewLine.indexOf(poweredByText) < 0) {
        $('.' + brandingSurveyFooterClass + ' .' + footerPartOneClass + ' .' + surveyFooterClass).html(poweredByText);
    }
}

function adjustTextBoxWidthWithText() {
    $.fn.textWidth = function (text) {
        if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
        $.fn.textWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css
        ('font', "300 14px/20px 'Fira Sans', sans-serif");
        return $.fn.textWidth.fakeEl.width();
    };

    $('.multi-row-question, .email-address-question, .comments-suggestions-question, .form-type-question, ' +
        '.multiple-choice-question').find('.answer-options:not(.is-auto)').find('.form-input, .other-input')
        .on('input textarea', function () {
            if ($(this).parent().parent('.answer-options').find('.prefix-wrapper, .suffix-wrapper').length > 0) {
            } else {
                var inputWidth = $(this).textWidth();
                $(this).parent().width(inputWidth + 24);

                if ($(this).val() == "") {
                    $(this).parent().width("auto");
                }
            }
        });

    $('.multi-row-question, .email-address-question, .comments-suggestions-question, .form-type-question, ' +
        '.multiple-choice-question').find('.answer-options:not(.is-auto)').find('.form-input, .other-input')
        .one('keydown', function () {
            if ($(this).parent().parent('.answer-options').find('.prefix-wrapper, .suffix-wrapper').length > 0) {
            } else {
                var textBoxWidth = $(this).parent().outerWidth();
                $(this).parent().css({"min-width": textBoxWidth, "max-width": "100%"});
                $(this).parent().find('.control-label').css('overflow-wrap', 'break-word');
            }
        });
}

function initPrintViewModeSettings() {
    if ($('.answer-color-popup').length > 0) {
        $('.answer-color-popup').hide();
        $('#textHighlighterPopOver').hide();
    }
    $('.survey-background-image').removeAttr('style');
    $('#ajaxContainerDiv').removeClass('has-bg-img');
    $('.is-review-mode .answer-container textarea').each(function () {
        $(this).height($(this).prop('scrollHeight'));
    });
}

function initPrintReview() {
    $('.survey-background-image').removeClass('survey-background-image');
}

function initTakeSurveyTooltip() {
    $('[data-qptooltip="tooltip"]').tooltipster({
        arrow: false,
        debug: false,
        delay: 50,
        interactive: true,
        maxWidth: 600,
        side: ['bottom', 'top', 'right', 'left'],
        speed: 300
    })
}
function submitFormIfAllAreHiddenQuestion(isFocusMode) {
    if ($('.survey-question-wrapper').not('.hidden').length == 0) {
        isFocusMode && $("#SurveySubmitButtonElement").parent().css('padding-top','80vh');
        $("#SurveySubmitButtonElement").click();
    }
}
function hideBackIfPreviousQuestionIsPlatformConnect(isPlatformConnectCompletionURL) {
    if (isPlatformConnectCompletionURL) {
        hideButton('.ok-wrapper .btn-prev');
        hideMainBackIfSingleQuestionOnPage();
    }
}

function hideMainBackIfSingleQuestionOnPage() {
    if ($(".survey-inside-wrapper .survey-question-wrapper").length == 1) {
        hideButton('.ok-wrapper .btn-prev:first-child');
    }
}

function hideButton(selector) {
        var backButton = document.querySelector(selector);
        backButton && $(backButton).hide();
}

function sortObject(obj) {
    var arr = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            arr.push({
                'key': prop,
                'value': obj[prop]
            });
        }
    }
    arr.sort(function(a, b) { return a.value - b.value; });
    return arr;
}

function deleteSurveyCookie() {
    var surveyCookies = Object.entries(getSurveyCookies());
    for (var i = 0; i < surveyCookies.length; i++) {
        var name = surveyCookies[i][0];
        document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=." + getRequestDomain() + ";";
        document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=." + getParentDomain() + ";";
        document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=" + getParentDomain() + ";";
        document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT;";
    }
}

function getSurveyCookies() {
    var cookies = document.cookie.split(";");
    var surveyCookieObject = new Object();
    for (var i = 0; i < cookies.length; i++) {
        if (getCookieName(cookies[i]).indexOf("Survey_") !== -1) {
            var cookie = cookies[i].split("=");
            surveyCookieObject[cookie[0].trim()] = cookie[1].trim();
        }
    }
    return surveyCookieObject;
}

function getCookieName(cookie) {
    var eqPos = cookie.indexOf("=");
    return eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
}

function getRequestDomain() {
    return window.location.hostname;
}

function getParentDomain() {
    var host = getRequestDomain();
    return host.substr(host.indexOf('.') + 1, host.length);
}

var maxNoOfImagesPreloadAtOnce = 5;

function getStartIndex() {
    if (window.sessionStorage.getItem('imgStartIndex')) {
        return window.sessionStorage.getItem('imgStartIndex');
    } else {
        return '0';
    }
}

function preload(imageArray) {
    var imageCount = 0, start = null, imageLoadedCount = 0;
    var images = new Array()
    start = getStartIndex();
    if (start == imageArray.length) {
        return;
    }
    if (document.images) {
        for (index = parseInt(start); index < imageArray.length; index++) {
            if (imageCount > maxNoOfImagesPreloadAtOnce - 1) {
                window.sessionStorage.setItem('imgStartIndex', index);
                break;
            }
            images[index] = new Image();
            images[index].src = imageArray[index];
            imageCount++;
            images[index].onload = function () {
                imageLoadedCount++;
                if (imageLoadedCount > maxNoOfImagesPreloadAtOnce - 1) {
                    preload(imageArray);
                }
            }
            images[index].onerror = function (e) {
                imageLoadedCount++;
                if (imageLoadedCount > maxNoOfImagesPreloadAtOnce - 1) {
                    preload(imageArray);
                }
            }
            window.sessionStorage.setItem('imgStartIndex', index + 1);
        }
    }
}

function getSanitizedTextForXSSPrevention(text) {
    if (text !== null && text !== '') {
        var modifiedText = text.replace(/\bon\w+=\S+(?=.*)/g, "");
        modifiedText = modifiedText.replace(/<script[^>]*>(?:(?!<\/script>)[^])*<\/script>/g, "");
        return modifiedText;
    }
    return text;
}

function addClassIfExitButtonExists() {
	if ($('.lang-exit-btn-wrapper').children('.survey-exit').length) {
		$('.survey-exit').parents('.take-survey-title').addClass('has-exit');
	}
}

function addTitleWrapperIfMoreThanOneDivOrParagraph() {
	const $spanChildren = $('.take-survey-title > span').children();
	const hasMultipleDivs = $spanChildren.filter('div').length > 1;
	const hasParagraphs = $spanChildren.filter('p').length >= 1;

	if (hasMultipleDivs) {
		$('.take-survey-title span > div').parents('.take-survey-title > span').addClass('ts-head-title-wrapper');
	} else if (hasParagraphs) {
		$('.take-survey-title span > p').parents('.take-survey-title > span').addClass('ts-head-title-wrapper');
	} else {
		$('.take-survey-title > span').removeClass('ts-head-title-wrapper');
	}
}

function addClassIfQuestionErrorClassPresent() {
	const $errorDivs = $('.take-survey-title .QuestionError > div');
	const $parentSpan = $errorDivs.parents('.take-survey-title > span');
	if ($errorDivs.css('text-align') === 'center') {
		$parentSpan.addClass('has-question-error-center');
	} else if ($errorDivs.css('text-align') === 'right') {
		$parentSpan.addClass('has-question-error-right');
	}
}

function handleTitleAlignmentWithExitButton() {
    addClassIfExitButtonExists();
    addTitleWrapperIfMoreThanOneDivOrParagraph();
    addClassIfQuestionErrorClassPresent();
}

var previousClassesOnBody = "";

function applyVisualModeBodyClasses(visualModeClasses) {
    var classes = previousClassesOnBody.split(" ");
    for (index = 0; index < classes.length; index++) {
        $('body').removeClass(classes[index]);
    }
    $('body').addClass(visualModeClasses);
    previousClassesOnBody = visualModeClasses;
}

function isVisualMode() {
    return $('body').hasClass('ts-visual-mode');
}

function poweredby() {
    var $activeQuest = $('.survey-question-wrapper.active-question');
    if ($activeQuest.prop('scrollHeight') > $activeQuest.height() + 101) {
        $('#powered-ft').attr('style', 'display: none !important;');
    } else {
        $('#powered-ft').attr('style', 'display: block !important;');
    }
}

function handlePageSpace() {
    poweredby();
    $(window).scroll(function () {
        poweredby();
        var $activeScrlQuest = $('.survey-question-wrapper.active-question');
        if ($activeScrlQuest.scrollTop() + $activeScrlQuest.innerHeight() >= $activeScrlQuest[0].scrollHeight - 20) {
            $('#powered-ft').attr('style', 'display: block !important;');
        } else {
            $('#powered-ft').attr('style', 'display: none !important;');
        }
    });
    $('.survey-question-wrapper.active-question').on('scroll', function () {
        if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight - 20) {
            $('#powered-ft').attr('style', 'display: block !important;');
        } else {
            $('#powered-ft').attr('style', 'display: none !important;');
        }
    });
}

function isUnichoiceQuestion(element) {
    return element.parent().parent().parent().hasClass('radio-jump');
}

function isMatrixQuestion(element) {
    return $('.active-question .answer-container').hasClass('matrix-multipoint-question');
}

function handleNAOptionClick() {
    if ($(this).parent().parent().hasClass('exclusive-option') || $('.active-question .answer-container').hasClass('has-matrix-exclusive-option')) {
        $(this).parent().parent().parent().each(function () {
            if ($(this).find('label').parent().hasClass('exclusive-option')) {
                $(this).find('label').removeClass("active");
            }
        });
    } else {
        $(this).parent().parent().parent().find('.exclusive-option label').removeClass('active')
    }
}

function handleMatrixUnichoice() {
    if (isMatrixQuestion($(this)) && !$('.active-question .answer-container').hasClass('has-matrix-exclusive-option')) {
        $(this).parent().parent().parent().each(function () {
            $(this).find('label').removeClass("active");
        });
    } else if (isMatrixQuestion($(this)) && $('.active-question .answer-container').hasClass('has-matrix-exclusive-option')) {
        $(this).parent().parent().parent().find('.has-na').find('label').removeClass("active");
    }
}

function handleMatrixMultiSelectNA() {
    if ($(this).parent().hasClass('matrix-exclusive-option')) {
        $(this).parent().parent().parent().each(function () {
            $(this).find('label').removeClass("active");
        });
    }
}

function addAnswerOptionSelectionHandlerForVisualMode() {
    $(".survey-body-wrapper .survey-question-wrapper .controls.control-selection .radio-check").click(function () {
        if ($(this).is(':checked')) {
            if (isUnichoiceQuestion($(this))) {
                $(this).parent().parent().parent().each(function () {
                    $(this).find('label').removeClass("active");
                });
            } else {
                handleMatrixUnichoice.call(this);
                handleMatrixMultiSelectNA.call(this);
                handleNAOptionClick.call(this);
            }
            $(this).parent().addClass('active');
        } else {
            $(this).parent().removeClass('active');
        }
    });
}

function initPageContentAllignment() {
    if ((isDesktopScreen() && isVisualMode()) || isFocusMode()) {
        $('.survey-question-wrapper').each(function () {

            var coverHeight = $(this).find('.cover-wrapper').outerHeight() + 2;
            var coverScroll = $(this).find('.cover-wrapper')[0].scrollHeight;

            if (coverScroll > coverHeight) {
                $(this)[0].style.cssText += 'justify-content: start !important;';
                $(this).find('.cover-wrapper').css('justify-content', 'start');
            } else {
                $(this)[0].style.cssText += 'justify-content: center !important;';
                $(this).find('.cover-wrapper').css('justify-content', 'safe center');
            }
        });
    } else {
        $('.ts-sqpp .survey-question-wrapper').attr('style', 'justify-content: start !important');
    }
    $('.ts-sqpp.is-half .survey-question-wrapper').attr('style', 'justify-content: start !important');
}

function initCoverWrapper() {
    if (!$('.survey-question-wrapper').has('div.cover-wrapper').length) {
        $('.ts-sqpp .take-survey-header').find('> *').wrapAll('<div class="cover-wrapper"></div>');
        $('.ts-sqpp .survey-question-wrapper').each(function () {
            $(this).find('> *').wrapAll('<div class="cover-wrapper"></div>');
        });
    }
}

function initCoverBanner() {
    if ($('.ts-sqpp').hasClass('is-half')) {
        $('.is-half .survey-question-wrapper').each(function () {
            $(this).find('.cover-wrapper').before('<div class="cover-banner"></div>');
        });
    } else {
        $('.cover-banner').remove();
    }
    initPageContentAllignment();
}

function initCoverFooterSpace() {
    var poweredFooter = 0;
    var coverBanner = 0;
    poweredFooter = $('#powered-ft').outerHeight();
    coverBanner = $('.cover-banner').outerHeight();
    var halfModeHeight = poweredFooter + coverBanner;
    $('.ts-visual-mode .survey-body-wrapper.ts-sqpp-main .survey-question-wrapper .cover-wrapper').css('height', 'calc(100% - ' + poweredFooter + 'px)');
    $('.ts-visual-mode .survey-body-wrapper.ts-sqpp-main .survey-question-wrapper:last-of-type .cover-wrapper').css('height', 'calc(100% - ' + (poweredFooter + 100) + 'px)');
    $('.ts-visual-mode .survey-body-wrapper.ts-sqpp-main .survey-run-form .survey-submit-wrapper').css('top', '-' + (poweredFooter + 100) + 'px');
    $('.ts-visual-mode .take-survey-header .take-survey-start').css('margin-bottom', '' + poweredFooter + 'px');
    $('.ts-visual-mode.is-half .survey-body-wrapper.ts-sqpp-main .survey-question-wrapper .cover-wrapper').css('height', 'calc(100% - ' + halfModeHeight + 'px)');
    $('.ts-visual-mode.is-half .survey-body-wrapper.ts-sqpp-main .survey-question-wrapper:last-of-type .cover-wrapper').css('height', 'calc(100% - ' + (halfModeHeight + 100) + 'px)');
    $('.ts-visual-mode.is-half .survey-body-wrapper.ts-sqpp-main .survey-run-form .survey-submit-wrapper').css('top', '-' + (poweredFooter + 50) + 'px');
}

function isFocusMode() {
    return $('body').hasClass('ts-sqpp') && !$('body').hasClass('ts-visual-mode');
}

function isDesktopScreen() {
    return $(window).width() >= MIN_WIDTH_DESKTOP;
}