(function($) {

    var W = this, D = this.document;
    
    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('address_zip', /^([0-9]{5})$/);
    
    if(!($('#core').hasClass('confirmation'))) {
        var verifyDate = function() {
            var day = Number(BOX.form('registerForm').text('f1user_birthday').getValue());
            var month = Number(BOX.form('registerForm').text('f1user_birthmonth').getValue()) - 1;
            if (month < 0) {
                month = 11;
            }
            var year = Number(BOX.form('registerForm').text('f1user_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;
        };
        
        var reFieldParentCls = /\b(text|radioGroup|select|checkbox)\b/;
        var getFieldParent = function(field) {
            var t = field.parentNode, target;
            while (t.parentNode) {
                if (reFieldParentCls.test(t.className)) {
                    return t;
                }
                t = t.parentNode;
            }
        };
        
        var errorImg = '<img id="%id%" class="error box:id:formError" alt="%msg%" src="/img/common/picto/error.gif" />';
        
        var fieldsTypes = {
            'text': 'single',
            'password': 'single',
            'select-one': 'single',
            'radio': 'group',
            'checkbox': 'single'
        };
        
        var addErrorPicto = {
            single: function(p, img) {
                var t = $('label', p);
                if (t.length == 1) {
                    t.prepend(img);
                } else {
                    $(p).prepend(img);
                }
            },
            group: function(p, img) {
                var t = $('span.legend', p);
                if (t.length == 1) {
                    t.prepend(img);
                } else {
                    $(p).prepend(img);
                }
            }
        };
        
        var manageFieldError = function(e, msg) {
            if (e.namespace && e.namespace.length == 2) {
                var type = e.namespace[0], name = e.namespace[1], obj = this[type](name), field;
                if (obj.getElement(0)) {
                    if (obj.name.indexOf('birthmonth') > -1 || obj.name.indexOf('birthyear') > -1) {
                        field = this.text('f1user_birthday').getElement();
                        name = this.text('f1user_birthday').name;
                    } else {
                        field = obj.getElement(0);
                    }
                    if (msg) {
                        addFieldError(field, name, msg);
                    } else {
                        removeFieldError(field, name);
                    }
                }
                obj = field = null;
            }
        };
        LOP.manageFieldError = manageFieldError;
        
        var addFieldError = function(field, id, msg) {
            var p = getFieldParent(field);
            if (field.name.indexOf('birthmonth') > -1 || field.name.indexOf('birthyear') > -1) {
                p = p.parentNode.getElementsByTagName('label')[0];
            }
            $(p).addClass('error');
            id = id + 'Error';
            var img = $('#' + id);
            if (!img.length) {
                var type = fieldsTypes[field.type];
                if (type) {
                    addErrorPicto[type](p, errorImg.replace('%id%', id).replace('%msg%', msg));
                }
            } else {
                img.attr('alt', msg);
            }
        };
        
        var removeFieldError = function(field, id) {
            $('#' + id + 'Error').remove();
            var p = getFieldParent(field);
            $(p).removeClass('error');
        };
    

    }



    LOP.popinOpeningActions = {
    	menXTransformers: function() {
            BOX.form('registerForm').addValidation(function(form) {
                form.radio('f1user_title').mustValidate(function(field) {
                    if (!field.isChecked()) {
                        return l10n.errorMsg.required.civility;
                    }
                });
                
                form.text('f1user_firstname').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.fname;
                    }
                });
                
                form.text('f1user_lastname').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.lname;
                    }
                });
                
                form.text('f1user_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('f1user_birthmonth').isEmpty() && !form.text('f1user_birthmonth').isMatching('month')) || (!form.text('f1user_birthyear').isEmpty() && !form.text('f1user_birthyear').isMatching('year'))) {
                        return l10n.errorMsg.invalid.birthday;
                    } else {
                        if (!verifyDate()) {
                            return l10n.errorMsg.invalid.birthday;
                        }
                    }
                });
                form.text('f1user_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('f1user_birthday').isEmpty() && !form.text('f1user_birthday').isMatching('day')) || (!form.text('f1user_birthyear').isEmpty() && !form.text('f1user_birthyear').isMatching('year'))) {
                        return l10n.errorMsg.invalid.birthday;
                    } else {
                        if (!verifyDate()) {
                            return l10n.errorMsg.invalid.birthday;
                        }
                    }
                });
                
                form.text('f1user_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('f1user_birthday').isEmpty() && !form.text('f1user_birthday').isMatching('day')) || (!form.text('f1user_birthmonth').isEmpty() && !form.text('f1user_birthmonth').isMatching('month'))) {
                        return l10n.errorMsg.invalid.birthday;
                    } else {
                        if (!verifyDate()) {
                            return l10n.errorMsg.invalid.birthday;
                        }
                    }
                });
                
                form.text('f1user_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('f1user_email').isValid(true)) {
                        var value = form.text('f1user_email').getValue();
                        if (!field.isEqualTo(value)) {
                            return l10n.errorMsg.confirm.email;
                        }
                    }
                });
                
               form.text('f1user_address_line1').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.street;
                    }
                });
                
                form.text('f1user_address_line2').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.streetNumber;
                    }
                });
                
                form.text('f1user_address_city').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.city;
                    }
                });
                
                form.text('f1user_address_zip').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.zip;
                    } else if (!field.isMatching('address_zip')) {
                        return l10n.errorMsg.invalid.zip;
                    }
                });
                
                form.checkbox('accept_Conditions').mustValidate(function(field) {
                    if (!(field.isChecked())) {				
                        return l10n.errorMsg.required.acceptOffers;
                    }
                });	
    			/*
    			 form.radio('extendedproperty1_NewsletterAccept').mustValidate(function(field) {
                    if (field.isChecked()) {
                        form.text('f1extendedproperty1').setValue($('#newsletterAccept label').text() + ';#' + field.getValue() + ';');
                    }
    				else {
    					return l10n.errorMsg.required.extendedproperty1;
    				}
                });*/
                
                return l10n.errorMsg.form.plural;
            }, 'p.save').addListeners({
                'formError': {
                    fn: LOP.addFormError
                },
                'formValid': {
                    'fn': function(e, originalEvent) {
                        originalEvent.preventDefault();
                        LOP.removeFormError.call(e.owner, e, originalEvent);
                        $.get(l10n.url.getContestInfos + BOX.form('registerForm').text('f1user_email').getValue(), function(datas) {
                            if (datas.indexOf('___success___') > -1) {
                                LOP.popins.add({
                                    url: l10n.url.popinContestAlreadySigned,
                                    id: 'minisiteContestAlreadySigned',
                                    processHTML: LOP.processHTMLPopins,
                                    refresh: true
                                });
                            }
                            else {
                                W.__doPostBack(e.owner.submitName, '');
                            }
                        });
                    }
                },
                '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');
                    }
                }
            });

            
            /*
            $(".conditionsLink").click(function(e){
                e.preventDefault();
                window.open(this.href,'conditions','width=600,height=400,left=100,top=100,scrollbars=yes');
            });
            
            LOP.popins.addListener('open', function(e, id) {
                if (id == 'registerConditions') {
                    LOP.scrolls.registerConditions = new BOX.SimpleScroll({
                        'target': $('#popinRegisterConditions div.scroll')[0]
                    });
                }
            });
            */
        }
    };
    
    LOP.popinClosingActions = {
    	menXTransformers: function() {
    		LOP.popins.currentDOM.css('top', '-10000px');
            BOX.form('registerForm', true);
    	}
    };
    
})(jQuery);
