﻿(function()
{
 
    var menuInitialized = false,
        translations = {
            login: "Veuillez vous connectez pour accéder à ce service.",
            minLvl: "Vous devez posséder un personage supérieur au niveau 10 / Renommée 1000(Castle of Heroes)",
            emptyField: "Le champ doit être renseigné.",
            invalidEmail: "L'adresse e-mail saisie est invalide.",
            noSupport: "Ce fournisseur de service n'est pas supporté actuellement.",
            limitReached: "Vous avez déjà envoyé 50 invitations ce mois-ci. Veuillez attendre le mois prochain ou utilisez les liens de parrainage.",
            noEmails: "Le champ des destinataires doit être renseigné.",
            bannersHeader: "Utilisez le code ci-dessous pour intégrer les bannières sur les sites webs, forums, blogs, où vous voulez !"
        };

    GPotato.Referral = {
        initializer: null,
        InitInvite: function()
        {
            this.initializer = initInvite;
        },
        InitBanners: function()
        {
            this.initializer = initBanners;
        },
        InitIndex: function()
        {
            this.initializer = initIndex;
        },
        InitTracker: function(settings)
        {
            this.initializer = initTracker;
        }
    };

    function initMenu()
    {
        menuInitialized = true;

        $(".-selectable").live("click", function()
        {
            $(this).select();
        });

        var isLoggedIn = $("#isUserLoggedIn").val() == "True",
            isPermitted = $("#isUserPermitted").val() == "True";
        $("#referral_menu a").each(function(i)
        {
            $(this).click(function()
            {
                $(this).blur();
                if (i != 0 && isLoggedIn === false)
                {
                    alert(translations.login);
                }
                else
                    if (i != 0 && isPermitted === false)
                {
                    alert(translations.minLvl);
                    return false;
                }
            });
        });

    }

    function GetCaptchaID()
    {
        return parseInt(Math.random() * 1000000);
    }

    function initCaptcha()
    {
        $("#img_capcha").css("opacity", 0);
        var captchaImage = new Image(),
            src = "?ajax=true&action=getCaptcha&ver=" + GetCaptchaID();
        captchaImage.src = src;
        captchaImage.onload = function()
        {
            $("#img_capcha").attr("src", src).fadeTo("fast", 1);
        };
        $("#txt_captcha").val("");
    }

    function initInvite()
    {
        function init()
        {
            $("#email_body").val("");
            $("#emails_container").html("");
        }

        function initImport()
        {
            //TODO: uncomment this
            //$("#email_addr").val("");
            //$("#email_pass").val("");
            $("#importer ul").html("");
        }

        init();

        var emailManager = {
            refresh: function()
            {
                $("#lbl_invites_no").text(this.getMaxNumber());
            },
            checkEmail: function(email)
            {
                var emails = getEmails();
                if (emails.indexOf(email) == -1 && this.getMaxNumber(emails) > 0)
                {
                    return true;
                }
                return false;
            },
            getMaxNumber: function(emails)
            {
                var emailManager = this;
                emailManager.emails = emails || getEmails(),
                    emailsNo = emailManager.max - emailManager.emails.length;

                if (emailsNo < 0)
                {
                    emailsNo = 0;
                }
                return emailsNo;
            },
            init: function()
            {
                this.max = parseInt($("#lbl_invites_no").text(), 10);
                return this;
            }
}.init();

            var windowManager = {
                main: "#main_win",
                initLogin: function(msg)
                {
                    var message = $("#ImportMessage").val();
                    if (message != "")
                    {
                        alert(message);
                        return;
                    }

                    emailManager.refresh();
                    if (emailManager.getMaxNumber() > 0)
                    {
                        msg = msg || "";
                        $("#error_msg").text(msg);
                        this.initWin("#import_win");
                        $("#email_addr").focus();

                        var captchaStatus = $("#CaptchaStatus").val().toLowerCase() === "true";
                        if (captchaStatus === true)
                        {
                            initCaptcha();
                            if ($("#email_addr").val() != "")
                            {
                                $("#txt_captcha").focus();
                            }
                            $("#capcha_container").show();
                        }
                        else
                        {
                            $("#capcha_container").hide();
                        }
                    }
                },
                initImport: function()
                {
                    initImport();
                    this.initWin("#import_contacts");

                },
                initImportNotification: function()
                {
                    this.initWin("#import_notification_win");
                },
                initMain: function()
                {
                    emailManager.refresh();
                    this.initWin(this.main);
                },
                initWin: function(win)
                {
                    this.disable();
                    this.current = win;
                    this.enable();
                },
                showLoading: function()
                {
                    this.disable();
                    var loading = $("<div id=\"loading_indicator\" />").appendTo("#invite_window");
                },
                removeLoading: function()
                {
                    $("#loading_indicator").remove();
                },
                disable: function()
                {
                    this.removeLoading();
                    if (this.current != this.main)
                    {
                        $(this.current).hide();
                    }
                    else
                    {
                        $(this.current).css("opacity", "0");
                    }
                },
                enable: function()
                {
                    if (this.current != this.main)
                    {
                        $(this.current).fadeIn("fast");
                    }
                    else
                    {
                        $(this.current).fadeTo("fast", 1);
                    }
                },
                init: function()
                {
                    this.current = this.main;
                    return this;
                }
}.init();
                $("#btn_refresh_captcha").click(function()
                {
                    initCaptcha();
                    $("#txt_captcha").focus();
                    return false;
                });

                $("#btn_import_contacts, #lnk_import_contacts").click(function()
                {
                    windowManager.initLogin();
                });

                $("#btn_cancel, #btn_cancel_import").click(function()
                {
                    windowManager.initMain();
                });

                $("#btn_add").click(function()
                {
                    if ($(this).attr("disabled") == "disabled")
                    {
                        return false;
                    }
                    var list = getEmails(),
                        importedContacts = importManager.getImportedContacts();
                    for (var i = 0; i < importedContacts.length; i++)
                    {
                        if (list.indexOf(importedContacts[i]) == -1)
                        {
                            AddEmail(importedContacts[i]);
                            list.push(importedContacts[i]);
                        }
                    }

                    windowManager.initMain();
                });

                $("#btn_copy_contacts").click(function()
                {
                    $("#contacts li input[type=checkbox]:checked").each(function()
                    {
                        $(this).removeAttr("checked");
                        //if ($(this).attr("checked") === true)
                        // {
                        importManager.addItem($(this).parent());
                        // }
                    });
                });

                $("#emails_container").click(function()
                {
                    AddEditorField();
                    emailManager.refresh();
                }).
                blur(function()
                {
                    emailManager.refresh();
                });

                function AddEditorField()
                {
                    if (emailManager.getMaxNumber() > 0)
                    {
                        RemoveEditorField();
                        $("<input id=\"email_edit\" type=\"text\" />").
                    click(function(e)
                    {
                        e.stopPropagation();
                    }).
                    appendTo("#emails_container").
                        blur(function()
                        {
                            RemoveEditorField();
                        }).
                        keypress(function(e)
                        {
                            var keys = [59, 32, 44],
                                specialKeys = [13, 9];
                            if (keys.indexOf(e.charCode) > -1 || specialKeys.indexOf(e.keyCode) > -1)
                            {
                                if (IsEmailEnteredValid() === true)
                                {
                                    RemoveEditorField();
                                    AddEditorField();
                                    emailManager.refresh();
                                    $("#email_edit").focus();
                                }
                                return false;
                            }
                        }).
                        focus();
                        $("#emails_container #email_edit").scroll(0, 500);
                    };
                }

                function RemoveEditorField()
                {
                    var editor = $("#emails_container #email_edit");
                    if (editor.length > 0)
                    {
                        if (IsEmailEnteredValid() === true)
                        {
                            var emails = GetEmailsEnteredValue();
                            for (var i = 0; i < emails.length; i++)
                            {
                                AddEmail(emails[i]);
                            }
                            emailManager.refresh();
                        }
                        editor.remove();
                    }
                }

                function AddEmail(email)
                {
                    var value = email;
                    if (value != "" && emailManager.checkEmail(value) > 0 && isEmailCorrect(email))
                    {
                        $("<div class=\"email_div\" title=\"" + value + "\">" + TrimEmail(value) + "<div class=\"email_div_close\">X</div></div>").
                                    appendTo("#emails_container").
                                    click(function(e)
                                    {
                                        e.stopPropagation();
                                    }).find(".email_div_close").click(function(e)
                                    {
                                        $(this).parent().fadeOut("fast", function()
                                        {
                                            $(this).remove();
                                            emailManager.refresh();
                                        });
                                        e.stopPropagation();
                                    });
                    }
                }

                function TrimEmail(email)
                {
                    if (email.length < 10)
                    {
                        return email;
                    }
                    else
                    {
                        return email.substring(0, 8) + "...";
                    }
                }

                function IsEmailEnteredValid()
                {
                    var editor = $("#emails_container #email_edit");
                    if (editor.length > 0)
                    {
                        var emails = GetEmailsEnteredValue();
                        return (emails.length == 1) ? isEmailCorrect(emails[0]) : true;
                    }
                    return false;
                }

                function GetEmailsEnteredValue()
                {
                    return $("#emails_container #email_edit").val().replace(/([; ,]|\s)+/g, ";").split(";");
                }

                $("#email_body").keyup(updateEmailBody).
                         keypress(updateEmailBody).
                         change(updateEmailBody);

                function updateEmailBody()
                {
                    var emailBody = $(this),
                        maxLength = 300;
                    bodyLength = maxLength - emailBody.val().length;
                    if (bodyLength < 0)
                    {
                        emailBody.val(emailBody.val().substring(0, maxLength));
                        bodyLength = 0;
                        emailBody.scroll(0, 1000);
                    }
                    $("#lbl_email_body").text(bodyLength);
                }

                $("#btn_select_all").click(function()
                {
                    changeSelection(true);
                });

                $("#btn_deselect_all").click(function()
                {
                    changeSelection(false);
                });

                function changeSelection(status)
                {
                    $("#contacts li input[type=checkbox]").each(function()
                    {
                        $(this).
                        attr("checked", status).
                            parent().
                            css("background", (status === true ? "#eee" : ""));
                    });
                }

                var importManager = {
                    _list: null,
                    importedItems: 0,
                    displayContacts: function()
                    {
                        var contacts = "",
                            results = this._list;

                        for (var i = 0; i < results.length; i++)
                        {
                            var contact = results[i];
                            if (this.emailsEntered.indexOf(contact.email) != -1)
                            {
                                continue;
                            }
                            var item = "<li class=\"" + contact.email + "\" ><input type=\"checkbox\" /><span>";
                            if (contact.name != "")
                            {
                                item += "<b>" + contact.name + "</b><br />" + contact.email;
                            }
                            else
                            {
                                item += "<b>" + contact.email + "</b>";
                            }
                            contacts += item + "</span></li>";
                        }
                        $("#contacts ul").html(contacts).
                            find("li input[type=checkbox]").click(function()
                            {
                                var backgroundColor = $(this).attr("checked") === true ? "#eee" : "";
                                $(this).parent().css("background", backgroundColor);
                            });
                    },
                    removeItem: function(item)
                    {
                        var contactImporter = this;
                        contactImporter.importedItems--;
                        item.css("opacity", "1").slideDown("fast",
                        function()
                        {
                            $(this).removeAttr("style"); //.css("background", "");
                        });
                        contactImporter.refresh();
                    },
                    getMaxContacts: function()
                    {
                        return (emailManager.max - this.emailsEntered.length - this.importedItems);
                    },
                    addItem: function(item)
                    {
                        var contactImporter = this,
                            email = item.attr("class");

                        if (contactImporter.getMaxContacts() > 0)
                        {
                            contactImporter.importedItems++;

                            item.
                            fadeTo("fast", 0,
                            function()
                            {
                                $(this).slideUp("fast");
                            });

                            $("<li><img src=\"http://simg.gpotato.eu/www/fr/referral/invite_list_remove_btn.jpg\" class=\"btn_remove_contact -button\" /><span>" + email + "</span></li>").
                            appendTo("#importer ul").
                                find(".btn_remove_contact").
                                click(
                                function()
                                {
                                    $(this).parent().remove();
                                    contactImporter.removeItem(item);
                                });
                        }
                        contactImporter.refresh();
                    },
                    refresh: function()
                    {
                        this.refreshMaxContacts();
                        if (this.importedItems === 0)
                        {
                            $("#btn_add").css("opacity", 0).attr("disabled", "disabled");
                        }
                        else
                        {
                            $("#btn_add").removeAttr("style").removeAttr("disabled");
                        }
                    },
                    getImportedContacts: function()
                    {
                        var contactList = [];
                        $("#importer li span").each(function()
                        {
                            contactList.push($(this).text());
                        });
                        return contactList;
                    },
                    refreshMaxContacts: function()
                    {
                        var maxContacts = this.getMaxContacts();
                        $("#max_contacts").text(maxContacts);
                        if (maxContacts > 0)
                        {
                            $("#btn_copy_contacts").show();
                        }
                        else
                        {
                            $("#btn_copy_contacts").hide();
                        }
                    },
                    init: function(list, emailsEntered)
                    {
                        this.emailsEntered = emailsEntered;
                        this._list = list;
                        this.displayContacts();
                        this.importedItems = 0;
                        this.refresh();
                    }
                };

                function CheckProvider()
                {
                    var emailAddr = $("#email_addr").val(),
                        mailMatch = emailAddr.match(/@(.*?)\./),
                        classProvider = "";
                    if (mailMatch != null && isEmailCorrect(emailAddr))
                    {
                        var provider = mailMatch[1].toLowerCase();
                        switch (provider)
                        {
                            case "live":
                            case "hotmail": classProvider = "hotmail"; break;
                            default: classProvider = provider;
                        }
                        classProvider = "ep_" + classProvider + "_s";
                    }
                    $("#provider_icon").html("<div class=\"" + classProvider + "\" />");
                }

                $("#email_pass, #email_addr, #txt_captcha").keypress(function(e)
                {
                    if (e.keyCode == 13)
                    {
                        ImportContacts();
                        return false;
                    }
                });

                $("#email_addr").keyup(function()
                {
                    CheckProvider();
                });

                $("#btn_next").click(ImportContacts);

                function ImportContacts()
                {
                    var emailBox = $("#email_addr"),
                        passBox = $("#email_pass"),
                        captchaBox = $("#txt_captcha"),
                        captchaEnabled = $("#CaptchaStatus").val().toLowerCase() === "true",
                        captcha = captchaBox.val(),
                        email = emailBox.val(),
                        pass = passBox.val(),
                        err = $("#error_msg");

                    if (email == "")
                    {
                        emailBox.focus();
                        err.text(translations.emptyField);
                        return;
                    }

                    if (isEmailCorrect(email) === false)
                    {
                        emailBox.focus();
                        err.text(translations.invalidEmail);
                        return;
                    }

                    if (isDomainCorrect(email) === false)
                    {
                        emailBox.focus();
                        err.text(translations.noSupport);
                        return;
                    }

                    if (pass == "")
                    {
                        passBox.focus();
                        err.text(translations.emptyField);
                        return;
                    }

                    if (captchaEnabled === true && captcha == "")
                    {
                        captchaBox.focus();
                        err.text(translations.emptyField);
                        return;
                    }

                    var emailsEntered = getEmails();

                    windowManager.showLoading();

                    $.ajax({
                        type: "POST",
                        url: "/account/referral/ContactsLoader.aspx",
                        data: { "email": email, "pass": pass, "captcha": captcha },
                        success: function(data)
                        {
                            var response = JSON.parse(data);
                            $("#CaptchaStatus").val(response.captchaEnabled)
                            if (response.errorCode == "0")
                            {
                                importManager.init(response.results, emailsEntered);
                                windowManager.initImport();
                            }
                            else
                            {

                                windowManager.initLogin(response.errorMessage);
                            }
                        },
                        error: function(e)
                        {
                            //console.log(e);
                        }
                    });
                }

                $("#inviter_link").live("click", function()
                {
                    init();
                    windowManager.initMain();
                    if (emailManager.max == 0)
                    {
                        ShowReachedEmailsLimitMessage();
                        window.location = window.location;
                    }
                    return false;
                });

                function ShowReachedEmailsLimitMessage()
                {
                    alert(translations.limitReached);
                }

                $("#btn_send_invite").click(function()
                {
                    var emails = getEmails();
                    if (emails.length === 0)
                    {
                        alert(translations.noEmails);
                        return;
                    }

                    if (emailManager.max == 0)
                    {
                        ShowReachedEmailsLimitMessage();
                        return;
                    }

                    windowManager.showLoading();
                    $.ajax({
                        type: "post",
                        url: "invite.aspx?ajax=true&action=send",
                        data: { "env": JSON.stringify({ "email_addr": emails, "message": $("#email_body").val() }) },
                        success: function(data)
                        {
                            var result = JSON.parse(data);
                            $("#import_notification_win").html(result.notification);
                            $("#imported_contacts_no").html(result.emailsSent);
                            emailManager.max = result.emailsLeft;
                            windowManager.initImportNotification();
                        },
                        error: function()
                        {
                        }
                    });
                });
            }

            function getEmails()
            {
                var emails = $("#emails_container .email_div"),
                    returnEmails = [];
                //emails = emails.replace(/\s*/g, "").split(";");
                for (var i = 0; i < emails.length; i++)
                {
                    var email = $(emails[i]).attr("title");
                    if (isEmailCorrect(email) === true)
                    {
                        returnEmails.push(email);
                    }
                }
                return returnEmails;
            }

            function isEmailCorrect(email)
            {
                return email.match(/^(("[\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) !== null;
            }

            function isDomainCorrect(email)
            {
                var supportedDomains = ["gmail",
                                        "aol",
                                        "yahoo",
                                        "live",
                                        "hotmail"
                                        ],
                    domainName = email.match(/@(\w+)\./)[1];
                if (supportedDomains.indexOf(domainName) > -1)
                {
                    return true;
                }
                return false;
            }

            function initBanners()
            {
                var modalWindow = new GPotato.ModalWindow();

                $("#banners_container img").click(function()
                {
                    modalWindow.show("<div id=\"banners_content\" >" + $("#" + $(this).attr("class")).html() + "</div>", translations.bannersHeader);
                });
            }

            function initIndex()
            {
            }

            function $gPotato()
            {
                function ajax(type, url, data, callback)
                {
                    var started = false,
                            timerout = setTimeout(function()
                            {
                                started = true;
                                $("#tracker_container").html("<div id=\"loading_indicator\" class=\"tracker_indicator\" />");
                            }, 300);

                    $.ajax(
                        {
                            type: type,
                            url: url,
                            data: data,
                            success: function(data)
                            {
                                if (started === false)
                                {
                                    clearTimeout(timerout);
                                    $("#tracker_container").html(data);
                                    if (callback)
                                    {
                                        callback();
                                    }
                                }
                                else
                                {
                                    $("#tracker_container").fadeTo("fast", 0, function()
                                    {
                                        $(this).html(data).fadeTo("fast", 1);
                                        if (callback)
                                        {
                                            callback();
                                        }
                                    });
                                }
                            },
                            error: function()
                            {
                            }
                        });
                }

                return {
                    post: function(url, data, callback)
                    {
                        ajax("post", url, data, callback);
                    },
                    get: function(url, callback)
                    {
                        ajax("get", url, null, callback);
                    }
                };
            }

            function initTracker()
            {
                var ids = [],
                        currentPage = 1,
                        status = "";

                //$("#status_bottom_line").addClass("fixie8class");

                $("#chk_all_email").click(function()
                {
                    $("#tracker input[type=checkbox]").attr("checked", $(this).attr("checked"));
                });

                $(".btn_nudge").live("click", function(e)
                {
                    //Left click only
                    if (e.button != 0)
                    {
                        return;
                    }
                    var $this = $(this),
                    id = $this.parent().siblings().find(".hdn_id").eq(0).text(),
                    ids = [id];

                    $this.parent().html("<b>" + $this.text() + "</b>").find
                ("b").css("color", "red").fadeOut("normal", function()
                {
                    $this.remove();
                });

                    $.ajax({
                        type: "post",
                        url: "tracker.aspx?ajax=true&action=nudge",
                        data: { ids: JSON.stringify(ids) },
                        success: function(data)
                        {
                        },
                        error: function()
                        {
                        }
                    });
                    return false;
                });

                $("#pager a").live("click", function()
                {
                    window.scrollTo(0, 0);
                    currentPage = $(this).attr("href").match(/\?.*page=(\d+).*/)[1];
                    $gPotato().get("tracker.aspx?ajax=true&action=get&page=" + currentPage + "&s=" + status);
                    return false;
                });

                $(".status_menu").hover(function()
                {
                    $(this).find("#status_menu_list").stop(true, true).fadeIn(80);
                },
                    function()
                    {
                        $(this).find("#status_menu_list").stop(true, true).hide();
                    });

                $(".status_menu a").click(function()
                {
                    var url = $(this).attr("href"),
                            statusMatch = url.match(/s=(-?\d+)/);
                    if (statusMatch != null)
                    {
                        status = statusMatch[1];
                    }
                    else
                    {
                        status = "";
                    }
                    $gPotato().get("tracker.aspx?ajax=true&action=get&s=" + status);
                    $(this).parent().parent().parent().hide();
                    return false;
                });

                $("#btn_delete").click(function()
                {
                    ids = [];
                    $("#Content table tr").each(function()
                    {
                        var chk = $(this).find("td input[type=checkbox]").eq(0);
                        if (chk.attr("checked") === true)
                        {
                            ids.push(chk.next().text());
                        }
                    });

                    if (ids.length > 0)
                    {
                        $gPotato().post("tracker.aspx?ajax=true&action=delete&page=" + currentPage + "&s=" + status,
                                          { ids: JSON.stringify(ids) });

                    }
                    return false;
                });
            }

            $(function()
            {
                if (GPotato.Referral.initializer != null)
                {
                    GPotato.Referral.initializer();
                }
                if (menuInitialized === false)
                {
                    initMenu();
                }
            });
        } ());





