$(document).ready(function() {
    $(".button").button();
    dialogs();
    directory();
    inviteall();
    $("select[id^='user_type']").change(user_type);
    $(".s_email").click(s_email);
    $(".click").click(click);
    $(".forgot_pass a").click(forgot_pass);
    forgot_submit();
    editable();
    $("#add_to_contacta_list,#add_to_contacta_list2").click(add_to_contacta_list);
    $("#long_list_submit").click(email_to);
    $("input[name^='tolonglist']").click(contact_invite);
    fancybox();
    $(".si").click(function(event){event.stopPropagation();})
    $(".user_agent").click(user_agent);
    $("input[name^='under_invite']").click(under_invite);
    $("input[name^='invite']").click(invite);
    $("input[name^='active']").click(active);
    $(".s_email select,.s_email select").click(function(event){event.stopPropagation();});
    $("#new_company_text").keyup(new_company_text);
    $("#add_user").click(add_user);
    $("#remove_user").click(remove_user);
    $("span[id^='delete_user']").click(delete_user);
    $("select[name^='ch_user_company']").change(user_company);
    $("#webnode_analytics").click(webnode_analytics);
    $("#profile_btn").click(profile);
    $("#profile").click(function(event){event.stopPropagation();});
    $("#profile input[type='button']").click(profile_button);
});

function dialogs(){
    $("#dialog,#dialog2,#dialog3").dialog({
        bgiframe: true,
        resizable: false,
        autoOpen: false, 
        height: 153,
        width:400,
        modal: true,
        buttons: {
            'OK': function(event) {
                $(this).dialog('close');
                event.stopPropagation();
            }
        },
        open: function() {
            $(".ui-widget-overlay").fadeTo(800, 0.5);
            var thisdialog = $(this);
            $(".ui-widget-overlay").click(function(event){
                thisdialog.dialog("close");
                event.stopPropagation();
            })
        },
        beforeclose: function() {
            $(".ui-widget-overlay").fadeTo(500, 0);
        }
    });
    $("#dialog2").dialog("open");

    $("#dialog_delete_user").dialog({
        bgiframe: true,
        resizable: false,
        autoOpen: false,
        height: 153,
        width:400,
        modal: true,
        buttons: {
            'Cancel': function() {
                $(this).dialog('close');
            },
            'Yes': function() {
                var id = $(this).data("id");
                $.ajax({
                    type: "POST",
                    url: "ajax/delete_user.php",
                    data: "id=" + id,
                    success: function(msg){
                        $("#delete_user"+id).parent().parent().parent().parent().slideUp();                        
                    }
                });
                $(this).dialog('close');
            }            
        },
        open: function() {
            $(".ui-widget-overlay").fadeTo(800, 0.5);
            var thisdialog = $(this);
            $(".ui-widget-overlay").click(function(){
                thisdialog.dialog("close")
            })
        },
        beforeclose: function() {
            $(".ui-widget-overlay").fadeTo(500, 0);
        }
    });

    $("#dialog_user_company").dialog({
        bgiframe: true,
        resizable: false,
        autoOpen: false,
        height: 153,
        width:400,
        modal: true,
        buttons: {
            'Cancel': function() {
                $(this).dialog('close');
            },
            'Yes': function() {
                var id = $(this).data("id");
                var value = $(this).data("value");
                var el = $(this).data("el");
                $.ajax({
                    type: "POST",
                    url: "ajax/move_user.php",
                    data: "id=" + id + "&value=" + value,
                    success: function(msg){
                        var moving = '<table style="width:100%">' + $("#delete_user"+id).parent().parent().parent().parent().html() + "</table>";
                        $("#company_subrow"+value).append(moving);
                        
                        $(el).parent().parent().parent().parent().slideUp();
                    }
                });
                $(this).dialog('close');
            }
        },
        open: function() {
            $(".ui-widget-overlay").fadeTo(800, 0.5);
            var thisdialog = $(this);
            $(".ui-widget-overlay").click(function(){
                thisdialog.dialog("close")
            })
        },
        beforeclose: function() {
            $(".ui-widget-overlay").fadeTo(500, 0);
        }
    });


    $("#email_to").dialog({
        bgiframe: true,
        resizable: false,
        autoOpen: false,
        height: 370,
        width:500,
        modal: true,
        buttons: {
            'Send': function() {
                $("#email_to_copy input[name='email_name']").val($("#email_to input[name='email_name']").val());
                $("#email_to_copy input[name='email_email']").val($("#email_to input[name='email_email']").val());
                $("#email_to_copy input[name='email_text']").val($("#email_to textarea[name='email_text']").val());
                $("#email_to input[name='uploadfile']").appendTo("#email_to_copy");
                $("#email_invite_send").submit();
                $(this).dialog('close');
            },
            'Cancel': function() {
                $(this).dialog('close');
            }
        },
        open: function() {
            $(".ui-widget-overlay").fadeTo(800, 0.5);
            var thisdialog = $(this);
            $(".ui-widget-overlay").click(function(){
                thisdialog.dialog("close")
            })
        },
        beforeclose: function() {
            $(".ui-widget-overlay").fadeTo(500, 0);
        }
    });

    $("#deactive").dialog({
        bgiframe: true,
        resizable: false,
        autoOpen: false,
        height: 210,
        width:600,
        modal: true,
        buttons: {
            'OK': function() {
                $("input[name='active"+$(this).data("id")+"']").parent().parent().toggleClass("red");
                var text = $("#deactive-ta").val();
                var id = $(this).data("id");
                var checked = $(this).data("checked");
                $.ajax({
                    type: "POST",
                    url: "ajax/deactive.php",
                    data: "id=" + id + "&text=" + text + "&checked=" + checked,
                    success: function(msg){                        
                        $("#active_status-"+id).html(msg == "" ? "-": msg);
                        success("saved");
                        if(checked){
                            $("input[name='active" + id + "']").parent().parent().next().insertAfter($(".s_email:last").next());
                            $("input[name='active" + id + "']").parent().parent().insertAfter($(".s_email:last").next());
                        }else{
                            $("input[name='active" + id + "']").parent().parent().next().insertBefore(".s_email:first");
                            $("input[name='active" + id + "']").parent().parent().insertBefore($(".s_email:first").prev());                            
                        }
                    }
                });
                $(this).dialog('close');
            },
            'Cancel': function() {
                var checked = $(this).data("checked");
                if(checked){
                    $("input[name='active"+$(this).data("id")+"']").removeAttr("checked");
                }else{
                    $("input[name='active"+$(this).data("id")+"']").attr("checked","checked");
                }
                $(this).dialog('close');
            }
        },
        open: function() {
            $(".ui-widget-overlay").fadeTo(800, 0.5);
            var thisdialog = $(this);
            $(".ui-widget-overlay").click(function(){
                thisdialog.dialog("close")
            })
        }
    });
}

function directory(){
    $('.hider').click(function() {
        var clicked_el = $(this)
        setTimeout(function(){
            var $target = clicked_el;
            var targetOffset = $target.offset().top;
            $('html,body').animate({
                scrollTop: [targetOffset-10, 'easeOutQuart']
            }, 1000);
            return false;
        }, 300)
    });
    $(".hider").click(function(){
        $(".hider").removeClass("close").addClass("more");
        $(this).removeClass("more").addClass("close");
        $(".directory ul li div").slideUp(300);
        var visible = $(this).next().is(":visible");
        if(!visible)$(this).next().slideDown(300);
        if(!visible){
            /*$.ajax({
                type: "POST",
                url: "ajax/click.php",
                data: "text=" + $(this).text(),
                success: function(msg){

                }
            });*/
        }else{
            $(this).removeClass("close").addClass("more");
        }
        return false;
    })
    $(".hider-span").click(function(){
        $(".directory ul li div").slideUp(300);
        var visible = $(this).next().next().is(":visible");
        if(!visible)$(this).next().next().slideDown(300);
        if(!visible){
        /*
            $.ajax({
                type: "POST",
                url: "ajax/click.php",
                data: "text=" + $(this).text(),
                success: function(msg){

                }
            });
            */
        }
        return false;
    })
    $(".hider2").click(function(){
       $(".directory ul li div").slideUp("slow");
       var visible = $(this).next().is(":visible");
       if(!visible)$(this).next().slideDown("slow");
       return false;
    });
}

function inviteall(){
    $("#inviteall").click(function(){
        if($(this).is(":checked")){
            $("input[name^='under_invite']").not(":disabled").attr("checked", "checked");
            $("input[name^='invite']").not(":disabled").attr("checked", "checked");
        }else{
            $("input[name^='under_invite']").not(":disabled").removeAttr("checked");
            $("input[name^='invite']").not(":disabled").removeAttr("checked");
        }        
    });
}

function user_type(){
    var id = this.id.replace(/\D/g,'');
    var type = $("#user_type" + id).val();
    
    $.ajax({
        type: "POST",
        url: "ajax/user_type.php",
        data: "id=" + id + "&type=" + type,
        success: function(msg){
            success(msg);
        }
    });
}

function click(){
/*
   $.ajax({
            type: "POST",
            url: "ajax/click.php",
            data: "text=" + $(this).text(),
            success: function(msg){
            }
    });    
    */
}

function s_email(event){
    $(this).next().find("div").slideToggle();
    $(this).find(".arrow").toggleClass("arrow_d").toggleClass("arrow_u");
    event.stopPropagation();
}

function forgot_pass(){
    $(".forgot_box").slideToggle("slow");
    return false;
}

function forgot_submit(){
        $(".forgot_box").click(function(event){
            event.stopPropagation();
        })
        $("body").click(function(){
            $(".forgot_box,#profile").slideUp("slow");
        });        
        $('#forgot_submit').click(function(){
            var email = $("#forgot_email").val();
            var directory = $("#forgot_directory").val();
            $.ajax({
                type: "POST",
                url: "ajax/forgot_pass.php",
                data: "email=" + email + "&directory=" + directory,
                success: function(msg){
                    if(msg!=""){
                        warning(msg);
                    };
                }
            });
            return false;
        });
}
function editable(){
    $('.edit').editable('https://www.centralway.com/exit/ajax/edit_email.php',{onblur : 'submit',placeholder:'-'});
    $('.edit2').editable('https://www.centralway.com/exit/ajax/edit_company.php',{onblur : 'submit',placeholder:'-'});
    $('.edit_ta').editable('https://www.centralway.com/exit/ajax/edit_company.php',{onblur : 'submit',placeholder:'-' ,type:'textarea',rows:'3',data: function(value, settings) {
      /* Convert <br> to newline. */
      var retval = value.replace(/<br[\s\/]?>/gi, '');
      return retval;
    }
});
    $('.edit_ta2').editable('https://www.centralway.com/exit/ajax/edit_active.php',{onblur : 'submit',type:'textarea',rows:'3',placeholder:'-',data: function(value, settings) {
      /* Convert <br> to newline. */
      var retval = value.replace(/<br[\s\/]?>/gi, '');
      return retval;
    }
});
    $('.edit_branch').editable(
        'https://www.centralway.com/exit/ajax/edit_branch.php',{
             loadurl : 'https://www.centralway.com/exit/ajax/json_branch.php',
             type   : 'select',
             submit : 'OK',
             onblur : 'submit',
             placeholder:'-'
         }
    );
    $('.edit_country').editable(
        'https://www.centralway.com/exit/ajax/edit_country.php',{
             loadurl : 'https://www.centralway.com/exit/ajax/json_country.php',
             type   : 'select',
             submit : 'OK',
             onblur : 'submit',
             placeholder:'-'
         }
    );
    $('.edit_position').editable(
        'https://www.centralway.com/exit/ajax/edit_position.php',{
             loadurl : 'https://www.centralway.com/exit/ajax/json_position.php',
             type   : 'select',
             submit : 'OK',
             onblur : 'submit',
             placeholder:'-'
         }
    );
    $('.edit_salut').editable(
        'https://www.centralway.com/exit/ajax/edit_salut.php',{
             loadurl : 'https://www.centralway.com/exit/ajax/json_salut.php',
             type   : 'select',
             submit : 'OK',
             onblur : 'submit',
             placeholder:'-'
         }
    );
    $('.edit_title').editable(
        'https://www.centralway.com/exit/ajax/edit_title.php',{
             loadurl : 'https://www.centralway.com/exit/ajax/json_title.php',
             type   : 'select',
             submit : 'OK',
             onblur : 'submit',
             placeholder:'-'
         }
    );
    $('.edit_pass').editable('https://www.centralway.com/exit/ajax/edit_pass.php',{placeholder:'-'});

}

function add_to_contacta_list(){
    $(".add_user_table").slideToggle("slow");
    $(".add_contact_top").slideToggle("slow");
    $("#add_to_contacta_list").slideToggle("slow");

    var $target = $(".add_user_table");
    var targetOffset = $target.offset().top;
    $('html,body').animate({
        scrollTop: [targetOffset-10, 'easeOutQuart']
    }, 1000);

    return false;
}

function email_to(){
    $("#email_to").dialog("open");
    return false;
}
function fancybox(){
    $(".fancybox").fancybox({
            'width'			: 650,
            'height'			: 480,
            'autoScale'			: false,
            'transitionIn'		: 'elastic',
            'transitionOut'		: 'elastic',
            'type'			: 'iframe',
            'titlePosition'             : 'inside'
    });
}
function contact_invite(event){
    var id = this.name.replace(/\D/g,'');
    var directory = this.value;
    var checked = $(this).attr("checked");
    if(checked) checked = "true";
    $.ajax({
        type: "POST",
        url: "ajax/contact_invite.php",
        data: "id=" + id + "&directory=" + directory + "&checked=" + checked,
        success: function(msg){
            if(msg!=""){
                warning(msg);
            };
        }
   });

    $(this).parent().parent().toggleClass("gray_td2").effect("pulsate",{times:3},300);
    event.stopPropagation();
}
function active(event){
    var id = this.name.replace(/\D/g,'');
    var checked = $(this).attr("checked");

    var text = $("#active_status-"+id).text();
    if(text=="-"){text = ""};
    $("#deactive textarea").val(text);

    $("#deactive").data("id",id);   
    $("#deactive").data("checked",checked);
    $("#deactive").dialog("open");
    event.stopPropagation();
}

function user_agent(event){
    var title = $(this).attr("title");
    var text = $(this).text();
    if(text.length > 35){title = title.substr(0, 32) + "..."};
    $(this).text(title);
    event.stopPropagation();
}

function under_invite(event){
    var checked = $(this).is(":checked");   

    if(checked){
            $(this).parent().parent().next().find("input[name^='invite']").not(":disabled").attr("checked", "checked");
        }else{
            $(this).parent().parent().next().find("input[name^='invite']").not(":disabled").removeAttr("checked");
        }
    event.stopPropagation();
}

function invite(event){
    var achecked = $(this).parent().parent().parent().parent().parent()
    .find("input[type='checkbox']:not(':disabled')").length;

    var lchecked = $(this).parent().parent().parent().parent().parent()
    .find("input[type='checkbox'][checked]:not(':disabled')").length;
   
    if(lchecked==0){
        $(this).parent().parent().parent().parent().parent().parent().parent().prev().find("input[name^='under_invite']").removeAttr("checked");
    }else{
        $(this).parent().parent().parent().parent().parent().parent().parent().prev().find("input[name^='under_invite']").attr("checked", "checked");
    }
    event.stopPropagation();
}

function new_company_text(){
    var val = $(this).val();
    if(val=="")val="[New Company]";
    $("select[name^='user_company_new']  option[value='0']").text(val)
}

function add_user(){
    var tr1 = "<tr class='adduser_1'>"+$(".adduser_1:first").html()+"</tr>";
    var tr2 = "<tr class='adduser_2'>"+$(".adduser_2:first").html()+"</tr>";
    var tr3 = "<tr class='adduser_3'>"+$(".adduser_3:first").html()+"</tr>";
    var new_user = tr1 + tr2 + tr3;
    $(".adduser_3:last").after(new_user);
    //$(".adduser_1:last select[name^='user_company_new'] option").val($(".adduser_1:first select[name^='user_company_new'] option"));
}

function remove_user(){
    if($(".adduser_1").length>1){
        $(".adduser_1:last").remove();
        $(".adduser_2:last").remove();
        $(".adduser_3:last").remove();
    }
}

function delete_user(){
    var id = this.id.replace(/\D/g,'');
    $("#dialog_delete_user").data("id",id);
    $("#dialog_delete_user").dialog("open");
}

function user_company(){
    var id = this.name.replace(/\D/g,'');
    var value = this.value;
    $("#dialog_user_company").data("id",id);
    $("#dialog_user_company").data("value",value);
    $("#dialog_user_company").data("el",this);
    $("#dialog_user_company").dialog("open");
}

function webnode_analytics(){
    var email = $("#webnode_analytics_value").val();
    var pattern = new RegExp(/^(("[\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);
    if(pattern.test(email)){
        $.ajax({
            type: "POST",
            url: "ajax/webnode_analytics.php",
            data: "email=" + email,
            success: function(msg){
                if(msg!=""){
                    success(msg);
                };
            }
       });
       $(this).parent().slideUp();
    }else{
        warning("Please insert valid E-mail adress")
    }
    return false;
}

function profile(event){
    $("#profile").slideToggle();
    event.stopPropagation();
    return false
}

function profile_button(event){
    var passold = $("#passold").val();
    var passnew = $("#passnew").val();
    var passre = $("#passre").val();
    $.ajax({
        type: "POST",
        url: "ajax/edit_pass.php",
        data: "passold=" + passold + "&passnew=" + passnew + "&passre=" + passre,
        success: function(msg){
            if(msg!=""){
                if(msg!="Password was succesfully changed"){
                    warning(msg);
                }else{
                    success(msg);
                    $("#profile").slideUp();
                    $("#passold").val("");
                    $("#passnew").val("");
                    $("#passre").val("");
                }
            };
        }
    });
    event.stopPropagation();
}

