var iFrameName = 'letter_content_frame';
var myIFrame = document.getElementById(iFrameName);
var process_mail_counter = 0;
var current_mail_send_time = 0;
var mail_subscriber_letters_per_minute = 50;


jQuery(document).ready(function() {

    jQuery(".js_send_letter").click(function() {
        var content = myIFrame.contentWindow.document.body.innerHTML;
        //******        
        var chooced_groups = [];
        var subscribe_theme_checkboxes = jQuery(".email_groups_values");
        jQuery.each(jQuery(subscribe_theme_checkboxes), function(index, item) {
            if (jQuery(item).val() == 1) {
                chooced_groups.push(jQuery(item).attr('name'));
            }
        });

        if (chooced_groups.length == 0) {
            show_info_popup("Choose e-mail groups!");
            return false;
        }

        if (confirm("Please confirm letter sending!")) {
            jQuery("#move_to_top").trigger('click');
            jQuery("#process_bar").show(333);
            var data = {
                action: "app_mail_subscriber_get_letter_recepients",
                subscribe_groups: chooced_groups
            };
            jQuery.post(ajaxurl, data, function(response) {

                var users_ids = jQuery.parseJSON(response);
                current_mail_send_time = parseInt(new Date().getTime() / 1000);
                content = content.replace(/__LETTER_TIME__/gi, current_mail_send_time);

                if (users_ids != null) {
                    if (users_ids.length > 0) {
                        mail_subscriber_letters_per_minute = jQuery("[name=letters_per_minute]").val();
                        if (!mail_subscriber_letters_per_minute) {
                            mail_subscriber_letters_per_minute = 50;
                        }
                        send_one_letter(content, users_ids, 0);
                        //save letter to history (archive)
                        var data = {
                            action: "app_mail_subscriber_save_archive_template",
                            content: content,
                            time: current_mail_send_time
                        };
                        jQuery.post(ajaxurl, data, function(archive_link) {
                            jQuery(".js_history").prepend('<li>' + archive_link + '</li>');
                        });
                    }
                }

                jQuery('html, body').animate({
                    scrollTop: 0
                }, 600);


            });
        }


        return false;
    });

    jQuery(".email_layouts").change(function() {
        jQuery(".archive_title").remove();
        var template = jQuery(this).val();
        jQuery(myIFrame).attr('src', mail_subscriber_app_uri + '/templates/' + template + '/layout.php');
    });

    jQuery('.button_save_mail_subscriber_options').live('click', function()
    {
        var data = {
            action: "app_mail_subscriber_save_settings",
            values: jQuery("[name=mail_subscriber_form]").serialize()
        };
        jQuery.post(ajaxurl, data, function(response) {
            show_info_popup(response);
        });

        return false;
    });

    /*
     jQuery(".app_mail_subscriber_groups").fancybox({
     'autoScale': true
     });
     */
    //checkbox
    jQuery(".app_mail_subscriber_groups_save").live('click', function() {
        var user_id = jQuery(this).attr('user-id');
        var mode = 0;
        if (jQuery(this).is(":checked")) {
            mode = 1;
        }

        var data = {
            action: "app_mail_subscriber_user_set_group",
            user_id: user_id,
            mode: mode,
            group_name: jQuery(this).val()
        };
        jQuery.post(ajaxurl, data, function(response) {

        });
    });

});

/*
 function set_tiny_content(content){
 if(typeof(tinyMCE) == undefined || tinyMCE.activeEditor == null){
 jQuery("#mail_subscriber_message").val(content);
 }else{
 //tinyMCE.execInstanceCommand("mail_subscriber_message", "mceFocus");
 if(tinyMCE.activeEditor.editorId=="mail_subscriber_message"){
 tinyMCE.activeEditor.setContent(content);
 }
 }
 }
 
 function get_tiny_content(){
 var content="";
 if(typeof(tinyMCE) == undefined || tinyMCE.activeEditor == null){
 content=jQuery("#mail_subscriber_message").val();
 }else{
 tinyMCE.execInstanceCommand("mail_subscriber_message", "mceFocus");
 content=tinyMCE.activeEditor.getContent();
 }
 
 return content;
 }
 */


function mail_subscriber_create_new_group() {
    var new_group_name = jQuery("#new_user_group").val();
    if (new_group_name.length > 0) {

        var data = {
            action: "app_mail_subscriber_add_group",
            new_group_name: new_group_name
        };
        jQuery.post(ajaxurl, data, function(response) {
            if (response.length == 0) {
                var html = jQuery("#new_user_group_template").html();
                html = html.replace(/__GROUP_NAME__/gi, new_group_name);
                jQuery("#mail_subscriber_no_groups").remove();
                jQuery("#users_groups").prepend(html);
                //*****
                jQuery("#email_groups_check_list").append('<li><input type="checkbox" class="option_checkbox"><input class="email_groups_values" name="' + new_group_name + '" type="hidden" value="0">&nbsp;' + new_group_name + '</li>');
                jQuery("#email_groups_check_list li:last-child input").uniform();
            } else {
                show_info_popup(response);
            }
        });

    }

    jQuery("#new_user_group").val("")
}

function mail_subscriber_remove_user_group(group_name) {
    if (confirm("Sure about " + group_name + " deleting?")) {
        var data = {
            action: "app_mail_subscriber_remove_group",
            group_name: group_name
        };
        jQuery.post(ajaxurl, data, function(response) {
            jQuery("#users_groups :contains(" + group_name + ")").remove();
        });
    }

}


function send_one_letter(content, users_ids, index) {
    var data = {
        action: "app_mail_subscriber_send_one_letter",
        content: content,
        user_id: users_ids[index]
    };
    jQuery.post(ajaxurl, data, function(responce) {
        responce = jQuery.parseJSON(responce);
        if (responce.error.length) {
            jQuery("#sent_letters_errors").show();
            jQuery("#sent_letters_errors").append("<li>" + responce.error + "</li>");
        }

        //*****
        ++index;
        if (index < users_ids.length) {
            var progress = parseFloat(Math.round((index / users_ids.length) * 100));
            jQuery("#process_progress").css('width', progress + '%');
            jQuery("#process_progress").animate({
                backgroundPosition: '100% 0'
            }, 3000);
            jQuery("#process_bar span").html(progress + '%');

            if (process_mail_counter == mail_subscriber_letters_per_minute) {
                show_static_info_popup("Paused. Please do not reload browser page till letters/messages are sending!");
                window.setTimeout(function() {
                    process_mail_counter = 0;
                    hide_static_info_popup();
                    send_one_letter(content, users_ids, index);
                }, 61000);

                return true;
            }


            ++process_mail_counter;
            send_one_letter(content, users_ids, index);
        } else {
            show_info_popup("Email saved to history!");
            process_mail_counter = 0;
            current_mail_send_time = 0;
            //****
            jQuery("#process_progress").css('width', '100%');
            jQuery("#process_bar span").html("");
            jQuery("#process_progress strong").html("Your mail was successfully sent to " + users_ids.length + " users!");
        }

    });
}


