$(document).ready(function(){
    //get_header_format();
    razmessage();
    razadvanced();
    
    $("#advanced_setting_btn").click(function(){
        $("#advanced_setting_panel").slideToggle();
    });
    
    $("#additional_body").click(function(){
        var myWindow = window.open("", "MsgWindow", "width=500, height=700");
        myWindow.document.write("<textarea rows='20' cols='10' id='html_additional_body' name='html_additional_body'></textarea>");
        
    });
    
});

function razmessage(){
  $("#message-warning").hide();
  $("#message-warning-custom").hide();
  $("#message-warning-custom-2").hide();
  $("#message-error").hide();
  $("#message-success").hide();

  $("#message-warning-vmta").hide();
  $("#message-warning-custom-vmta").hide();
  $("#message-error-vmta").hide();
  $("#message-success-vmta").hide();
}

function close_message_warning(){
    $("#message-warning").slideUp("slow");
}

function close_message_warning_custom(){
    $("#message-warning-custom").slideUp("slow");
}

function close_message_warning_custom_2(){
    $("#message-warning-custom-2").slideUp("slow");
}

function close_message_error(){
    $("#message-error").slideUp("slow");
}

function close_message_success(){
    $("#message-success").slideUp("slow");
}

function close_message_warning_vmta(){
    $("#message-warning-vmta").slideUp("slow");
}

function close_message_warning_custom_vmta(){
    $("#message-warning-custom-vmta").slideUp("slow");
}

function close_message_error_vmta(){
    $("#message-error-vmta").slideUp("slow");
}

function close_message_success_vmta(){
    $("#message-success-vmta").slideUp("slow");
}

function processing_show(){
    $("#processing").html("<div class='progress progress-info progress-striped active'><div class='bar' style='width: 100%;'>&nbsp;&nbsp;Processing...&nbsp;&nbsp;</div></div>");
    $("#processing").show();
}

function processing_hide(){
    $("#processing").hide();
}

function processing_show_vmta(){
    $("#processing_vmta").html("<div class='progress progress-info progress-striped active'><div class='bar' style='width: 100%;'>&nbsp;&nbsp;Processing...&nbsp;&nbsp;</div></div>");
    $("#processing_vmta").show();
}

function processing_hide_vmta(){
    $("#processing_vmta").hide();
}

function razadvanced(){
    $("#advanced_setting_panel").hide();
}

function razbody(){
    $("#source_text").hide();
    $("#source_html").hide(); 
}

function body1(){ 
     razbody();
     $("#source_text").fadeIn(); 
}
function body2(){ 
     razbody();
     $("#source_html").fadeIn(); 
}
function body3(){ 
     razbody();
     $("#source_text").fadeIn();   
     $("#source_html").fadeIn(); 
}

function formatBytes(bytes) {
    if(bytes < 1024) return bytes + " Bytes";
    else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KB";
    else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MB";
    else return(bytes / 1073741824).toFixed(3) + " GB";
}

function calculate_negative_size(){
    var negative=$("#additional_negative").val();
    var count=$("#repeat_negative").val();
    if(count>0){
        var bytes=negative.length;
        $("#size_result").text(formatBytes(bytes*count));
    }else{
        $("#size_result").text('Incorrect number');
    }
}

function get_header_format(){
    $("#header_format").text("");
    $("#header_format").text("Waiting for extracting Headers Format...");         
    $.ajax({
        url: 'header_format.php',
        type: 'get',
        data: {
            header_nbr: document.getElementById('header_nbr').value,
            body_type: '1'
        },
        success: function(data) {
            $("#header_format").text(data);          
        }
    });
}

function vmta_select_count(){
    var nbvmtas=$('#vmta option:selected').length;
    var str='';
    if(nbvmtas==0){
        str='No IP Vmta selected';
    }
    if(nbvmtas==1){
        str=nbvmtas+' Vmta selected';
    }
    if(nbvmtas>1){
        str=nbvmtas+' Vmtas selected';
    }
    $("#vmta_count").text(str);
}

function vmta_unselect(){
    $('#vmta option:selected').prop('selected', false);
    vmta_select_count();
}

function refresh(){
    processing_show();
    $.ajax({
        url: 'scripts.php?action=show',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var color="";
            $('#show').dataTable().fnClearTable();
            for (var i = 0; i < list.length; i++) {
                switch(list[i].status){
                    case 'Starting': color='info';break;
                    case 'Sending': color='warning';break;
                    case 'Stopped': color='important';break;
                    case 'Finished': color='success';break;
                    default : color='';
                }
                $('#show').dataTable().fnAddData([ 
                    list[i].id,
                    list[i].date_send,
                    list[i].offer_name,
                    list[i].news_name,
                    list[i].isp_name,
                    list[i].list_name,
                    list[i].data_from+"-"+list[i].data_count,
                    "<div id='idc-sent"+list[i].id+"'>"+list[i].data_sent+"</div>",
                    "<div class='center' id='idc-status"+list[i].id+"'><span class='badge badge-"+color+"'>"+list[i].status+"</span></div>",
                    "<i class='icon-refresh icon-white' title='Refresh' style='cursor: pointer;' onclick='get_real_sent("+list[i].id+");'></i>&nbsp;&nbsp;<i href='#myModal' class='icon-off icon-white' title='Stop' role='button' data-toggle='modal' style='cursor: pointer;' onclick='confirm_campaign("+list[i].id+");'></i>&nbsp;&nbsp;<i class='icon-edit icon-white' title='Edit' style='cursor: pointer;' onclick="+"location.href='send.php?edit_campaign="+list[i].id+"'"+"></i>&nbsp;&nbsp;<i class='icon-signal icon-white' title='Stats' style='cursor: pointer;' onclick="+"location.href='stats/show.php?id_campaign="+list[i].id+"'"+"></i>" 
                    //"<i class='icon-refresh icon-white' title='Refresh' style='cursor: pointer;' onclick='get_real_sent("+list[i].id+");'></i>&nbsp;&nbsp;<i class='icon-off icon-white' title='Stop' style='cursor: pointer;' onclick='stop_campaign("+list[i].id+");'></i>&nbsp;&nbsp;<i class='icon-edit icon-white' title='Edit' style='cursor: pointer;' onclick="+"location.href='edit.php?id_campaign='"+"></i>&nbsp;&nbsp;<i class='icon-signal icon-white' title='Stats' style='cursor: pointer;' onclick=''></i>" 
                ]);
            }
            processing_hide();
        },
        error: function() {
            $("#message-error").slideDown("slow");
            processing_hide();
        }
    });
}

function confirm_campaign(id_campaign){
    $("#stop-campaign-id").html(id_campaign);
}

function stop_campaign(id_campaign){
    processing_show();
    $("#idc-status"+id_campaign+"").html("<span class='badge badge-info'>Stopping</span>");
    $.ajax({
        url: 'scripts.php?action=stop_campaign',
        type: 'get',
        data: {
            id_campaign: id_campaign
        },
        success: function(data) {
            var str=data.replace(/(\r\n|\n|\r)/gm,"");
            //alert(str);
            get_real_sent(id_campaign);
            get_real_status(id_campaign);
            processing_hide();
        },
        error: function() {
            $("#message-error").slideDown("slow");
            processing_hide();
        }
    });
}

function edit_campaign(id){
    processing_show();
    $.ajax({
        url: 'scripts.php?action=edit',
        type: 'get',
        data: {
            id_campaign: id
        },
        success: function(data) {
            var list = JSON.parse(data);
            if(list.length==0){
                $("#message-custom").text("You don't have permission to edit campaigns of other Mailers or other Servers!");
                $("#message-warning-custom").slideDown("slow");
                setTimeout(function(){close_message_warning_custom();},3000);
            }else{
                $("#from_name").val(list[0].from_name);
                $("#subject").val(list[0].subject);
                $("#from_email").val(list[0].from_email);
                $("#reply_email").val(list[0].reply_email);
                $("#bounce_email").val(list[0].bounce_email);
                $("#return_path").val(list[0].return_path);
                $("#received").val(list[0].received);
                $("#xmailer").val(list[0].xmailer);
                $("#header_nbr").val(list[0].header_nbr);
                $("#header_format").val(list[0].header_format);
                select_server(list[0].id_server_body);
                select_domains_2(list[0].id_server_body,list[0].domain_body);
                $("#redirect_type").val(list[0].redirect_type);
                $('input:radio[name=open_tracker][value='+list[0].open_tracker+']').attr('checked', true);
                $('input:radio[name=body_type][value='+list[0].body_type+']').attr('checked', true);
                if(list[0].body_type==0)body1();
                if(list[0].body_type==1)body2();
                if(list[0].body_type==2)body3();
                $("#text_body").text(list[0].text_body);
                $("#html_body").text(list[0].html_body);
                select_vmtas(list[0].id_vmtas);
                select_sponsor(list[0].id_sponsor);
                select_offer(list[0].id_offer,list[0].id_sponsor);
                select_news(list[0].id_news);
                select_isp(list[0].id_isp);
                select_data_list(list[0].id_data_list,list[0].id_isp,list[0].id_news);
                $("#test_emails_to").val(list[0].test_emails_to);
                $("#test_period").val(list[0].test_period);
                $("#xdelay").val(list[0].xdelay);
                $("#change_ip").val(list[0].change_ip);
                $("#data_from").val((+list[0].data_sent) + (+list[0].data_from) + (+1));
                $("#data_count").val((+list[0].data_count) - (+list[0].data_sent)); 
            }   
            processing_hide();
        },
        error: function() {
            $("#message-error").slideDown("slow");
            processing_hide();
        }
    });
}

function get_real_sent(id_campaign){ 
    processing_show();
    $.ajax({
        url: 'scripts.php?action=get_real_sent',
        type: 'get',
        data: {
            id_campaign: id_campaign
        },
        success: function(data) {
            var str=data.replace(/(\r\n|\n|\r)/gm,"");
            $("#idc-sent"+id_campaign+"").text(str);
            processing_hide();
        },
        error: function() {
            $("#message-error").slideDown("slow");
            processing_hide();
        }
    });
    get_real_status(id_campaign);
}

function get_real_status(id_campaign){
    processing_show();
    $.ajax({
        url: 'scripts.php?action=get_real_status',
        type: 'get',
        data: {
            id_campaign: id_campaign
        },
        success: function(data) {
            var str=data.replace(/(\r\n|\n|\r)/gm,"");
            var color;
            switch (str){
                case 'Starting': color="info";break;
                case 'Sending': color="warning";break;
                case 'Stopped': color="important";break;
                case 'Finished': color="success";break;
                default : color='';
            }
            $("#idc-status"+id_campaign+"").html("<span class='badge badge-"+color+"'>"+str+"</span>");
            processing_hide();
        },
        error: function() {
            $("#message-error").slideDown("slow");
            processing_hide();
        }
    });
    
}

function preview(){
    close_message_error();
    var domain=document.getElementById("domain_body").value;
    if(domain==="0"){
        $("#message-warning-custom-2").show();
    }else{
        var creative=document.getElementById("html_body").value;
        var res=creative.split('[Domain]').join(domain);
        $("#preview").html(res);
        $("#message-warning-custom-2").hide();
    }
}

function test_auto(){
    $('#frame').css('height','404px');
    document.getElementById("sendform").action = "socket_reply.php?action=testauto";
    document.forms["sendform"].submit();
}

function test_campaign(){
    $('#frame').css('height','404px');
    document.getElementById("sendform").action = "socket_reply.php?action=testcampaign";
    document.forms["sendform"].submit();
}

function send_campaign(){
    $('#frame').css('height','404px');
    document.getElementById("sendform").action = "socket_reply.php?action=sendcampaign";
    document.forms["sendform"].submit();
}

function select_server(id){
    var html= "<option value='0' disabled=''>Waiting for extracting Servers...</option>";
    $("#server_body").html(html);
    $.ajax({
        url: 'scripts.php?action=get_servers',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#server_body").html(html);
            $('#server_body option[value=' + id + ']').attr('selected', 'selected');
        }
    });
}

function show_servers(){
    var html= "<option value='0' disabled=''>Waiting for extracting Servers...</option>";
    $("#server_body").html(html);
    $.ajax({
        url: 'scripts.php?action=get_servers',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#server_body").html(html);
        }
    });
}

function select_domains(id){
    var html= "<option value='0' disabled=''>Waiting for selecting Domains...</option>";
    $("#domain_body").html(html);
    $.ajax({
        url: 'scripts.php?action=get_domains',
        type: 'get',
        data: {
            server: id
        },
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].host_name+"'>"+list[i].host_name+"</option>";
            }
            $("#domain_body").html(html);          
        }
    });
}

function select_domains_2(id,domain){
    var html= "<option value='0' disabled=''>Waiting for selecting Domains...</option>";
    $("#domain_body").html(html);
    $.ajax({
        url: 'scripts.php?action=get_domains',
        type: 'get',
        data: {
            server: id
        },
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].host_name+"'>"+list[i].host_name+"</option>";
            }
            $("#domain_body").html(html);
            $("#domain_body").val(domain).trigger("change");
        }
    });
}

function show_domains(){
    var html= "<option value='0' disabled=''>Waiting for extracting Domains...</option>";
    $("#domain_body").html(html);
    $.ajax({
        url: 'scripts.php?action=get_domains',
        type: 'get',
        data: {
            server: document.getElementById("server_body").value
        },
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].host_name+"'>"+list[i].host_name+"</option>";
            }
            $("#domain_body").html(html);          
        }
    });
}

function show_vmtas()
{
    var html= "<option value='0' disabled=''>Waiting for extracting VMTAs...</option>";
    $("#vmta").html(html);
    $.ajax({
        url: 'scripts.php?action=get_vmtas',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+";"+list[i].name+";"+list[i].address_ip+";"+list[i].host_name+";"+list[i].main_ip+"'>"+list[i].name+" | "+list[i].address_ip+" | "+list[i].host_name+"</option>";
            }
            $("#vmta").html(html);
        }
    });
}

function search_vmtas(){
    //$("#vmta option:selected").prop("selected", false);
    var values=$("#search_vmtas_area").val();
    if(values.trim()!==''){
        values=values.split('\n');
        var value='';
        var searchrow='';
        var searchstr='';
        for(var i=0;i<values.length;i++){
            value=values[i].trim();
            $('#vmta option').each(function() {
                searchrow=($(this).val()).split(';');
                searchstr='';
                if($("#search-vmta-name").is(':checked')){
                    searchstr += searchrow[1];
                }
                if($("#search-vmta-ip").is(':checked')){
                    if($("#search-vmta-name").is(':checked')){
                        searchstr +=";";
                    }
                    searchstr+=searchrow[2];
                }
                if($("#search-vmta-host").is(':checked')){
                     if($("#search-vmta-name").is(':checked') || $("#search-vmta-ip").is(':checked')){
                        searchstr +=";";
                    }
                    searchstr+=searchrow[3];
                }
                if(searchstr.match(value)){
                   $("#vmta option[value='"+ $(this).val() +"']").prop('selected', true);
                }
            });
        } 
    }
    vmta_select_count();
}

function show_vmtas_editable(){ 
    var text= "Waiting for extracting VMTAs";
    $("#edit_vmtas_area").val(text);
    $.ajax({
        url: 'scripts.php?action=get_vmtas',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var text = "";
            var ligne= "";
            var cpt=0;
            for (var i = 0; i < list.length; i++) {
                ligne="";
                cpt++;
                if($("#edit-vmta-name").is(':checked')){
                    ligne += list[i].name;
                }
                if($("#edit-vmta-ip").is(':checked')){
                    if($("#edit-vmta-name").is(':checked')){
                        ligne +=";";
                    }
                    ligne+=list[i].address_ip;
                }
                if($("#edit-vmta-host").is(':checked')){
                    if($("#edit-vmta-name").is(':checked') || $("#edit-vmta-ip").is(':checked')){
                        ligne +=";";
                    }
                    ligne+=list[i].host_name;
                }
                if(cpt!=list.length){
                   ligne+="\n"; 
                }
                
                text+=ligne;
                
            }
            $("#edit_vmtas_area").val(text);          
        }
    });
}

function select_vmtas(vmtas){
    var html= "<option value='0' disabled=''>Waiting for selecting VMTAs...</option>";
    $("#vmta").html(html);
    $.ajax({
        url: 'scripts.php?action=get_vmtas',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "";
            var str_vmta=vmtas.split(';');
            var selected="";
            for (var i = 0; i < list.length; i++) {
                selected="";
                for(var vmta in str_vmta){
                    if(str_vmta[vmta]==list[i].id){
                        selected="selected";
                    }
                }
                html += "<option value='"+list[i].id+";"+list[i].name+";"+list[i].address_ip+";"+list[i].host_name+";"+list[i].main_ip+"' "+selected+">"+list[i].name+" | "+list[i].address_ip+" | "+list[i].host_name+"</option>";
            }
            $("#vmta").html(html);          
        }
    });
}

function show_sponsors(){
    var html= "<option value='0' disabled=''>Waiting for extracting Sponsors...</option>";
    $("#sponsor").html(html);
    $.ajax({
        url: 'scripts.php?action=get_sponsors',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#sponsor").html(html);          
        }
    });
}

function select_sponsor(id){
    var html= "<option value='0' disabled=''>Waiting for selecting Sponsor...</option>";
    $("#sponsor").html(html);
    $.ajax({
        url: 'scripts.php?action=get_sponsors',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#sponsor").html(html); 
            $('#sponsor option[value=' + id + ']').attr('selected', 'selected');
        }
    });
}

function show_offers(){
    var html= "<option value='0' disabled=''>Waiting for extracting Offers...</option>";
    $("#offer").html(html);
    $.ajax({
        url: 'scripts.php?action=get_offers',
        type: 'get',
        data: {
            sponsor: document.getElementById("sponsor").value,
            country: document.getElementById("country").value
        },
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#offer").html(html);          
        }
    });
}
function show_fname(){
    var html= "<option value='0' disabled=''>Waiting for extracting From name...</option>";
    $("#fname").html(html);
    $.ajax({
        url: 'scripts.php?action=get_fname',
        type: 'get',
        data: {
            offer: document.getElementById("offer").value
        },
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i]+"'>"+list[i]+"</option>";
            }
            $("#fname").html(html);          
        }
    });
}
function show_subject(){
    var html= "<option value='0' disabled=''>Waiting for extracting Subject...</option>";
    $("#subject1").html(html);
    $.ajax({
        url: 'scripts.php?action=get_subject',
        type: 'get',
        data: {
            offer: document.getElementById("offer").value
        },
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i]+"'>"+list[i]+"</option>";
            }
            $("#subject1").html(html);          
        }
    });
}

function select_offer(id,id_sponsor){
    var html= "<option value='0' disabled=''>Waiting for selecting Offer...</option>";
    $("#offer").html(html);
    $.ajax({
        url: 'scripts.php?action=get_offers',
        type: 'get',
        data: {
            sponsor: id_sponsor
        },
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#offer").html(html);
            $('#offer option[value=' + id + ']').attr('selected', 'selected');
        }
    });
}

function show_news(){
    var html= "<option value='0' disabled=''>Waiting for extracting News...</option>";
    $("#news").html(html);
    $.ajax({
        url: 'scripts.php?action=get_news',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#news").html(html);          
        }
    });
}

function select_news(id){
    var html= "<option value='0' disabled=''>Waiting for selecting News...</option>";
    $("#news").html(html);
    $.ajax({
        url: 'scripts.php?action=get_news',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#news").html(html); 
            $('#news option[value=' + id + ']').attr('selected', 'selected');
        }
    });
}

function show_isps(){
    var html= "<option value='0' disabled=''>Waiting for extracting ISPs...</option>";
    $("#isp").html(html);
    $.ajax({
        url: 'scripts.php?action=get_isps',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#isp").html(html);          
        }
    });
}

function select_isp(id){
    var html= "<option value='0' disabled=''>Waiting for selecting ISP...</option>";
    $("#isp").html(html);
    $.ajax({
        url: 'scripts.php?action=get_isps',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "<option value='0'>Select here...</option>";
            for (var i = 0; i < list.length; i++) {
                html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>";
            }
            $("#isp").html(html);   
            $('#isp option[value=' + id + ']').attr('selected', 'selected');
        }
    });
}

function show_data_lists(){
    if((document.getElementById("news").value!=="0")&&(document.getElementById("isp").value!=="0")){
        var html= "<div class='progress progress-info progress-striped active span10'><div class='bar' style='width: 100%;'>Waiting for extracting Data Lists...</div></div>";
        $("#data-list").html(html);
        $.ajax({
            url: 'scripts.php?action=get_data_lists',
            type: 'get',
            data: {
                news: document.getElementById("news").value,
                isp: document.getElementById("isp").value
            },
            success: function(data) {
                var list = JSON.parse(data);
                var html = "";
                var cpt=0;
                if(list.length===0){
                    html= "<label class='radio'><span class='label label-important'>No Data Selected</span></label>";  
                }else{
                    html += "<select name='data_list' class='span10' tabindex='1'>";
                    for (var i = 0; i < list.length; i++) {
                        html += "<option value='"+list[i].id+"'>"+list[i].name+"&nbsp;("+lisibilite_nombre(list[i].count_isp)+")</option>";
                        cpt+=parseInt(list[i].count_isp);
                    }
                    html += "</select>";
                }
                html+= "<label class='radio' style='margin-top: 10px;padding-left: 0px;'><span class='label label-success'>Total&nbsp;&nbsp;&nbsp;"+lisibilite_nombre(cpt)+"</span></label>";
                $("#data-list").html(html);          
            }
        });
    }else{
        html= "<label class='radio'><span class='label label-important'>No Data Selected</span></label>";
        $("#data-list").html(html);
    }
    
}

function select_data_list(id,id_isp,id_news){
    if((id_news!=="0")&&(id_isp!=="0")){
        var html= "<div class='progress progress-info progress-striped active span10'><div class='bar' style='width: 100%;'>Waiting for selecting Data List...</div></div>";
        $("#data-list").html(html);
        $.ajax({
            url: 'scripts.php?action=get_data_lists',
            type: 'get',
            data: {
                news: id_news,
                isp: id_isp
            },
            success: function(data) {
                var list = JSON.parse(data);
                var html = "";
                var cpt=0;
                if(list.length===0){
                    html= "<label class='radio'><span class='label label-important'>No Data Selected</span></label>";  
                }else{
                    for (var i = 0; i < list.length; i++) {
                        html += "<label class='radio'><input type='radio' name='data_list' value='"+list[i].id+"'><span class='label label'>"+list[i].name+"&nbsp;&nbsp;&nbsp;"+lisibilite_nombre(list[i].count_isp)+"</span></label>";
                        cpt+=parseInt(list[i].count_isp);
                    }
                }
                html+= "<label class='radio'><span class='label label-success'>Total&nbsp;&nbsp;&nbsp;"+lisibilite_nombre(cpt)+"</span></label>";
                $("#data-list").html(html);
                $('input:radio[name=data_list][value='+id+']').attr('checked', true);
            }
        });
    }else{
        html= "<label class='radio'><span class='label label-important'>No Data Selected</span></label>";
        $("#data-list").html(html);
    }
    
}

function show_ips(){
    var html= "<option value='0' disabled=''>Waiting for extracting IP Addresses...</option>";
    $("#address_ip_vmta").html(html);
    $.ajax({
        url: 'scripts.php?action=get_ips',
        type: 'get',
        success: function(data) {
            var list = JSON.parse(data);
            var html = "";
            for (var i = 0; i < list.length; i++) {
                 html += "<option value='"+list[i].address_ip+"'>"+list[i].address_ip+"</option>";
            }
            $("#address_ip_vmta").html(html);
			ip_select_count();
        }
    });
}

function ip_select_count(){
    var nbips=$('#address_ip_vmta option:selected').length;
    var str='';
    if(nbips==0){
        str='No IP Address selected';
    }
    if(nbips==1){
        str=nbips+' IP Address selected';
    }
    if(nbips>1){
        str=nbips+' IP Addresses selected';
    }
    $("#ip_count").text(str);
}

function check_data_vmta(){
   if(document.getElementById("name_vmta").value==="")return false;
   if($('#address_ip_vmta option:selected').length===0)return false;
   if(document.getElementById("host_name_vmta").value==="")return false;
   if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(document.getElementById("host_name_vmta").value)){
	  return false;
   }
   return true;
}

function clear_data_vmta(){
   document.getElementById("name_vmta").value="";
   document.getElementById("address_ip_vmta").value="0";
   document.getElementById("host_name_vmta").value="";
   ip_select_count();
}

function add_vmta(){
	var address_ips='';
	$('#address_ip_vmta option:selected').each(function() {
		address_ips+=$(this).val()+';';
	});
	address_ips=address_ips.substring(0, address_ips.length - 1);

    if(check_data_vmta()){
        processing_show_vmta();
        $.ajax({
            url: 'scripts.php?action=add_vmta',
            type: 'post',
            data: {
                name: document.getElementById("name_vmta").value,
                address_ips: address_ips,
                host_name: document.getElementById("host_name_vmta").value
            },
            success: function(data) {
                var str=data.replace(/(\r\n|\n|\r)/gm,"");
				var ok=true;
                if(str==="0"){ 
                    $("#message-success-vmta").slideDown("slow");
                    setTimeout(function(){close_message_success_vmta();},3000);
                    clear_data_vmta();
					ok=false;
					show_vmtas();
					vmta_select_count();
                }
                if(str==="1"){ 
                    $("#message-custom-vmta").text("VMTA Name already in use for this Server");
                    $("#message-warning-custom-vmta").slideDown("slow");
                    setTimeout(function(){close_message_warning_custom_vmta();},3000);
					ok=false;
                }

				if(ok){
					$("#message-custom-vmta").text(str);
					$("#message-warning-custom-vmta").slideDown("slow");
					setTimeout(function(){close_message_warning_custom_vmta();},3000);
				}

                processing_hide_vmta();
            },
            error: function() {
                $("#message-error-vmta").slideDown("slow");
                setTimeout(function(){close_message_error_vmta();},3000);
                processing_hide_vmta();
            }
            
        });
    }else{
        $("#message-warning-vmta").slideDown("slow");
        setTimeout(function(){close_message_warning_vmta();},3000);
    }
}

function reset_vmtas(){
	$.ajax({
		url: 'scripts.php?action=reset_vmtas',
		type: 'post',
		success: function(data) {
                var str=data.replace(/(\r\n|\n|\r)/gm,"");
				var ok=true;
                if(str==="0"){
					show_vmtas();
					vmta_select_count();
                }
            },
		error: function() {
		}
		
	});	
}

function generate_name(){
	var text = "";
    var possible = "abcdefghijklmnopqrstuvwxyz";
    for( var i=0; i < 5; i++ )text += possible.charAt(Math.floor(Math.random() * possible.length));
	$("#name_vmta").val('mta'+text);
}

function lisibilite_nombre(nbr){
    var nombre = ''+nbr;
    var retour = '';
    var count=0;
    for(var i=nombre.length-1 ; i>=0 ; i--){
            if(count!=0 && count % 3 == 0)
                    retour = nombre[i]+' '+retour ;
            else
                    retour = nombre[i]+retour ;
            count++;
    }
    return retour;
}



