﻿$(document).ready(function() {
	//spécial minisites
	if(document.getElementById("minisites") && gTypeProfile == "VIP"){
		top.location.replace("@@@successURL@@@");
	}
	//fin minisites
    (function($) {   
    var D = this.document;
    var myDatas = D.getElementById('myDatasMandatory');
    
    BOX.addFormRule('zip', /^[0-9]{5}$/);
    BOX.addFormRule('day', /^(([123][01])|([012]?[1-9]))$/);
    BOX.addFormRule('month', /^((1[012])|(0?[1-9]))$/);
    BOX.addFormRule('year', /^((19[0-9]{2})|(20[0-9]{2}))$/);
	//BOX.addFormRule('password', /^[a-zA-Z0-9]{5,}$/); 
	BOX.addFormRule('password', /^[a-zA-Z0-9@_#-]{5,}$/); 
    
    var verifyDate = function() {
        var day = Number(BOX.form('registerForm').text('birthday').getValue());
        var month = Number(BOX.form('registerForm').text('birthmonth').getValue()) - 1;
        if (month < 0) {
            month = 11;
        }
        var year = Number(BOX.form('registerForm').text('birthyear').getValue());
        var date = new Date();
        var minAge = 15;
        if (!isNaN(day) && !isNaN(month) && !isNaN(year)) {
            if (year >= 1900 && year <= date.getFullYear() - minAge) {
                var original = year + '.' + month + '.' + day;
                var compute = new Date(year, month, day);
                var compare = compute.getFullYear() + '.' + compute.getMonth() + '.' + compute.getDate();
                return original == compare;
            }
            return false;
        } 
        return true;
    };
    
    BOX.form('registerForm').addValidation(function(form) {
        form.radio('title_list').mustValidate(function(field) {
            if (!field.isChecked()) {
                return l10n.errorMsg.required.civility;
            }
        });
        
        form.text('fname').mustValidate(function(field) {
            if (field.isEmpty()) {
                return l10n.errorMsg.required.fname;
            }
        });
        
        form.text('lname').mustValidate(function(field) {
            if (field.isEmpty()) {
                return l10n.errorMsg.required.lname;
            }
        });
        
        form.text('birthday').mustValidate(function(field) {
            if (field.isEmpty()) {
                return l10n.errorMsg.required.birthday;
            } else if (!field.isMatching('day')) {
                return l10n.errorMsg.invalid.birthday;
            } else if ((!form.text('birthmonth').isEmpty() && !form.text('birthmonth').isMatching('month')) || (!form.text('birthyear').isEmpty() && !form.text('birthyear').isMatching('year'))) {
                return l10n.errorMsg.invalid.birthday;
            } else {
                if (!verifyDate()) {
                    return l10n.errorMsg.invalid.birthday;
                }
            }
        });
        
        form.text('birthmonth').mustValidate(function(field) {
            if (field.isEmpty()) {
                return l10n.errorMsg.required.birthday;
            } else if (!field.isMatching('month')) {
                return l10n.errorMsg.invalid.birthday;
            } else if ((!form.text('birthday').isEmpty() && !form.text('birthday').isMatching('day')) || (!form.text('birthyear').isEmpty() && !form.text('birthyear').isMatching('year'))) {
                return l10n.errorMsg.invalid.birthday;
            } else {
                if (!verifyDate()) {
                    return l10n.errorMsg.invalid.birthday;
                }
            }
        });
        
        form.text('birthyear').mustValidate(function(field) {
            if (field.isEmpty()) {
                return l10n.errorMsg.required.birthday;
            } else if (!field.isMatching('year')) {
                return l10n.errorMsg.invalid.birthday;
            } else if ((!form.text('birthday').isEmpty() && !form.text('birthday').isMatching('day')) || (!form.text('birthmonth').isEmpty() && !form.text('birthmonth').isMatching('month'))) {
                return l10n.errorMsg.invalid.birthday;
            } else {
                if (!verifyDate()) {
                    return l10n.errorMsg.invalid.birthday;
                }
            }
        });
        
        if (!myDatas) {
            form.text('email').mustValidate(function(field) {
                if (field.isEmpty()) {
                    return l10n.errorMsg.required.email;
                } else if (!field.isMatching('email')) {
                    return l10n.errorMsg.invalid.email;
                }
            });
            
            form.text('email_conf').mustValidate(function(field) {
                if (form.text('email').isValid(true)) {
                    var value = form.text('email').getValue();
                    if (!field.isEqualTo(value)) {
                        return l10n.errorMsg.confirm.email;
                    }
                }
            });
        }
        
        if (myDatas) {
            form.text('old_password').mustValidate(function(field) {
                if (!field.isEmpty() && !field.isMatching('password')) {
                    return l10n.errorMsg.invalid.pwd;
                }
            });
        }
        
        form.text('password').mustValidate(function(field) {
            if (!myDatas || (!form.text('old_password').isEmpty() && form.text('old_password').isValid(true))) {
                if (field.isEmpty()) {
                    return l10n.errorMsg.required.pwd;
                } else if (!field.isMatching('password')) {
                    return l10n.errorMsg.invalid.pwd;
                }
            }
        });
        
        form.text('password_conf').mustValidate(function(field) {
            if (form.text('password').isValid(true) && !field.isEqualTo(form.text('password').getValue())) {
                return l10n.errorMsg.confirm.pwd;
            }
        });
        
        //community
        form.radio('ep1rlVIP_visible_profile').mustValidate(function(field) {
            var sf = (this.getValue() == "1")? "" : gLabels.sfdatastring;
            form.text('stfdatas').setValue(sf);
            if (!field.isChecked()) {
                return gLabels.registerError;
            }
        });
        
        form.checkbox('ep1cbVIP_accept_conditions').mustValidate(function(field) {
            if (!field.isChecked()) {
                return gLabels.registerError;
            }
        });
        //fin community
        
        form.radio('ep1rlNewsletter').mustValidate(function(field) {
            if (!field.isChecked()) {
                return l10n.errorMsg.required.newsletter;
            }
        });
        
        return l10n.errorMsg.form.plural;
    }, 'p.save').addListeners({
        'formError': {
            fn: LOP.addFormError
        },
        'formValid': {
            fn: function(e, originalDomEvent) {
                //insertion code promo
                if($('#pcode').val() != ''){
                    if(typeof originalDomEvent == 'object') {
                        originalDomEvent.preventDefault(); //pour empêcher l'action par défaut
                    }
                    var callback = function(msg, textStatus, XMLHttpRequest){
                        var msg = (typeof selector == "string") ? msg : msg.toString();
                        if(msg.indexOf('true') >= 0){
                            var mess= 'Code promo validé';
                            
                            //on applique la bonne valeur à l'input EP VIP_Promo
                            $('#codepromoField .codeValue').val($('#pcode').val());
                            
                            //on submite le form
                            __doPostBack(BOX.form('registerForm').submitName, '');
                        }
                        else{
                            var mess= 'Le code saisi n’est pas valide ou a déjà été utilisé';
                            $('#promotionCode .message').text(mess);
                            $('#promotionCode .message').fadeIn();
                        }
                    }
                    $.ajax({
                        type: "GET",
                        url: gVIPpath + "webboxtools/code-promo.aspx",
                        data: "rules=promoPoints&promoCode="+$('#pcode').val(),
                        success: callback
                    });
                }
                else{
                    $.cookie('logout', 'false', {expires: 0.1});
                    LOP.removeFormError.call(e.owner, e);
                }
            }
        },
        'fieldError': {
            'fn': LOP.manageFieldError
        },
        'fieldValid': {
            'fn': LOP.manageFieldError
        }
    }).addReplacement({'maxHeight': 150});
    
    LOP.tooltips.add({
        selector: '#registerForm:hover',
        ruleNamespace: 'formError',
        rule: function(el) {
            if (el.nodeName.toLowerCase() == 'img') {
                this.setHTML(el.alt).setAttributeCache(el, 'alt').setId('toolTipError');
            }
        }
    });
    
    if (D.getElementById('errorAlreadySigned')) {
        $('#registerFormError').css('display', 'block');
    }
    
    /* Start FacebookConnect Implementations */
    if(LOP.FBC) {
        var fillFieldsWithFBDatas = function() {
            $('#fbFieldsCompletion').html('<p><span class="visual"><img alt="' + l10n.FB.generic.connect + '" src="/img/l10n/btn/fbConnect25x25.png" /></span><span class="content">' + l10n.FB.labels.datasAlreadyFilledWithFBC + '</span></p>');
            
            FB.api('/me', function(response) {
                var fbBDay = response.birthday.split('/'), form = BOX.form('registerForm'); 
                
                form.text('fname').setValue(response.first_name);
                form.text('lname').setValue(response.last_name);
                form.text('birthday').setValue(fbBDay[1]);
                form.text('birthmonth').setValue(fbBDay[0]);
                form.text('birthyear').setValue(fbBDay[2]);
            });
        };
        
        LOP.FBC.checkStatus({
            logged: function() {
                fillFieldsWithFBDatas();
            },
            notLogged: function() {
                $('#fbFieldsCompletion').html('<a href="#" class="FBLink"><img alt="' + l10n.FB.labels.fillDatasWithFBC + '" src="/img/l10n/btn/fbConnectDatasCompletion22.png" /></a>');
                
                $('#fbFieldsCompletion .FBLink').click(function(e) {
                    e.preventDefault();
                    FB.login(function(r) {
                        if(r.session) {
                            fillFieldsWithFBDatas();
                        }
                    }, {perms: 'user_birthday'});
                });
            }
        });
    }
    /* End FacebookConnect Implementations */
    
})(jQuery);
});
// **************************************** VIP CARD POPIN DETAIL AND CONDITIONS ****************************************
function openConditions(tag){
    document.getElementById("popinConditions").style.display = "block";
    if(!navig.IE6){
        var dragPopinComment = new BOX.SimpleDrag({
            'root': '#popinConditions',
            'handle': '#popinConditionsTitle',
            'minX': -200,
            'minY': 0,
            'maxX': 814,
            'maxY': 812 - $("#popinConditions").height()
        });
    }
    LOP.scrolls.condiScroll.compute();
    if(typeof tag == 'string' && vipStats[tag]) {
        LOP.execStatCM(vipStats[tag]);
    }
}
function closeConditions(){
    document.getElementById("popinConditions").style.display = "none";
}
// **************************************** FIN VIP CARD POPIN DETAIL AND CONDITIONS ****************************************
