(function($) {
    var W = this, D = this.document;
    
    $(D).ready(function() {
        
        /* for testing purposes : simulates flash call */
        /*
        if (D.getElementById('main')) {
            $('a.openCommentPopin').click(function(e) {
                e.preventDefault();
                LOP.callCommentPopin();
            });
        }
        */
       
        //LOP.popins.insertPoint = $('#popin');
        
        if (D.getElementById('loginOnlyOK') || D.getElementById('loginOK')) {
            var user = {
                name: $('#userName').html(),
                id: $('#userId').html()
            };
            parent.window.LOP.user = user;
            parent.window.$('#popin').before('<div id="logged">' + 
                                             '    <span id="userName">' + user.name + '</span>' +
                                             '    <span id="userId">' + user.id + '</span>' +
                                             '</div>');
            
            if (D.getElementById('loginOnlyOK')) {
                /* popin login only */
                parent.document.getElementById('MenExpert').setUser({
                    name: user.name,
                    id: user.id
                });    
            }
            if (D.getElementById('loginOK')) {
                /* popin login, sends to comment form */
                parent.document.getElementById('MenExpert').setUser({
                    name: parent.window.LOP.user.name,
                    id: parent.window.LOP.user.id
                }, true);
            }
            
            parent.window.closeIFramePopin();
        }
        
        if (D.getElementById('popinLoginMenExpert2010')) {
            parent.window.centerIFramePopin();
            var top = parseInt(parent.window.$('#iFramePopin').css('top').split('px')[0], 10);
            if (top < 120) {
                parent.window.$('#iFramePopin').css('top', '120px');
            }
            /* login form */
            BOX.form('loginForm').addValidation(function(form) {
                form.text('login').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.email;
                    } else if (!field.isMatching('email')) {
                        return l10n.errorMsg.invalid.email;
                    }
                });
                form.text('password').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.pwd;
                    } else if (!field.isMatching('password')) {
                        return l10n.errorMsg.invalid.pwd;
                    }
                });
                return l10n.errorMsg.form.plural;
            }, 'p.save').addListeners({
                'formError': {
                    'fn': LOP.addFormError
                },
                'formValid': {
                    'fn': LOP.removeFormError
                },
                'fieldError': {
                    'fn': LOP.manageFieldError
                },
                'fieldValid': {
                    'fn': LOP.manageFieldError
                }
            });
            
            LOP.tooltips.add({
                selector: '#loginForm:hover',
                ruleNamespace: 'formError',
                rule: function(el) {
                    if (el.nodeName.toLowerCase() == 'img') {
                        this.setHTML(el.alt).setAttributeCache(el, 'alt').setId('toolTipError');
                    }
                }
            });
            
            var hasFormError = $('#loginFormError').html();
            if (hasFormError) {
                $('#loginFormError').css('display', 'block');
            }
        }
        
        if (D.getElementById('popinRegisterMenExpert2010')) {
            /* register form */
            parent.window.$('#iFramePopin').css({
                'width': 960,
                'height': 800
            });
            parent.window.centerIFramePopin();
            parent.window.$('#iFramePopin').css({
                'top': '0'
            });
            $('#popinRegisterMenExpert2010 #closePopin').click(function(e) {
                parent.window.closeIFramePopin();
            });
        }
        
        if (D.getElementById('popinConfirmRegistration')) {
            /* registering complete */
            parent.window.$('#iFramePopin').css({
                'width': 407,
                'height': 135
            });
            parent.window.centerIFramePopin();
            var top = parseInt(parent.window.$('#iFramePopin').css('top').split('px')[0], 10);
            if (top < 120) {
                parent.window.$('#iFramePopin').css('top', '120px');
            }
            $('#popinConfirmRegistration a.close').click(function() {
                parent.window.LOP.callLoginPopin();
            });
        }
        
        if (D.getElementById('popinForgottenPassword') && !D.getElementById('forgottenPasswordConfirm')) {
            BOX.form('forgottenPasswordForm').addValidation(function(form) {
                form.text('login').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.errorMsg.required.email;
                    } else if (!field.isMatching('email')) {
                        return l10n.errorMsg.invalid.email;
                    }
                });
                return l10n.errorMsg.form.singular;
            }, 'p.save').addListeners({
                'formError': {
                    fn: LOP.addFormError
                },
                'formValid': {
                    fn: LOP.removeFormError
                },
                'fieldError': {
                    'fn': LOP.manageFieldError
                },
                'fieldValid': {
                    'fn': LOP.manageFieldError
                }
            });
            
            LOP.tooltips.add({
                selector: '#forgottenPasswordForm:hover',
                ruleNamespace: 'formError',
                rule: function(el) {
                    if (el.nodeName.toLowerCase() == 'img') {
                        this.setHTML(el.alt).setAttributeCache(el, 'alt').setId('toolTipError');
                    }
                }
            });
            
            var hasFormError = $('#forgottenPasswordFormError').html();
            if (hasFormError) {
                $('#forgottenPasswordFormError').css('display', 'block');
            }
        }
        
        if (document.getElementById('logout')) {
            parent.window.LOP.user = null;
            parent.document.getElementById('MenExpert').setUser(null);
            parent.window.$('#logged').remove();
            parent.window.closeIFramePopin();
        }
        
        
        LOP.popinOpeningActions.menExpert2010BVform = function() {
            /* BVcommentForm popin opening actions */
            $('#agreedtotermsandconditionsField a').click(function(e) {
                e.preventDefault();
                window.open(this.href, null, 'left=50,top=50,width=500,height=500,toolbar=0,location=0,resizable=1,scrollbars=1');
            });
            
            $('#productName').append(LOP.BVcomment.title);
            
            /* for testing purposes : adds test objects */
            /*
            LOP.BVcomment.param.rating_Texture = {
                type: 'IntegerInput',
                minimum: 1,
                maximum: 5,
                label: 'Texture'
            }
            LOP.BVcomment.param.rating_QualityPrice = {
                type: 'IntegerInput',
                minimum: 1,
                maximum: 5,
                label: 'Rapport Qualité Prix'
            }
            */
            /* creates fields */
            /* dynamic fields must contain 'rating_' */
           
            var fieldset = $('#BVcommentForm fieldset');
            for (var i in LOP.BVcomment.param) {
                if (i.indexOf('rating_') > -1) {
                    var myParam = LOP.BVcomment.param[i];
                    switch (myParam.type) {
                        case "TextInput":
                            fieldset.append('<div id="' + i + 'Field" class="text">' + 
                                            '    <label for="' + i + '">' + myParam.label + '<em class="required">*</em></label>' +
                                            '    <input type="text" name="' + i + '" id="' + i + '" />' +
                                            '</div>');
                            if (myParam.minLength) {
                                $('#' + i + 'Field').append('<p>' + l10n.BVcomment.text.min + ' ' + myParam.maxLength + ' ' + l10n.BVcomment.text.letters + '</p>');
                            }
                            if (myParam.maxLength) {
                                $('#' + i + 'Field').append('<p>' + l10n.BVcomment.text.max + ' ' + myParam.maxLength + ' ' + l10n.BVcomment.text.letters + '</p>');
                            }
                            break;
                        case "TextAreaInput":
                            fieldset.append('<div id="' + i + 'Field" class="text">' +
                                            '    <label for="' + i + '">' + myParam.label + '<em class="required">*</em></label>' +
                                            '    <textarea id="' + i + '" name="' + i + '" cols="20" rows="5"></textarea>' + 
                                            '</div>');
                            if (myParam.minLength) {
                                $('#' + i + 'Field').append('<p>' + l10n.BVcomment.text.min + ' ' + myParam.maxLength + ' ' + l10n.BVcomment.text.letters + '</p>');
                            }
                            if (myParam.minLength) {
                                $('#' + i + 'Field').append('<p>' + l10n.BVcomment.text.min + ' ' + myParam.maxLength + ' ' + l10n.BVcomment.text.letters + '</p>');
                            }
                            break;
                        case "IntegerInput":
                            fieldset.append('<div id="' + i + 'Field" class="radioGroup">' +
                                            '    <span class="legend">' + myParam.label + '<em class="required">*</em></span>' +
                                            '    <ul></ul>' +
                                            '</div>');
                            for (var k = myParam.minimum; k <= myParam.maximum; k++) {
                                $('#' + i + 'Field ul').append('<li class="radio' + k + '">' +
                                                               '    <label for="' + i + k + '">1</label>' +
                                                               '    <input value="' + k + '" type="radio" name="' + i + '" id="' + i + k + '" />' +
                                                               '</li>');
                            }
                            break;
                        case "BooleanInput":
                            fieldset.append('<div id="' + i + 'Field" class="checkBox">' +
                                            '    <input type="checkbox" name="' + i + '" id="' + i + '" />' +
                                            '    <label for="' + i + '">' + myParam.label + '<em class="required">*</em></label>' +
                                            '</div>');
                            break;
                    }
                }
            }
            
            /* form validation */
            BOX.form('BVcommentForm').addValidation(function(form) {
                /* dynamic fields */
                for (var i in LOP.BVcomment.param) {
                    if (i.indexOf('rating_') > -1) {
                        var myParam = LOP.BVcomment.param[i];
                        switch (myParam.type) {
                            case "TextInput":
                                form.text(i).mustValidate(function(field) {
                                    if (field.isEmpty()) {
                                        return l10n.BVcomment.required.generic;
                                    }
                                    if (myParam.minLength) {
                                        if (field.element.value.length < myParam.minLength) {
                                            return l10n.BVcomment.error.shortText;
                                        }
                                    }
                                    if (myParam.maxLength) {
                                        if (field.element.value.length > myParam.maxLength) {
                                            return l10n.BVcomment.error.longText;
                                        }
                                    }
                                });
                                break;
                            case "TextAreaInput":
                                form.text(i).mustValidate(function(field) {
                                    if (field.isEmpty()) {
                                        return l10n.BVcomment.required.generic;
                                    }
                                    if (myParam.minLength) {
                                        if (field.element.value.length < myParam.minLength) {
                                            return l10n.BVcomment.error.shortText;
                                        }
                                    }
                                    if (myParam.maxLength) {
                                        if (field.element.value.length > myParam.maxLength) {
                                            return l10n.BVcomment.error.longText;
                                        }
                                    }
                                });
                                break;
                            case "IntegerInput":
                                form.radio(i).mustValidate(function(field) {
                                    if (!field.isChecked()) {
                                        return l10n.BVcomment.required.generic;
                                    }
                                });
                                break;
                            case "BooleanInput":
                                form.checkbox(i).mustValidate(function(field) {
                                    if (!field.isChecked()) {
                                        return l10n.BVcomment.required.generic;
                                    }
                                });
                                break;
                        }
                    }
                }
                
                /* common fields */
                form.radio('rating').mustValidate(function(field) {
                    if (!field.isChecked()) {
                        return l10n.BVcomment.required.rating;
                    }
                });
                
                form.text('reviewtext').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.BVcomment.required.reviewtext;
                    } else if (field.element.value.length < 50) {
                        return l10n.BVcomment.errors.shortOpinion;
                    }
                });
                
                form.text('Usernickname').mustValidate(function(field) {
                    if (field.isEmpty()) {
                        return l10n.BVcomment.required.Usernickname;
                    } else if (field.element.value.length > 25) {
                        return l10n.BVcomment.errors.longNickName;
                    }
                });
                
                form.checkbox('agreedtotermsandconditions').mustValidate(function(field) {
                    if (!field.isChecked()) {
                        return l10n.BVcomment.required.agreedtotermsandconditions;
                    }
                });
                
                return l10n.errorMsg.form.plural;
                
            }, 'p.save').addListeners({
                'formError': {
                    'fn': LOP.addFormError
                },
                'formValid': {
                    'fn': function(e, formEvent) {
                        formEvent.preventDefault();
                        /* sends form's datas to flash function BVSendData() */
                        BVSendData(LOP.getBVcomments());
                    }
                },
                'fieldError': {
                    'fn': LOP.manageFieldError
                },
                'fieldValid': {
                    'fn': LOP.manageFieldError
                }
            }).addReplacement();
            
            $('#BVcommentForm .radioGroup label').mouseover(function() {
                $(this).addClass('hover');
                var myValue = $(this).next('input').attr('value');
                $(this).parent().parent().find('label').each(function(index) {
                    if ((index + 1) <= myValue) {
                        $(this).addClass('hover');
                    }
                    if ((index + 1) > myValue) {
                        $(this).removeClass('hover');
                    }
                });
            });
            
            $('#BVcommentForm .radioGroup ul').mouseover(function() {
                $(this).removeClass();
            });
            
            $('#BVcommentForm .radioGroup ul').mouseout(function() {
                $(this).find('label').each(function() {
                    $(this).removeClass('hover');
                });
                var chk = $(this).find('input:checked').val();
                if (chk) {
                    $(this).addClass('checked' + chk);
                }
            });
            
            LOP.tooltips.add({
                selector: '#BVcommentForm:hover',
                ruleNamespace: 'formError',
                rule: function(el) {
                    if (el.nodeName.toLowerCase() == 'img') {
                        this.setHTML(el.alt).setAttributeCache(el, 'alt').setId('toolTipError');
                    }
                }
            });
            
            var hasFormError = $('#BVcommentFormError').html();
            if (hasFormError) {
                $('#BVcommentFormError').css('display', 'block');
            }
            
            this.position();
            var top = parseInt($('#popin .popinWrapper').css('top').split('px')[0], 10);
            if (top < 120) {
                $('#popin .popinWrapper').css('top', '120px');
            }
        };
        
        LOP.getBVcomments = function() {
            LOP.BVcomment.results = {};
            for (var i in LOP.BVcomment.param) {
                LOP.BVcomment.results[i] = {};
                var myParam = LOP.BVcomment.param[i];
                switch (myParam.type) {
                    case "TextInput":
                        LOP.BVcomment.results[i].value = $('#popin input[name=' + i + ']').val();
                        break;
                    case "TextAreaInput":
                        LOP.BVcomment.results[i].value = $('textarea[name=' + i + ']').val();
                        break;
                    case "IntegerInput":
                        LOP.BVcomment.results[i].value = $('input[name=' + i + ']:checked').val();
                        break;
                    case "BooleanInput":
                        LOP.BVcomment.results[i].value = $('input[name=' + i + ']').val();
                        if (LOP.BVcomment.results[i].value == 'on') {
                            LOP.BVcomment.results[i].value = true;
                        } else {
                            LOP.BVcomment.results[i].value = false;
                        }
                        break;
                }
            }
            return LOP.BVcomment.results;
        };
        
        LOP.popinClosingActions.menExpert2010BVform = function() {
            /* destroy BOX.form BVcommentForm */
            BOX.form('BVcommentForm', true);
        };
        
        LOP.popinOpeningActions.menExpert2010BVformConfirm = function() {
            this.position();
            var top = parseInt($('#popin .popinWrapper').css('top').split('px')[0], 10);
            if (top < 120) {
                $('#popin .popinWrapper').css('top', '120px');
            }
        };
        
        LOP.popinOpeningActions.menExpert2010BVformFailure = function() {
            if (LOP.BVcomment.failure) {
                $('#BVcommentFailure').append('<p>' + LOP.BVcomment.failure + '</p>');
            }
            this.position();
            var top = parseInt($('#popin .popinWrapper').css('top').split('px')[0], 10);
            if (top < 120) {
                $('#popin .popinWrapper').css('top', '120px');
            }
        };
        
        LOP.callCommentPopin = function(title, param) {
            LOP.BVcomment = {};
            LOP.BVcomment.title = title;
            LOP.BVcomment.param = param;
            LOP.popins.add({
                url: l10n.url.menExpert2010BVform,
                id: 'menExpert2010BVform',
                processHTML: LOP.processHTMLPopins
            });
        };
        
        LOP.callLoginPopin = function(isAskForm) {
            if (isAskForm) {
                /* open comment popin */
                LOP.openIFramePopin({
                    'url': l10n.url.menExpert2010comment,
                    'width': 407,
                    'height': 320
                });
            } else {
                /* open login popin */
                LOP.openIFramePopin({
                    'url': l10n.url.menExpert2010logIn,
                    'width': 407,
                    'height': 320
                });
            }
        };
        
		LOP.callRegisterPopin = function() {
			LOP.openIFramePopin({
				'url': l10n.url.menExpert2010register,
				'width': 407,
				'height': 800
			});
        };
		
        LOP.submissionSuccess = function() {
            LOP.popins.add({
                url: l10n.url.menExpert2010BVformConfirm,
                id: 'menExpert2010BVformConfirm',
                processHTML: LOP.processHTMLPopins
            });
        };
        
        LOP.submissionFailure = function(param) {
            var str = "";
            for (var t in param) {
                str += t + "\n | error=" + param[t].error + "\n";
                
            }
            LOP.BVcomment.failure = str;
            LOP.popins.add({
                url: l10n.url.menExpert2010BVformFailure,
                id: 'menExpert2010BVformConfirm',
                processHTML: LOP.processHTMLPopins
            });
        };

        LOP.callLogout = function() {
            LOP.openIFramePopin({
                'url': l10n.url.menExpert2010logOut,
                'width': 407,
                'height': 320
            });
        };
    });
})(jQuery);

