﻿var Plugins =
{
    _active: false,
    _requestUrl: '',
    _pageUrl: '',
    _currentLanguage: '',
    _currentBrand: '',
    _containerDivId: '',
    _modalOpen: false,
    _RES: new Array(),
    _date: new Date(),

    Init: function (params) {

        if (Plugins._active) {
            // Read in the params
            Plugins._requestUrl = params.requestUrl;
            Plugins._pageUrl = params.pageUrl;
            Plugins._currentLanguage = params.currentLanguage.substring(0, 5);
            Plugins._currentBrand = params.currentBrand;
            Plugins._containerDivId = params.containerDivId;

            // Is it a supported language? 
            var supportedLanguage = (':en-GB:de-DE:es-ES:fr-FR:nl-BE:pt-PT:'.indexOf(Plugins._currentLanguage) != -1);

            // Is it a supported brand? 
            var supportedBrand = (':AuctionView:BCAutoEncheres:BCAAustria:BCABelgium:BCADenmark:BCAGermany:BCAItaly:BCANetherlands:BCAPortugal:BCASpain:BCASweden:'.indexOf(Plugins._currentBrand) != -1);

            // If it's a valid page, language, brand
            if ((Plugins._pageUrl.toLowerCase() == '/default.aspx') && supportedLanguage && supportedBrand) {
                Plugins.InitSurvey();
            }
        }
    },
    InitSurvey: function () {

        // Get the survey status (Completed, Declined, Postponed)
        var status = Plugins.ReadCookieValue('Survey', 'Status_1');
        var ask = false;

        // If postponed and not today
        if (status == 'Postponed') {
            var then = new Date(Plugins.ReadCookieValue('Survey', 'Stamp_1'));
            if (then.getDate() != Plugins._date.getDate()) {
                ask = true;
            }
        }

        // If ok to ask then initialise the modal
        if ((status == null) || ask) {

            Plugins.InitResources();
            Plugins.InitModal();
        }
    },

    InitResources: function () {

        // English
        Plugins._RES['en-GB'] = new Array();
        Plugins._RES['en-GB']['close'] = 'Close';
        Plugins._RES['en-GB']['participate'] = 'Do you have a couple of minutes to answer 7 questions that will help us improve your BCA website?';
        Plugins._RES['en-GB']['yes'] = 'Yes, I\'m happy to do it now.';
        Plugins._RES['en-GB']['later'] = 'I\'m busy right now, but please remind me tomorrow.';
        Plugins._RES['en-GB']['no'] = 'No, please don\'t ask me again.';
        Plugins._RES['en-GB']['surveyurl'] = 'http://www.surveygizmo.com/s3/648630/BCA-Survey-UK';

        // German
        Plugins._RES['de-DE'] = new Array();
        Plugins._RES['de-DE']['close'] = 'Schließen';
        Plugins._RES['de-DE']['participate'] = 'Haben Sie ein paar Minuten, um sieben Fragen zu beantworten, die uns helfen werden, die BCA Webseite weiter zu verbessern?';
        Plugins._RES['de-DE']['yes'] = 'Ja, ich unterstütze Sie gerne.';
        Plugins._RES['de-DE']['later'] = 'Ich bin beschäftigt im Moment; bitte fragen Sie mich morgen noch einmal.';
        Plugins._RES['de-DE']['no'] = 'Nein, bitte fragen Sie mich nicht mehr danach.';
        Plugins._RES['de-DE']['surveyurl'] = 'http://www.surveygizmo.com/s3/648631/BCA-Survey-DE';

        // Spanish
        Plugins._RES['es-ES'] = new Array();
        Plugins._RES['es-ES']['close'] = 'Cerrar';
        Plugins._RES['es-ES']['participate'] = 'Tiene usted un par de minutos para responder a 7 preguntas que nos ayudarán a mejorar la web de BCA?';
        Plugins._RES['es-ES']['yes'] = 'Si, encantado de responderlas ahora.';
        Plugins._RES['es-ES']['later'] = 'Estoy ocupado ahora, pero recuérdenmelo mañana, por favor.';
        Plugins._RES['es-ES']['no'] = 'No, por favor no me pregunte de nuevo.';
        Plugins._RES['es-ES']['surveyurl'] = 'http://www.surveygizmo.com/s3/648633/BCA-Survey-ES';

        // French
        Plugins._RES['fr-FR'] = new Array();
        Plugins._RES['fr-FR']['close'] = 'Fermer';
        Plugins._RES['fr-FR']['participate'] = 'Avez-vous 3mn pour répondre à 7 questions qui nous aideraient à améliorer le site Internet de BCA?';
        Plugins._RES['fr-FR']['yes'] = 'Oui, je souhaite participer maintenant.';
        Plugins._RES['fr-FR']['later'] = 'Je n’ai pas le temps, mais rappelez-le moi demain.';
        Plugins._RES['fr-FR']['no'] = 'Non, je ne souhaite pas participer.';
        Plugins._RES['fr-FR']['surveyurl'] = 'http://www.surveygizmo.com/s3/648628/BCA-Survey-FR';

        // Netherlands
        Plugins._RES['nl-BE'] = new Array();
        Plugins._RES['nl-BE']['close'] = 'Sluiten';
        Plugins._RES['nl-BE']['participate'] = 'Heeft u tijd om enkele korte vragen te beantwoorden en ons hiermee te helpen onze website te verbeteren? ';
        Plugins._RES['nl-BE']['yes'] = 'Ja, ik wil graag deelnemen.';
        Plugins._RES['nl-BE']['later'] = 'Momenteel ben ik druk, herinner mij morgen.';
        Plugins._RES['nl-BE']['no'] = 'Nee, vraag mij er niet meer na. ';
        Plugins._RES['nl-BE']['surveyurl'] = 'http://www.surveygizmo.com/s3/648626/BCA-Survey-NL';

		// Portuguese
        Plugins._RES['pt-PT'] = new Array();
        Plugins._RES['pt-PT']['close'] = 'Fechar';
        Plugins._RES['pt-PT']['participate'] = 'Tem alguns minutos para responder a 7 perguntas rápidas que nos ajudarão a melhorar o site da BCA?';
        Plugins._RES['pt-PT']['yes'] = 'Sim, posso responder agora.';
        Plugins._RES['pt-PT']['later'] = 'Agora estou ocupado, mas lembrem-me amanhã.';
        Plugins._RES['pt-PT']['no'] = 'Não. Não voltem a lembrar-me.';
        Plugins._RES['pt-PT']['surveyurl'] = 'http://www.surveygizmo.com/s3/648627/BCA-Survey-PT';
    },

    Resource: function (key) {
        // Return the translation
        return Plugins._RES[Plugins._currentLanguage][key];
    },

    InitModal: function () {

        // Create the modal html
        var html = '<div class="ModalPopup" id="survey-modal"><div class="Close"><div class="Inner"><a>';
        html += Plugins.Resource('close');
        html += '</a></div></div><div class="ModalContent">';
        html += '<p>' + Plugins.Resource('participate') + '</p>';
        html += '<ul><li><a class="Yes">' + Plugins.Resource('yes') + '</a></li>';
        html += '<li><a class="No">' + Plugins.Resource('no') + '</a></li>';
        html += '<li><a class="Later">' + Plugins.Resource('later') + '</a></li></ul>';
        html += '</div></div>';
        html += '<div id="survey-modal-background" class="ModalBackground"></div>';

        // Append to the end of the page body
        $('body').append(html);

        // Button events

        $('#survey-modal a.Yes').click(function () {
            window.open(Plugins.Resource('surveyurl'), 'Survey', 'status=yes,toolbar=no,menubar=no,location=no,width=600,height=400,resizable=1,scrollbars=1');
            Plugins.SetCookie('Survey', 1, 'Completed', Plugins._date.toGMTString());
            Plugins.CloseModal();
        });

        $('#survey-modal a.No, #survey-modal div.Close a').click(function () {
            Plugins.SetCookie('Survey', 1, 'Declined', Plugins._date.toGMTString());
            Plugins.CloseModal();
        });

        $('#survey-modal a.Later').click(function () {
            Plugins.SetCookie('Survey', 1, 'Postponed', Plugins._date.toGMTString());
            Plugins.CloseModal();
        });

        // Styling

        $('#survey-modal div.Close a').css({
            'padding-right': '26px'
        });

        $('#survey-modal div.ModalContent').css({
            'padding': '10px',
            'font-size': '.8em',
            'height': 'auto'
        });

        $('#survey-modal li a').css({
            'font-weight': 'bold',
            'cursor': 'pointer'
        });

        $('#survey-modal').css({
            'position': 'fixed',
            'left': '0px',
            'top': '0px',
            'z-index': '10001',
            'width': '400px',
            'height': 'auto'
        });

        $('#survey-modal-background').css({
            'position': 'fixed',
            'left': '0px',
            'top': '0px',
            'z-index': '10000'
        });

        // Capture a window re-size
        $(window).resize(function () { Plugins.ResizeModal(); });

        // Flag as open
        Plugins._modalOpen = true;

        Plugins.ResizeModal();
    },

    CloseModal: function () {

        $('#survey-modal, #survey-modal-background').css({
            'left': '-9999px',
            'top': '-9999px',
            'height': '1px',
            'width': '1px'
        });

        Plugins._modalOpen = false;
    },

    ResizeModal: function () {
        if (Plugins._modalOpen) {

            // Re-size the background
            $('#survey-modal-background').width($(window).width()).height($(window).height());

            // Move the modal
            $('#survey-modal').css({
                'top': ($(window).height() / 2 - ($('#survey-modal').height() / 2)) + 'px',
                'left': ($(window).width() / 2 - ($('#survey-modal').width() / 2)) + 'px'
            });
        }
    },

    SetCookie: function (cookieName, key, status, stamp) {

        var cookie = Plugins.ReadCookie(cookieName);

        if (cookie == null)
            cookie = '';
        if (cookie != '') {

            // Break out the key value pairs
            var cookieParts = cookie.split('&');

            // Track if we've updated it
            var found = false;

            // Go through the pairs
            for (var i = 0; i < cookieParts.length; i++) {

                // Split the name and value
                var cookieData = cookieParts[i].split('=');

                if (cookieData.length == 2) {

                    // Update the status
                    if (cookieData[0] == 'Status_' + key) {
                        cookieData[1] = status;
                        found = true;
                    }

                    // Update the Stamp
                    if (cookieData[0] == 'Stamp_' + key) {
                        cookieData[1] = stamp;
                    }
                }

                // Re-build the name value pair
                cookieParts[i] = cookieData.join('=');
            }

            // If found then update the cookie string - else append to it
            if (found) {
                cookie = cookieParts.join('&');
            } else {
                cookie += '&Status_' + key + '=' + status + '&Stamp_' + key + '=' + stamp;
            }
        } else {
            cookie += 'Status_' + key + '=' + status + '&Stamp_' + key + '=' + stamp;
        }

        Plugins.CreateCookie(cookieName, cookie + '; path=/', 2000);
    },

    CreateCookie: function (name, value, days) {

        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";

        document.cookie = name + "=" + value + expires;
    },

    ReadCookieValue: function (cookieName, cookieKey) {

        var cookie = Plugins.ReadCookie(cookieName);

        if (cookie != null && cookie != '') {

            var cookieParts = cookie.split('&');

            for (var i = 0; i < cookieParts.length; i++) {

                var cookieData = cookieParts[i].split('=');

                if (cookieData.length == 2) {

                    if (cookieData[0] == cookieKey) {
                        return cookieData[1];
                    }
                }
            }
        }

        return null;
    },

    ReadCookie: function (name) {

        var nameEQ = name + "=";

        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, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }

        return null;
    }

}
