$(function() {

//    // proper target _blank
//    jQuery('a[rel*=external]').click(function() {
//        this.target = '_blank';
//    });

    // init facebox

    $.facebox.settings.loading_image = '/skin/default/p/facebox/loading.gif';
    $.facebox.settings.close_image = '/skin/default/p/facebox/closelabel-small.gif';
    $.facebox.settings.faceboxHtml = '\
<div id="facebox" style="display:none;"> \
    <div class="popup"> \
        <table> \
            <tbody> \
                <tr> \
                    <td class="tl"/><td class="b"/><td class="tr"/> \
                </tr> \
                <tr> \
                    <td class="b"/> \
                    <td class="body"> \
                        <div class="content"> \
                        </div> \
                        <div class="footer"> \
                            <a href="#" class="close"> \
                                <img src="' + $.facebox.settings.close_image + '" title="close" class="close_image" alt="" /> \
                            </a> \
                        </div> \
                    </td> \
                    <td class="b"/> \
                </tr> \
                <tr> \
                    <td class="bl"/><td class="b"/><td class="br"/> \
                </tr> \
            </tbody> \
        </table> \
    </div> \
</div>';
    
    var submited_form = '';

    raise_popup = function(level, msg) {

        popup = '\
    <div id="popup-content"> \
        <img src="/skin/default/p/facebox/icon-' + level + '.gif" width="49" height="49" alt="" /> \
        <p>' + msg + '</p> \
    </div>';

        jQuery.facebox(popup);
        /*if(document.getElementById('mode').value == 'light02CHE')
        {
            document.getElementById('facebox').style.position='relative';
            document.getElementById('facebox').style.left='40%';
            document.getElementById('facebox').style.width='410px';                
        }*/
    };

    raise_popup_form_error = function(e, validator) {

        custom_message = message_form_error + '<ul>';
        for (var k in validator.errorMap) {
            custom_message+= '<li>' + validator.errorMap[k] + '<\/li>';
        }
        custom_message+= '<ul>';

        raise_popup('error', custom_message);
    };

    process_submit = function(form) {
        if (is_processing == true) {
            return false;
        }
        is_processing = true;

        // build the final parameters list

        // loop to remove some unused fields
        var params_current = $(form).serializeArray();
        var params_new = new Array();
        var j = 0;
        jQuery.each(params_current , function(i, field) {
            if (field.name != 'birth_date_day' && field.name != 'birth_date_month' && field.name != 'birth_date_year' && field.name != 'redirect_url') {
                params_new[j] = params_current[i];
                j++;
            }
        });

        // add well formated birth_date
        params_new[j] = {name: 'birth_date', value: $('#birth_date_year').val() + '-' + $('#birth_date_month').val() + '-' + $('#birth_date_day').val()};

        submited_form = $(form).attr("id").toString().substring(0, $(form).attr("id").toString().length - 5);
        
        $.ajax({
            url: api_gateway_url,
            type: 'POST',
            data: $.param(params_new),
            dataType: 'json',
            success: process_success,
            error: process_error
        });

        return false;
    };

    process_show_error = function(errorMap, errorList) {
        // disable normal default error display
    };

    get_redirection_url = function(id_affiliate, msginfo) {
        var parameters = {
            i: redirect_id_aff,
            cc: redirect_id_cc,
            redirect_HP: id_country_area + "-" + $("[name=zipcode]").val()
        }

        var url_redirection = "";
	if(lf_redirect == "")
	{
            lf_redirect = portal_url + 'aff.php?' + $.param(parameters);
	}
		

        if (id_affiliate != 0 && id_affiliate != undefined)
            parameters["id_affiliate_tag"] = id_affiliate;
        if (msginfo != '' && msginfo != undefined)
            parameters["msginfo"] = msginfo;

        // Get random url
        if(typeof check_participant != 'undefined' && check_participant) {
            var random_number = Math.floor(2 * Math.random());
            // LF
            if(random_number == 0) {
                url_redirection = lf_redirect;
                popunder_url = partner_url_site_under;
            }
            else { // LF
                url_redirection = partner_url_direct;
                popunder_url = lf_redirect;
            }
            
        } else {
            url_redirection = lf_redirect;
        }

        return url_redirection;
    }

    get_login_url = function(id_lf_customer, hash, redirection) {
        return portal_url + 'w/account/identification_submit.php?' + $.param({
            key_c: id_lf_customer + '-' + hash,
            url: redirection
        });
    }

    function array_search(value, table) {
        for(var i = 0; i < table.length; i++)
            if (value == table[i])
                return i;
        return undefined;
    }

    process_success = function(response) {
        if (response instanceof Object
            && 'result' in response
            && response['result'] == "1"
            && 'result_detail' in response
            && response['result_detail'] == "OK") {

            var form_index = array_search(submited_form, forms_list);
                        
            // If it was the last step
            if (form_index == forms_list.length - 1) {
                // user has been registered
                
                // handle no special offers on given zipcode
                if (typeof response['data']['special_offers_nb'] != 'undefined' && response['data']['special_offers_nb'] == "0") {
                    var redirect_location = get_login_url(response['data']['id_lf_customer'], response['data']['cx_hash'], get_redirection_url($('#id_affiliate').val(), message_no_special_offer));
                } else {
                    var redirect_location = get_login_url(response['data']['id_lf_customer'], response['data']['cx_hash'], get_redirection_url($('#id_affiliate').val(), ''));
                }

                if(typeof check_participant != 'undefined' && check_participant) {
                    // Put pixel for partner for all informations
                    if(typeof full_api_partner_url != 'undefined') {
                        var email_value = $('#' + submited_form + '_form [name=email]').val();
                        var zipcode_value = $('#' + submited_form + '_form [name=zipcode]').val();
                        var civility_value = $('#' + submited_form + '_form [name=civility]').val().toLowerCase();
                        var first_name_value = $('#first_name').val();
                        var last_name_value = $('#last_name').val();
                        var birth_date_value = $('#birth_date_day').val() + '-' + $('#birth_date_month').val() + '-' + $('#birth_date_year').val();
                        var password_value = $('#password').val();
                        if(civility_value == "mr") civility_value = "m";
                        else if(civility_value == "miss") civility_value = "mlle";

                        full_api_partner_url = full_api_partner_url.replace("##email##", email_value);
                        full_api_partner_url = full_api_partner_url.replace("##zipcode##", zipcode_value);
                        full_api_partner_url = full_api_partner_url.replace("##civility##", civility_value);
                        full_api_partner_url = full_api_partner_url.replace("##first_name##", first_name_value);
                        full_api_partner_url = full_api_partner_url.replace("##last_name##", last_name_value);
                        full_api_partner_url = full_api_partner_url.replace("##birth_date##", birth_date_value);
                        full_api_partner_url = full_api_partner_url.replace("##password##", password_value);
                        jQuery.ajax({
                            url: full_api_partner_url,
                            async: false,
                            dataType: 'html'
                        });
                    }
                }
                if(document.getElementById("account03_form"))
                {
                    document.getElementById("account03_form").style.display='none';
                    document.getElementById("splash_page").style.display='block';
                }
                else
                {
                    if (typeof _gaq != 'undefined' && typeof _gaq.push == 'function') {
                        // google analytics loaded
                        _gaq.push(['_trackPageview', '/subscribe.html']);
                        // delay the redirection
                        _gaq.push(function(){
                            setTimeout('window.location = "' + redirect_location + '";', 200);
                        });
                    } else {
                        // google analytics not loaded, redirect
                        window.location = redirect_location;
                    }
                }
            } else {
                var email_value = $('#' + submited_form + '_form [name=email]').val();
                $('#' + forms_list[form_index + 1] + '_form').append("<input type='hidden' name='email' value='" + email_value + "'/>");

                var zipcode_value = $('#' + submited_form + '_form [name=zipcode]').val();
                $('#' + forms_list[form_index + 1] + '_form').append("<input type='hidden' name='zipcode' value='" + zipcode_value + "'/>");

                $('#' + forms_list[form_index + 1] + '_form').show();
                $('#' + submited_form + '_form').hide();

                // Put pixel for partner
                if(typeof check_participant != 'undefined' && check_participant) {
                    if(typeof light_api_partner_url != 'undefined') {
                        light_api_partner_url = light_api_partner_url.replace("##email##", email_value);
                        light_api_partner_url = light_api_partner_url.replace("##zipcode##", zipcode_value);
                        jQuery("#partner_tag").html("<img src='" +light_api_partner_url + "' border='0' width='1' height='1' />");
                    }
                    if(typeof t_list_pixel_partner != 'undefined' && t_list_pixel_partner.length > 0 && ! response['data']['already_bc_participant'] && typeof $('#id_affiliate').val() != 'undefined') {
                        var pixel_url = t_list_pixel_partner[$('#id_affiliate').val()];
                        pixel_url = pixel_url.replace("##email##", email_value);
                        pixel_url = pixel_url.replace("##email_md5##", response['data']['email_md5']);
                        jQuery("#affiliate_tag").html(pixel_url);
                    }
                }

                is_processing = false;
            }

        } else {
            is_processing = false;
            raise_popup('error', form_message['unknown_error']);
        }
    };

    process_error = function(xhr, ajaxOptions, thrownError) {
        is_processing = false;

        var tmp_detail = eval('(' + xhr.responseText + ')');
        if (tmp_detail instanceof Object
            && 'result_code' in tmp_detail
            && 'result_detail' in tmp_detail
        ) {
            // managed error
            if (tmp_detail['result_code'] == 'BAD_PARAMETER'
                && tmp_detail['result_detail'].toLowerCase() in form_message) {
                // input test failed
                var tmp_e;
                if (form_message[tmp_detail['result_detail'].toLowerCase()] instanceof Object) {
                    // multiple message for one field
                    if (tmp_detail['result_detail'].toLowerCase() == 'email') {
                        // mostly strength email syntax check
                        var tmp_validator = {errorMap: {0: form_message[tmp_detail['result_detail'].toLowerCase()]['email']}};
                    } else {
                        // other
                        var tmp_validator = {errorMap: {0: form_message[tmp_detail['result_detail'].toLowerCase()]['required']}};
                    }
                } else {
                    // one message for one field
                    var tmp_validator = {errorMap: {0: form_message[tmp_detail['result_detail'].toLowerCase()]}};
                }

                // display error
                raise_popup_form_error(tmp_e, tmp_validator);

            } else if (tmp_detail['result_code'] == 'ACCOUNT_EXIST') {
                // this account already exists

                if (typeof _gaq != 'undefined' && typeof _gaq.push == 'function') {
                    _gaq.push(['_trackPageview', '/already.html']);
                }
                // display a popup to continue non-authenticated
                var popup_redirect = '<br \/><br \/><span style="display: block; width: 100%; text-align: center;"><a';
                popup_redirect += '';
                if(document.getElementById('mode').value == 'light02CHE')
                {
                    popup_redirect+= ' href="#" onclick="gotoStep3();"';
                }
                else
                {
                    if(typeof check_participant != 'undefined' && check_participant) {
                        popup_redirect+= ' href="#" onclick="open_site_under(1);"';
                    } else {
                        popup_redirect+= ' href="' + get_redirection_url(0) + '"';
                    }
                }
                popup_redirect+= ' id="continue_link"><\/a><\/span>';

                if(typeof tmp_detail.data != 'undefined' && tmp_detail["data"]["email"] != '' && ! tmp_detail['data']['already_bc_participant']) {
                    // -- Send user informations to partner if he already is in our DB
                    var tmp_birth_date = tmp_detail["data"]["birth_date"].split("-");
                    var birth_date = tmp_birth_date[2] + "-" + tmp_birth_date[1] + "-" + tmp_birth_date[0];
                    var civility_value = tmp_detail["data"]["civility"].toLowerCase();
                    if(civility_value == "mr") civility_value = "m";
                    else if(civility_value == "miss") civility_value = "mlle";
                    full_api_partner_url_account = full_api_partner_url_account.replace("##email##", tmp_detail["data"]["email"]);
                    full_api_partner_url_account = full_api_partner_url_account.replace("##zipcode##", tmp_detail["data"]["zipcode"]);
                    full_api_partner_url_account = full_api_partner_url_account.replace("##civility##", civility_value);
                    full_api_partner_url_account = full_api_partner_url_account.replace("##first_name##", tmp_detail["data"]["first_name"]);
                    full_api_partner_url_account = full_api_partner_url_account.replace("##last_name##", tmp_detail["data"]["last_name"]);
                    full_api_partner_url_account = full_api_partner_url_account.replace("##birth_date##", birth_date);
                    full_api_partner_url_account = full_api_partner_url_account.replace("##password##", tmp_detail["data"]["password"]);
                    jQuery.ajax({
                        url: full_api_partner_url_account,
                        async: false,
                        dataType: 'html'
                    });
                    if(typeof t_list_pixel_partner != 'undefined' && t_list_pixel_partner.length > 0 && ! tmp_detail['data']['already_bc_participant'] && typeof $('#id_affiliate').val() != 'undefined') {
                        var pixel_url = t_list_pixel_partner[$('#id_affiliate').val()];
                        pixel_url = pixel_url.replace("##email##", tmp_detail["data"]["email"]);
                        pixel_url = pixel_url.replace("##email_md5##", tmp_detail["data"]["email_md5"]);
                        jQuery("#affiliate_tag").html(pixel_url);
                    }
                }
                // -- end sending
                raise_popup('info', message_account_exists + popup_redirect);
            } else {
                raise_popup('error', form_message['unknown_error']);
            }
        } else {
            raise_popup('error', form_message['unknown_error']);
        }
    };

    open_site_under = function(redirect) {
        var p = 'scrollbars=yes,resizable=yes,toolbar=yes,menubar=yes,status=yes,location=yes,height=900,width=900';
        if(redirect == 1) {
            var url_redirect = get_redirection_url(0);
            win2=window.open(popunder_url,"bw",p);
            win2.blur();
            window.focus();
            window.location = url_redirect;

        } else {
            win2=window.open(popunder_url,"bw",p);
            win2.blur();
            window.focus();
        }
    }

    validator_configuration = {
        debug: true,
        messages: form_message,
        showErrors: process_show_error,
        submitHandler: process_submit
    };
    
    check_id_bc = function(expected_id_bc) {
        var uriCourant = document.location.pathname; 
        var id_bc= uriCourant.substring(1, uriCourant.indexOf('/',1));
        if(id_bc == expected_id_bc)
        {
            return true;
        }
        else
        {
            return false;                
        }
    };    
    
    gotoStep3 = function() {
        document.getElementById('facebox').style.display='none';
        document.getElementById('light02CHE_form').style.display='none';
        document.getElementById('splash_page').style.display='block';
    };
    
});

