$(document).ready(function() {

    initialize();
});

function initialize(){

    // initialize the addthis toolbox
    addthis.toolbox('.addthis_toolbox');

//    switch_to("#referral-success");
    switch_to("#referral-share-options");

    // if click to back :

    $(".back-to-options").click(function(){
        switch_to("#referral-share-options");
        $("#imported-addresses ul").empty();
        $(".selected-contacts-count").text(0);
        //$(".total-possible-earnings").text(0);
        $(".total-contacts-count").text(0);
    });

    $(".back-to-email").click(function(){
        switch_to("#referral-share-options");
        $("#invalid-addresses ul, #imported-addresses ul").empty();
        $(".referral_email_addresses").val($(".referral_email_addresses").attr('title')).removeClass("focused");
        $("#referral-email-invite-container img.loading, #invalid-addresses").hide();
        $(".selected-contacts-count, .total-contacts-count, .total-referral-count").text(0);
    });


    // enable email invite form
    $("#referral-form").submit(function(){

        // show preloader
        $("#referral-email-invite-container img.loading").show();

        // ensures empty fields are serialized as empty
        empty_fields(this);

        // form submit handling
        $(this).ajaxSubmit({
            success: function(response){

                // hide preloader
                $("#referral-addressbook-login-form img.loading").hide();

                // show total valid emails
                var totalReferralCount = response.valid_email_count;
                $(".total-referral-count").text(totalReferralCount);

                // if form data IS valid and HAS invalid emails
                if(response != "Invalid form data" & response.invalid_emails != ""){

                    // populate with invalid emails
                    $.tmpl("invalidTemplate", response.invalid_emails).appendTo("#invalid-addresses ul");

                    // show invalid addresses
                    $('#invalid-addresses').show();
                }
                successful_invite();
            }
        });
    return false;
    });


    // handle addressbook login form
    $("#referral-addressbook-login-form").submit(function(){

        // show preloader
        $("#referral-addressbook-login-form img.loading").show();

        // ensures empty fields are serialized as empty
        empty_fields(this);

        // form submit handling
        $(this).ajaxSubmit({
            type: 'post',
            dataType: 'json',
            success: function(data){

                // hide preloader
                $("#referral-addressbook-login-form img.loading").hide();
                // hide error msgs
                $(".error-msg").hide();

                // go to addressbook
                switch_to("#referral-addressbook");

                // populate with checkboxes
                $.tmpl("contactTemplate", data).appendTo("#imported-addresses ul");

                // update total contacts count
                $(".total-contacts-count").text(data.length);

                // initialize contact counter
                $("#imported-addresses ul li input").change(update_selected_contacts_count);

                // initialize select all/none buttons
                $("#select_all").click(function(event){
                    event.preventDefault();
                    $("input:checkbox").attr("checked","checked");
                    update_selected_contacts_count();
                });
                $("#select_none").click(function(event){
                    event.preventDefault();
                    $("input:checkbox").removeAttr('checked');
                    update_selected_contacts_count();
                });
            },
            error: function (e){
                if(e.status == "500"){
                    // show error msg
                    $("#referral-addressbook-error-msg").show();
                    // hide preloader
                    $("#referral-addressbook-login-form img.loading").hide();
                }
            }
        });
    return false;
    });

    $("#referral-addressbook-invite-form").submit(function(){
        var emails = [];
        $('#imported-addresses input:checked').each(function(index) {
            emails.push($(this).val());
        });
        $(this).ajaxSubmit({
            data: {
                referral_email_addresses: new String(emails),
                referral_text: $("#referral_text").val(),
                deal: $("input#deal").val(),
                location: $("input#location").val(),
            },
            success:function(response){

                // show total valid emails
                var totalReferralCount = response.valid_email_count;
                $(".total-referral-count").text(totalReferralCount);

                if(response != "Invalid form data" & response.invalid_emails != ""){
                    // populate with invalid emails
                    $.tmpl("invalidTemplate", response.invalid_emails).appendTo("#invalid-addresses ul");

                    // show invalid addresses
                    $('#invalid-addresses').show();
                }
                successful_invite();
            }
        });
    return false;
    });

    // enable inline field labels
    $("input[title]").each(function(){
        if ($(this).val() === '') {
            $(this).val($(this).attr('title'));
        }
        $(this).focus(function(){
            if ($(this).val() === $(this).attr('title')) {
                $(this).val('').addClass("focused");
            };
        })
        $(this).blur(function(){
            if ($(this).val() === '') {
                $(this).val($(this).attr('title')).removeClass("focused");
            };
        })
    });

}

var markup1 = '<li><label><input class="invite-checkbox" type="checkbox" name="${name}" value="${emails}"><strong>${name}</strong> ${emails}</label></li>';
var markup2 = '<li>${}</li>';
$.template( "contactTemplate", markup1 );
$.template( "invalidTemplate", markup2 );


function update_selected_contacts_count(){
    var selectedContactsCount = count_selected_contacts();
    var totalPossibleEarnings = selectedContactsCount * REFERRAL_AMOUNT;
    $(".selected-contacts-count").text(selectedContactsCount);
    $(".total-possible-earnings").text(totalPossibleEarnings);
}

function count_selected_contacts(){
    var selectedCount = 0;
    $("#imported-addresses ul li input").each(function(){
        if($(this).attr('checked')){selectedCount ++;}
    });
    return selectedCount;
}


function switch_to(elementID){
    $("div.referral-page").hide();
    $(elementID).show();
}

function empty_fields(element){
     $(element).find(':input').each(function(){
        if ($(this).val() == $(this).attr('title')) {
            $(this).val('');
        }
    });
}

function successful_invite(){
    // hide error msgs
    $(".error-msg").hide();
    switch_to("#referral-success");
}

