if (Mxm == undefined) {
    var Mxm = {};
}

if (Mxm.Subscribe == undefined) {
    Mxm.Subscribe = {};
}

Array.prototype.in_array = function(p_val)
{
    for(var i = 0, l = this.length; i < l; i++) {
        if(this[i] == p_val) {
            rowid = i;
            return true;
        }
    }
    return false;
}

Array.prototype.any_in_array = function(vals)
{
    for (var i = 0, l = vals.length; i < l; i++) {
        if (this.in_array(vals)) {
            return true;
        }
    }

    return false;
}

Mxm.Subscribe.Survey = {
    _hasErrorOnJoin : false,
    _pollsStudies : null,
    _pollsJob : null,
    _pollsFamily : null,

    init : function() {
        this._pollsStudies = new Array('poll[31][27]');
        this._pollsJob = new Array(
            'poll[29][25]','poll[30][26]', 'poll[32][28]'
        );
        this._pollsFamily = new Array(
            'poll[15][11]', 'poll[65][60]', 'poll[211][189]'
        );
    },

    showStep : function (stepKey) {
        // click on <h1> .. show
        $(stepKey).show();
        // do not allow button display
        if ($('validate_' + stepKey) !== 'undefined') {
            $('validate_' + stepKey).hide();
        }
        else {
            $('validate_survey_end').hide();
        }
    },

    idByElmName : function (name) {
        if (name == 'poll1') {
            return 'poll-31-27';
        }
        else if (name == 'poll2') {
            return 'poll-29-25';
        }
        else if (name == 'poll3') {
            return 'poll-30-26';
        }
        else if (name == 'poll4') {
            return 'poll-32-28';
        }
        else if (name == 'poll5') {
            return 'poll-15-11';
        }
        else if (name == 'poll6') {
            return 'poll-65-60-non';
        }
        else if (name == 'poll7') {
            return 'poll:1310';
        }
        else {
            // not a poll field
            return 'no_poll';
        }
    },

    activateStep : function (stepKey, activeStep) {

        var fieldsToValidate = new Array;
        if (activeStep == 'survey_subscription_general') {
            // general fields
            fieldsToValidate = new Array(
                'civilite', 'prenom', 'nom',
                'datenaiss_jour', 'datenaiss_mois', 'datenaiss_annee',
                'email', 'email_confirm', 'passe', 'password_confirm',
                'tel', 'telportable', 'flyer', 'addr1', 'addr2',
                'cp', 'ville', 'pays'
            );
        }
        else if (activeStep == 'survey_subscription_studies') {
            // general fields + studies
             fieldsToValidate = new Array(
                'civilite', 'prenom', 'nom',
                'datenaiss_jour', 'datenaiss_mois', 'datenaiss_annee',
                'email', 'email_confirm', 'passe', 'password_confirm',
                'tel', 'telportable', 'flyer', 'addr1', 'addr2',
                'cp', 'ville', 'pays', 'poll1'
            );
        }
        else if (activeStep == 'survey_subscription_job') {
            // general fields + studies + job
             fieldsToValidate = new Array(
                'civilite', 'prenom', 'nom',
                'datenaiss_jour', 'datenaiss_mois', 'datenaiss_annee',
                'email', 'email_confirm', 'passe', 'password_confirm',
                'tel', 'telportable', 'flyer', 'addr1', 'addr2',
                'cp', 'ville', 'pays', 'poll1', 'poll2',
                'poll3', 'poll4'
            );
        }
        else if (activeStep == 'survey_subscription_family') {
            // general fields + studies + job
             fieldsToValidate = new Array(
                'civilite', 'prenom', 'nom',
                'datenaiss_jour', 'datenaiss_mois', 'datenaiss_annee',
                'email', 'email_confirm', 'passe', 'password_confirm',
                'tel', 'telportable', 'flyer', 'addr1', 'addr2',
                'cp', 'ville', 'pays', 'poll1', 'poll2',
                'poll3', 'poll4', 'poll5', 'poll6', 'poll7'
            );
        }

        var confirmUrl = $('checkform').value;
        var needsQuestionMark = true;
        if (confirmUrl.indexOf('?') !== -1) {
            needsQuestionMark = false;
        }
        confirmUrl += (needsQuestionMark ? '?' : '&') + 'validateAll=1';
        // append all elements' values for validation
        var cntFieldsToValidate = fieldsToValidate.length;
        var elmCollection = Form.getElements($('inscription_v2'));
        var workingField = '';
        var hasValue = false;
        var hasValue1 = false;
        var hasDoneLastPoll = false;
        var hasDonePoll6 = false;
        var countPollAnswers = 0;
        var countPollAnswers1 = 0;
        elmCollection.each( function(elm) {
            var fieldName = '';
            fieldName = elm.name;
            var doNotValidate = false;

            if (fieldsToValidate.in_array(fieldName)) {
                // element at current iterator position needs
                // validation in this step
                if (fieldName == 'civilite' && elm.checked) {
                    confirmUrl += '&' + fieldName + '=' + escape(elm.value);
                }
                else if (fieldName != 'civilite') {
                    confirmUrl += '&' + fieldName + '=' + escape(elm.value);
                }
            }
        });

        var errorFields = $$('.error');
        for (var x = 0; x < errorFields.length; x++) {
            // hide all error fields, validation will be done again..
            errorFields[x].remove();
        }

        // validate common fields (no polls)
        var validateStep = new Ajax.Request(
            confirmUrl,
            {
                method: 'get',
                parameters: '',
                asynchronous: false,
                onSuccess : function (xhrObj) {
                    if (xhrObj.responseText.indexOf('clean') !== -1) {
                        // fields have been validated

                        // look if there are some polls to validate ; if so we need
                        // to validate them too, before displaying next step
                        // polls validation has been moved to another action in order
                        // to be compatible with any locale..
                        var stepPollRel = 'poll_';
                        switch (activeStep) {
                            case 'survey_subscription_studies' :
                                stepPollRel = stepPollRel + 'studies';
                                break;

                            case 'survey_subscription_job' :
                                stepPollRel = stepPollRel + 'job';
                                break;

                            case 'survey_subscription_family' :
                                stepPollRel = stepPollRel + 'family';
                                break;

                            default :
                                stepPollRel = '';
                                break;
                        }

                        var errorPollsElm   = new Array();
                        if (stepPollRel != '') {

                            // get all polls to validation for the current step
                            // all polls are generated with a 'rel' attribute set to
                            // a currents step's unique id
                            var userAnswers     = new Array();
                            $$('div.ipolls[rel="' + stepPollRel + '"]').each (function(pollElm) {

                                var pollSelectElm   = pollElm.down('select');
                                var pollCheckboxElm = pollElm.down('input[type="checkbox"]');
                                var pollRadioElm    = pollElm.down('input[type="radio"]');
                                var pollTextElm     = pollElm.down('input[type="text"]');

                                var parentElm = pollElm.up('div');

                                // parentElm is :
                                // div#{activeStep} ||
                                // div#poll:child:{x}

                                var elementIsVisible = parentElm.visible();

                                if (elementIsVisible === false) {
                                    // no validation needed for current element,
                                    // its display attribute is set to "none"
                                    return ;
                                }

                                var userChoice      = 'default';

                                // for each found element, we need to get the user's choice (if any)

                                if (typeof(pollSelectElm) != 'undefined') {

                                    userChoice = pollSelectElm.options[pollSelectElm.selectedIndex].value;
                                }

                                if (typeof(pollTextElm) != 'undefined') {

                                    userChoice = pollTextElm.value;
                                }

                                if (typeof(pollCheckboxElm) != 'undefined') {

                                    // we need to go up to the div.ipolls in order to get
                                    // all ul.interest => these are the several choices for
                                    // current poll
                                    var parentUl = pollCheckboxElm.up('div.ipolls').down('ul.interest');
                                    var allChoices = new Array();
                                    var hasOneChoice = false;

                                    allChoices.push(parentUl);
                                    while ((parentUl = parentUl.next()) != null) {
                                        allChoices.push(parentUl);
                                    }

                                    allChoices.each(function(ulElm) {
                                        var checkElm = ulElm.down('input[type="checkbox"]');

                                        if (checkElm.checked) {
                                            userChoice = checkElm.value;
                                            hasOneChoice = true;
                                        }
                                    });

                                }

                                if (typeof(pollRadioElm) != 'undefined') {

                                    var pollChoices = $$('input[name="' + pollRadioElm.name + '"]');

                                    pollChoices.each(function(radioElm) {
                                        if (radioElm.checked) {
                                            userChoice = radioElm.value;
                                        }
                                    });
                                }

                                if (
                                    elementIsVisible &&
                                    (userChoice == '' || userChoice == 'default' || userChoice == 0)
                                ) {
                                    // no answer for current poll

                                    errorPollsElm.push(pollElm);
                                }

                            });

                        } // endif: stepPollRel != ''

                        // do ajax request for displaying poll errors (if any)
                        if (errorPollsElm.length > 0) {
                            // has polls errors

                            var pollErrorDisplayUrl = $('poll_display_error').value;
                            pollErrorDisplayUrl = pollErrorDisplayUrl;

                            // ajax request for getting message to display
                            new Ajax.Request(pollErrorDisplayUrl, {
                                method: 'get',
                                parameters: '',
                                asynchronous : false,
                                onSuccess : function(transport) {

                                    var errorMsg = transport.responseText;

                                    errorPollsElm.each(function(pollElm) {
                                        // for each poll having no selected choice,
                                        // print an error message

                                        var errorDiv = new Element('div');
                                        errorDiv.addClassName('error');
                                        var errorUl = new Element('ul');
                                        var errorLi = new Element('li');

                                        errorLi.update(errorMsg);

                                        // insert poll error after the poll div
                                        Element.insert(pollElm, {'after': errorDiv});
                                        Element.insert(errorDiv,{'top'  : errorUl});
                                        Element.insert(errorUl, {'top'  : errorLi});
                                    });
                                }
                            });

                        }
                        else {
                            // step validation done successfully. The user has answered
                            // all polls and has filled all needed information

                            $('validate_' + activeStep).hide();

                            if ($(stepKey)) {
                                $(stepKey).show();
                            }
                            if ($('validate_' + stepKey)) {
                                $('validate_' + stepKey).show();
                            }

                            if (stepKey == 'survey_subscription_end') {
                                var isJsSubscription = new Element('input');
                                isJsSubscription.setAttribute('type', 'hidden');
                                isJsSubscription.setAttribute('value', '1');
                                isJsSubscription.setAttribute('name', 'isJsSubscription');

                                Element.insert($('inscription_v2'), {'bottom' : isJsSubscription});

                                $('survey_end_step').show();
                                $('optin-cgv').show();
                                $('validate_survey_end').show();
                            }
                        }
                    }
                    else {
                    // has errors in general information data..

                        var fieldsWithError = xhrObj.responseText.split('##');

                        var count = fieldsWithError.length;
                        for (var i = 0; i < count; ++i) {
                            var data = fieldsWithError[i].split(':');
                            if (data[0] == 'datenaiss') {
                                data[0] = 'datenaiss_annee';
                            }

                            var newName = Mxm.Subscribe.Survey.idByElmName(data[0]);
                            if (newName !== 'no_poll') {
                                data[0] = newName;
                            }

                            var inputField = $(data[0]).up('p'); // need to insert AFTER <p>
                            var errorField = new Element('div');
                            errorField.className = 'error';

                            var errorMessages = new Array;
                            var countErrorForField = 0;

                            if (data[1].indexOf('|') !== -1) {
                                errorMessages = data[1].split('|');
                                countErrorForField = errorMessages.length;
                            }
                            else {
                                errorMessages.push(data[1]);
                                countErrorForField = errorMessages.length;
                            }

                            var ulField = new Element('ul');
                            try {
                                // insert div container + ul
                                Element.insert(inputField, {'after' : errorField});
                                Element.insert(errorField, {'top'   : ulField});
                            }
                            catch (exc) {
                                break;
                            }

                            // any error is: <div class="error"><ul><li>ERROR</li> ... </ul></div>
                            var liFields= new Array;
                            for (var j = 0; j < countErrorForField; ++j) {
                                var tmpLi = new Element('li');
                                tmpLi.update(errorMessages[j]);

                                try {
                                    Element.insert(ulField, {'bottom' : tmpLi});
                                }
                                catch (exc) {
                                    ;
                                }
                            }
                        }
                    }
                }
            }
        );
    },

    validateLastStep : function()
    {
        var returnBool = true;

        // remove already existing error divs
        if (! $$('p.mentions').first().next('div').hasClassName('survey_optinError')) {
            // has error div before div.survey_optinError
            // div.survey_optinError is used as fix for getting already
            // existing error divs
            $$('p.mentions').first().next('div').remove();
        }

        if ($$('p.botCheck').first().down('div')) {
            // already has CGV error div
            $$('p.botCheck').first().down('div').remove();
        }

        if (! $('subscription:survey').checked) {

            var errorDisplayUrl = $('poll_display_error').value;
            errorDisplayUrl = errorDisplayUrl + '?is_survey=1';

            new Ajax.Request(errorDisplayUrl, {
                method : 'get',
                parameters: '',
                asynchronous: false,
                onSuccess : function (transport)
                {
                    var errorDiv = new Element('div');
                    errorDiv.addClassName('error');
                    errorDiv.addClassName('mT5');

                    var errorUl = new Element('ul');
                    var errorLi = new Element('li');

                    errorLi.update(transport.responseText);

                    // insert error after survey optin
                    Element.insert($$('p.mentions').first(), {'after' : errorDiv});
                    Element.insert(errorDiv,{'top'  : errorUl});
                    Element.insert(errorUl, {'top'  : errorLi});
                }
            });

            returnBool = false;
        }

        if (! $('subscription:cgv').checked) {

            var errorDisplayUrl = $('poll_display_error').value;
            errorDisplayUrl = errorDisplayUrl + '?is_cgv=1';

            new Ajax.Request(errorDisplayUrl, {
                method : 'get',
                parameters: '',
                asynchronous: false,
                onSuccess : function (transport)
                {
                    var errorDiv = new Element('div');
                    errorDiv.addClassName('error');
                    errorDiv.addClassName('mT5');
                    var errorUl = new Element('ul');
                    var errorLi = new Element('li');

                    errorLi.update(transport.responseText);

                    // insert error after CGV
                    Element.insert($('subscription:cgv').up('p.botCheck'), {'bottom':errorDiv});
                    Element.insert(errorDiv,{'top'  : errorUl});
                    Element.insert(errorUl, {'top'  : errorLi});
                }
            });

            returnBool = false;
        }

        return returnBool;
    },

    validateStep1 : function() {
        new Ajax.Request(
            $('validateform').value,
            {
                asynchronous : false,
                method : 'get',
                parameters : '',
                onSuccess : function(response) {
                    ; // no work needed, graphics changed from php
                }
            }
        );
    },

    validateStep1GeneralInfo : function(urlCheck) {
        var fieldsText = $('inscription_v2').getInputs('text');
        var fieldsPass = $('inscription_v2').getInputs('password');
        var idNames = new Array();

        fieldsText.each( function(elm) {
            idNames.push(elm.id)
        });

        fieldsPass.each( function(elm) {
            idNames.push(elm.id)
        });

        var countElm = idNames.length;
        for (var i = 0; i < countElm; ++i) {
            var urlArgument = idNames[i] + '=' + $(idNames[i]).value;
            urlCheck += (i == 0) ? '?' + urlArgument : '&' + urlArgument;
        }

        new Ajax.Request(urlCheck, {
            method: 'get',
            asynchronous: true,
            parameters : '',
            onComplete : function(XHR, eJSON) {
                try {
                    eval(eJSON);
                }
                catch (e) {
                    ; //
                }

                if (Ajax.clicked_obj && Ajax.clicked_obj.submited) {
                    Ajax.clicked_obj.submited = false;
                }
                if (Ajax.loading_cnt > 0) {
                    Ajax.loading_cnt--;
                }
                if (Ajax.loading_cnt == 0) {
                    Ajax.loading_div.hide();
                }

                var invalidCollection = $('inscription_v2').down('.invalid');

                if (typeof invalidCollection == 'undefined') {
                    $('validate_survey_subscription_general').hide();
                    $('survey_subscription_studies').show();
                }
                else {
                    return false;
                }
            }
        });
    }
};

