/**
 * @author florent@ezoulou.be 20092010 - feel free to use
 */
/* var used when setting the focus on email field */
var origEmailStr = null;
/* step nav translations -> included in forms.xsl so you should just translate those in /lang/master.xx.xml */
try {
    if (validate == null) 
        validate = 'valider';
} 
catch (e) {
    validate = 'valider';
}
try {
    if (returnStr == null) 
        returnStr = 'retour';
} 
catch (e) {
    returnStr = 'retour';
}

$(document).ready(function(){
    // store original email value into global variable
    origEmailStr = $('.formItem.email .formField').val();
    // actions happening on fields focus
    $('.formItem .formField').focus(function(){
        // remove style (red color)
        $(this).parent().removeClass('warning');
        
    });
    // activate steps mechanism
    activateStepsSystem();
    // activate substeps mechanism
    activateSubstepsSystem();
    
    // hide all radio buttons
    $('input[type="radio"]').hide();
    
    /*
     * SPECIALS : hide every next field after 'other' checkebox
     */
    for (var i = 0; i < $('.checkbox .formField[value*="Autre"]').length; i++) {
        $('.checkbox .formField[value="Autre"]:eq(' + i + ')').parent().parent().parent().next('.formItem:first').hide();
    }
    for (var i = 0; i < $('.checkbox .formField[value*="Other"]').length; i++) {
        $('.checkbox .formField[value="Autre"]:eq(' + i + ')').parent().parent().parent().next('.formItem:first').hide();
    }
    /*
     * click action on checkbox
     */
    $('.checkbox .formWrapper').click(function(){
    
        /*
         * SPECIALS : for the show/hide effect on next text field following checkbox with the 'OTHER' choice.
         */
        if ($(this).parent().parent().hasClass('formItem') && $(this).parent().parent().hasClass('checkbox')) {
            if ($(this).find('.formField').val() == 'Autre' || $(this).find('.formField').val() == ' Autre ' || $(this).find('.formField').val() == ' Other ' || $(this).find('.formField').val() == 'Other') {
                $(this).parent().parent().next('.formItem:first').slideDown();
            }
            else 
                if ($(this).parent().find('.formField[value*="Autre"]').length > 0 || $(this).parent().find('.formField[value*="Other"]').length > 0) {
                    $(this).parent().parent().next('.formItem:first').slideUp();
                }
        }
        
        /*
         * otherwise
         */
        // test it current substep is not already active...   
        if ($(this).hasClass('active')) 
            return false;
        else {
            if ($(this).parent().parent().hasClass('warning')) {
                $(this).parent().parent().find('.formAlert:first').remove();
                $(this).parent().parent().removeClass('warning');
            }
            $(this).parent().find('.formWrapper').removeClass('active');
            $(this).addClass('active');
            $(this).find('input[type="radio"]').attr('checked', 'checked'); // needed since it is display:none; 
        }
        return false;
    });
    
    /*
     * form validation
     */
    $('form.form').submit(function(){
        // we check the current step
        if ($(this).find('.formStep.active').length > 0) {
            if (formItemsCheck($(this).find('.formStep.active'), true)) {
                if ($(this).find('.formStep.active').hasClass('last')) {
                    // and is the last step, we submit
                    return true;
                }
                else {
                    // otherwise we display the next step
                    $(this).find('.formStep.active').slideUp(function(){
                        $(this).removeClass('active');
                        $(this).nextAll('.formStep:first').slideDown();
                        $(this).nextAll('.formStep:first').addClass('active');
                    });
                    // we don't submit now, we have some more steps to visit 
                    return false;
                }
            }
            else {
                // current step is not validated 
                return false;
            }
        }
        // case of the forms without steps
        else {
            if (formItemsCheck($(this), true)) {
                // we submit
                return true;
            }
            else {
                // form is not validated 
                return false;
            }
        }
    });
});



function activateStepsSystem(){
    /* 
     * MAIN stepsr
     * navigation
     *
     */
    // hide every step
    $('.formStep').hide();
    
    // activate last class on last step
    $('.formStep:last').addClass('last');
    // show first step
    $('.formStep:first').show();
    $('.formStep:first').addClass('active');
    $('.formStep').append('<a class="button" href="#">' + validate + '</a>');
    // remove next step button from the last step
    $('.formStep a.button:last').remove();
    // action for the button
    $('.formStep a.button').click(function(){
        if (formItemsCheck($(this).parent(), true)) {
            $(this).parent().slideUp(function(){
                $(this).removeClass('active');
                $(this).nextAll('.formStep:first').slideDown();
                $(this).nextAll('.formStep:first').addClass('active');
                $(this).nextAll('.formStep:first').find('.formField:first').focus();
            });
        }
        return false;
    });
    // create the button to go return to previous step
    $('.formStep').append('<a class="return" href="#">' + returnStr + '</a>');
    // remove next step button from the first step	
    $('.formStep a.return:first').remove();
    
    // action for the return link
    $('.formStep a.return').click(function(){
        $(this).parent().slideUp(function(){
            $(this).removeClass('active');
            $(this).prevAll('.formStep:first').slideDown();
            $(this).prevAll('.formStep:first').addClass('active');
            $(this).prevAll('.formStep:first').find('.formField:first').focus();
        });
    });
}

function activateSubstepsSystem(){
    /*
     * hides substeps
     */
    $('.substep').hide();
    
    /*
     * hide cancel button
     */
    $('.substepKicker.stepCancel').hide();
    
    /*
     * event to show substep
     */
    $('.substepKicker').click(function(){
        // clear warnings
        if ($(this).parent().hasClass('warning')) {
            $(this).parent().find('.formAlert:first').remove();
            $(this).parent().removeClass('warning');
            // clear childrens warnings
            $(this).parent().find('.formItem').removeClass('warning');
        }
        // show cancel button
        
        if ($(this).hasClass('stepCancel')) {
            $(this).hide();
        }
        else {
            $(this).parent().find('.substepKicker.stepCancel').show();
        }
        // test it current substep is not already active...   
        if ($(this).nextAll('.substep:first').hasClass('active')) 
            return false;
        // in case a substep is already active
        if ($(this).parent().find('.substepKicker.active').length > 0) {
            // clear previous
            $(this).parent().find('.substepKicker.active').next().hide();
            $(this).parent().find('.substepKicker.active').next().removeClass('active');
            $(this).parent().find('.substepKicker.active').removeClass('active');
            //            $(this).parent().find('.substep.active').hide();
            //            $(this).parent().find('.substep.active').removeClass('active');
            // activate current
            $(this).addClass('active');
            $(this).nextAll('.substep:first').slideDown();
            $(this).nextAll('.substep:first').addClass('active');
            $(this).find('input[type="radio"]').attr('checked', 'checked'); // needed since it is display:none;
        }
        else {
            // in case we just arrived in the page : no substep is active yet
            $(this).addClass('active');
            $(this).nextAll('.substep:first').slideDown();
            $(this).nextAll('.substep:first').addClass('active');
            $(this).find('input[type="radio"]').attr('checked', 'checked'); // needed since it is display:none; 
        }
        return false;
    });
}



/*
 * forms functions
 */
function formItemsCheck(node, showMessage){
    var checkedOk = true;
    /*
     * checking the active substep fields
     */
    if (node.find('.formItem').length > 0) {
        if (node.find('.substep.active').length > 0) {
            for (var i = 0; i < node.find('.substep.active .formItem.required').length; i++) {
                var formItem = node.find('.substep.active .formItem.required:eq(' + i + ')');
                if (!formItemCheck(formItem, showMessage)) 
                    checkedOk = false;
            }
        }
        /*
         * otherwise checking the whole fields of the current step (or the whole form if there are no steps)
         */
        else {
            for (var i = 0; i < node.find('.formItem.required').length; i++) {
                // current form item (one form item = one field) 
                var formItem = node.find('.formItem.required:eq(' + i + ')');
                if (!formItemCheck(formItem, showMessage)) 
                    checkedOk = false;
            }
        }
    }
    return checkedOk;
}

function formItemCheck(formItem, showMessage){
    var checkedOk = true;
    // text or textarea
    if (formItem.hasClass('text') || formItem.hasClass('message')) {
        if (formItem.find('.formField').val() == '' || formItem.find('.formField').text() == 'required') {
            checkedOk = false;
            if (showMessage) {
                formItem.find('.formField').parent().addClass('warning');
                //                formItem.find('.formField').attr('value', 'required');
            }
        }
    }
    else 
        // email
        if (formItem.hasClass('email')) {
            if (formItem.find('.formField').val() == '' ||
            formItem.find('.formField').val() == origEmailStr ||
            formItem.find('.formField').val() == 'required' ||
            !isValidEmailAddress(formItem.find('.formField').val())) {
                checkedOk = false;
                if (showMessage) {
                    formItem.find('.formField').parent().addClass('warning');
                /*                    if (formItem.find('.formField').val() == '') {
                 formItem.find('.formField').attr('value', 'required');
                 }
                 */
                }
            }
        }
        else 
            // file
            if (formItem.hasClass('file')) {
                if (formItem.find('.formField').val() == '') {
                    checkedOk = false;
                    if (showMessage) {
                        formItem.find('.formField').parent().addClass('warning');
                        formItem.find('.formField').parent().find('.formAlert').remove();
                        formItem.find('.formField').parent().prepend('<div class="formAlert">required</div>');
                    }
                }
            }
            else 
                // substep checkbox 
                if (formItem.hasClass('checkbox') && formItem.hasClass('hasSubstep')) {
                    if (formItem.find('.substepKicker .formField:checked').length == 0) {
                        checkedOk = false;
                        if (showMessage) {
                            formItem.addClass('warning');
                            formItem.find('.formAlert:first').remove();
                            formItem.prepend('<div class="formAlert">required</div>');
                        }
                    }
                }
                else 
                    // default checkbox
                    if (formItem.hasClass('checkbox')) {
                        if (formItem.find('.formField:checked').length == 0) {
                            checkedOk = false;
                            if (showMessage) {
                                formItem.addClass('warning');
                                formItem.find('.formAlert:first').remove();
                                formItem.prepend('<div class="formAlert">required</div>');
                            }
                        }
                    }
    return checkedOk;
}

function isValidEmailAddress(emailAddress){
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}
