function wplc_pro_admin_javascript()
{
    $ajax_nonce = wp_create_nonce("wplc");
    $agent_id = wplc_ma_check_if_user_is_agent();
    ?>
    <script type="text/javascript">


        var wplc_ajaxurl = '<?php 
    echo plugins_url('/ajax-pro.php', __FILE__);
    ?>
';

        var data = {
            action: 'wplc_admin_long_poll',
            security: '<?php 
    echo $ajax_nonce;
    ?>
',
            wplc_list_visitors_data: false,
            wplc_update_admin_chat_table: false,
            wplc_agent_id: '<?php 
    echo $agent_id;
    ?>
'
        };
        var wplc_pending_refresh = null;

        var wplc_notification_icon_url = '<?php 
    echo plugins_url('/images/wplc_notification_icon.png', __FILE__);
    ?>
';

    //        function wplc_desktop_notification() {
    //            if(typeof Notification !== 'undefined'){
    //                if (!Notification) {
    //                  return;
    //                }
    //                if (Notification.permission !== "granted")
    //                  Notification.requestPermission();
    //
    //                var wplc_desktop_notification = new Notification('New chat received', {
    //                    icon: wplc_notification_icon_url,
    //                    body: "A new chat has been received. Please go the 'Live Chat' page to accept the chat"
    //                });
    //                //Notification.close()
    //            }
    //        }

        function wplc_call_to_server(data) {

            var wplc_run = true;
            jQuery.ajax({
                url: wplc_ajaxurl,
                data: data,
                type: "POST",
                success: function (response) {

                    //Update your dashboard gauge
                    if (response) {
                        //console.log(response);
                        response = JSON.parse(response);
                        data["wplc_list_visitors_data"] = response['wplc_list_visitors_data'];
                        data["wplc_update_admin_chat_table"] = response['wplc_update_admin_chat_table'];
                        //console.log(response['visitors']);
                        if (response['action'] === "wplc_list_visitors") {
                            jQuery("#wplc_admin_visitor_area").html(response['wplc_list_visitors_data']);
                            jQuery( "#wplc_visitor_accordion" ).accordion({heightStyle: "content"});
                        }
                        if (response['action'] === "wplc_update_admin_chat") {
                            jQuery("#wplc_admin_chat_area").html(response['wplc_update_admin_chat_table']);
                            if (response['pending'] === true) {

                                var orig_title = document.getElementsByTagName("title")[0].innerHTML;
                                var ringer_cnt = 0;
                                wplc_pending_refresh = setInterval(function () {
                                    //console.log("chat request");

                                    ringer_cnt++;

                                    if (ringer_cnt <= 1) {
                                        wplc_desktop_notification();
                                    }

                                    if (ringer_cnt > 1) {
                                        clearInterval(wplc_pending_refresh);
                                        wplc_title_alerts4 = setTimeout(function () {
                                            document.title = orig_title;
                                        }, 4000);
                                        return;
                                    }

                                    document.title = "** CHAT REQUEST **";
                                    wplc_title_alerts2 = setTimeout(function () {
                                        document.title = orig_title;
                                    }, 2000);
                                    wplc_title_alerts4 = setTimeout(function () {
                                        document.title = "** CHAT REQUEST **";
                                    }, 4000);

//                                    document.getElementById("wplc_sound").innerHTML = "<embed src='<?php 
    echo plugins_url('/ring.wav', __FILE__);
    ?>
' hidden=true autostart=true loop=false>";

                                        var wplc_notify_sound = '<?php 
    echo plugins_url('/ring.wav', __FILE__);
    ?>
';
                                        var wplc_notify_chat = new Audio(wplc_notify_sound);
    
                                        if(ringer_cnt < 5){
                                            wplc_notify_chat.play();
                                        }

                                }, 5000);
                            } else {
                                //console.log("end");
                                clearInterval(wplc_pending_refresh);
                            }
                        }

                    }
                },
                error: function (jqXHR, exception) {
                    if (jqXHR.status == 404) {
                        console.log('Requested page not found. [404]');
                        wplc_run = false;
                    } else if (jqXHR.status == 500) {
                        console.log('Internal Server Error [500].');
                        wplc_run = false;
                    } else if (exception === 'parsererror') {
                        console.log('Requested JSON parse failed.');
                        wplc_run = false;
                    } else if (exception === 'abort') {
                        console.log('Ajax request aborted.');
                        wplc_run = false;
                    } else {
                        console.log('Uncaught Error.\n' + jqXHR.responseText);
                        wplc_run = false;
                    }
                },
                complete: function (response) {
                    //console.log(wplc_run);
                    if (wplc_run) {
                        setTimeout(function () {
                            wplc_call_to_server(data);
                        }, 3000);
                    }
                },
                timeout: 120000
            });
        }
        ;

        jQuery(document).ready(function () {
            jQuery('body').on("click", "a", function (event) {
                if (jQuery(this).hasClass('wplc_open_chat')) {

                    if (event.preventDefault) {
                        event.preventDefault();
                    } else {
                        event.returnValue = false;
                    }
                    window.open(jQuery(this).attr("href"), jQuery(this).attr("window-title"), "width=800,height=620,scrollbars=yes", false);
                }
            });
            wplc_call_to_server(data);
        });



    </script>
    <?php 
}
function wplc_pro_admin_javascript()
{
    $ajax_nonce = wp_create_nonce("wplc");
    $agent_id = wplc_ma_check_if_user_is_agent();
    if (get_option('wplc_use_external_server')) {
        $wplc_ajax_url = 'http://ccplugins.co/wplc-api/v2/ajax-pro.php';
    } else {
        $wplc_ajax_url = admin_url('admin-ajax.php');
    }
    ?>
    <script type="text/javascript">
        var wplc_ajaxurl = '<?php 
    echo $wplc_ajax_url;
    ?>
';
        var chat_count = 0;
        var wplc_run = true;
        var wplc_had_error = false;
        var ringer_cnt = 0;
        var orig_title = document.getElementsByTagName("title")[0].innerHTML;
        var current_chat_ids = new Object();

        var data = {
            action: 'wplc_admin_long_poll',
            security: '<?php 
    echo $ajax_nonce;
    ?>
',
            wplc_list_visitors_data: false,
            wplc_update_admin_chat_table: false,
            wplc_agent_id: '<?php 
    echo $agent_id;
    ?>
',
            api: '<?php 
    echo get_option('wplc_api_key');
    ?>
',
            domain: '<?php 
    echo get_option('siteurl');
    ?>
'
        };
        var wplc_pending_refresh = null;

        var wplc_notification_icon_url = '<?php 
    echo plugins_url('/images/wplc_notification_icon.png', __FILE__);
    ?>
';

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };

        function wplc_notify_agent() {
            
            var wplc_sounder = document.createElement("embed");
            wplc_sounder.src = '<?php 
    echo plugins_url('/ring.wav', __FILE__);
    ?>
';
            wplc_sounder.hidden = 'true';
            wplc_sounder.autostart = 'true';
            wplc_sounder.loop = 'false';
            wplc_sounder.type = 'audio/x-wav';
            var seconds = new Date().getTime() / 1000;
            wplc_sounder.id = 'wplc_s_'+seconds;

            
            document.body.appendChild(wplc_sounder);  
            
            if (ringer_cnt <= 0) {
                wplc_desktop_notification();
            }
            ringer_cnt++;

            if (ringer_cnt > 1) {
                clearInterval(wplc_pending_refresh);
                wplc_title_alerts4 = setTimeout(function () {
                    document.title = orig_title;
                }, 4000);
                return;
            }

            document.title = "** CHAT REQUEST **";
            wplc_title_alerts2 = setTimeout(function () {
                document.title = "** CHAT REQUEST **";
            }, 2000);
            wplc_title_alerts4 = setTimeout(function () {
                document.title = orig_title;
            }, 4000);


                
            

        }
        function wplc_call_to_server(data) {
            var wplc_run = true;
            var wplc_had_error = false;
            jQuery.ajax({
                url: wplc_ajaxurl,
                data: data,
                type: "POST",
                success: function (response) {

                    //Update your dashboard gauge
                    if (response) {

                        response = JSON.parse(jQuery.trim(response));
                        data["wplc_list_visitors_data"] = response['wplc_list_visitors_data'];
                        data["wplc_update_admin_chat_table"] = response['wplc_update_admin_chat_table'];
                        if (response['action'] === "wplc_update_chat_list") {
                            wplc_handle_chat_output(response['wplc_update_admin_chat_table']);
                            if (response['pending'] === true) {
                                
                                wplc_notify_agent();
                                wplc_pending_refresh = setInterval(function () {
                                    
                                    wplc_notify_agent();
                                }, 5000);
                            } else {
                                clearInterval(wplc_pending_refresh);
                                ringer_cnt = 0;
                            }
                        }

                    }
                },
                error: function (jqXHR, exception) {
                    if (jqXHR.status == 404) {
                        if (window.console) { console.log('Requested page not found. [404]'); }
                        wplc_run = false;
                    } else if (jqXHR.status == 500) {
                        if (window.console) { console.log('Internal Server Error [500].'); }
                        wplc_run = true;
                        wplc_had_error = true;
                        setTimeout(function () {
                            wplc_call_to_server(data);
                        }, 10000);
                    } else if (exception === 'parsererror') {
                        if (window.console) { console.log('Requested JSON parse failed.'); }
                        wplc_run = false;
                    } else if (exception === 'abort') {
                        if (window.console) { console.log('Ajax request aborted.'); }
                        wplc_run = false;
                    } else {
                        if (window.console) { console.log('Uncaught Error.\n' + jqXHR.responseText); }
                        wplc_run = true;
                        wplc_had_error = true;
                        setTimeout(function () {
                            wplc_call_to_server(data);
                        }, 10000);
                        
                    }
                    return;
                },
                complete: function (response) {
                    //console.log(wplc_run);
                    if (wplc_run && !wplc_had_error) {
                      setTimeout(function () {
                          wplc_call_to_server(data);
                      }, 3000);
                    }
                },
                timeout: 120000
            });
        };

        function wplc_handle_chat_output(response) {
            var obj = jQuery.parseJSON(response);
            if (obj === false || obj === null) {
                    jQuery("#wplc_chat_ul").html("");
                    current_chat_ids = {};
                    wplc_handle_count_change(0);
                    
            } else {
                var size = Object.size(current_chat_ids);
                wplc_handle_count_change(size);
                if (size < 1) {
                    /* no prior visitor information, update without any checks */
                    current_chat_ids = obj["ids"];
                    wplc_update_chat_list(false,obj);
                } else {
                    /* we have had visitor information prior to this call, update systematically */
                    if (obj === null) {
                        jQuery("#wplc_chat_ul").html("");
                    } else {
                        current_chat_ids = obj["ids"];
                        wplc_update_chat_list(true,obj);
                    }
                }

            
            }
            var size = Object.size(current_chat_ids);
            wplc_handle_count_change(size);
            
        

        }
        function wplc_handle_count_change(qty) {
            if (qty > chat_count) {
                jQuery(".wplc_chat_vis_count_box").animate({backgroundColor: '#B3D24B'}, 300);
                jQuery(".wplc_vis_online").html(qty);
                jQuery(".wplc_chat_vis_count_box").animate({backgroundColor: 'white'}, 200);
            } else if (qty === chat_count) {
                jQuery(".wplc_vis_online").html(qty);
            } else {
                jQuery(".wplc_chat_vis_count_box").animate({backgroundColor: '#E1734A'}, 300);
                jQuery(".wplc_vis_online").html(qty);
                jQuery(".wplc_chat_vis_count_box").animate({backgroundColor: 'white'}, 200);
            }
            chat_count = qty;
            
        }
    
    
        function wplc_get_status_name(status) {
            if (status === 1) {
                return "<span class='wplc_status_box wplc_status_"+status+"'>complete</span>";
            }
            if (status === 2) {
                return "<span class='wplc_status_box wplc_status_"+status+"'>pending</span>";
            }
            if (status === 3) {
                return "<span class='wplc_status_box wplc_status_"+status+"'>active</span>";
            }
            if (status === 4) {
                return "<span class='wplc_status_box wplc_status_"+status+"'>deleted</span>";
            }
            if (status === 5) {
                return "<span class='wplc_status_box wplc_status_"+status+"'>browsing</span>";
            }
            if (status === 6) {
                return "<span class='wplc_status_box wplc_status_"+status+"'>requesting chat</span>";
            }
            if (status === 8){
                return "<span class='wplc_status_box wplc_status_"+status+"'>chat ended</span></span>";
            }
            if (status === 9){
                return "<span class='wplc_status_box wplc_status_"+status+"'>chat closed</span>";
            }
            if (status === 10){
                return "<span class='wplc_status_box wplc_status_8'>chat minimized</span>";
            }
        }
        function wplc_get_type_box(type) {
            if (type === "New") {
                return "<span class='wplc_status_box wplc_type_new'>New</span>";
            }
            if (type === "Returning") {
                return "<span class='wplc_status_box wplc_type_returning'>Returning</span>";
            }
        }
    
        function wplc_create_chat_ul_element_after_eating_vindaloo(obj,key) {
            console.log(obj[key]);
            var v_img = obj[key]['image'];
            var v_name = obj[key]['name'];
            var v_email = obj[key]['email'];
            var v_browser = obj[key]['data']['browser'];
            var v_browsing = obj[key]['data']['browsing_nice_url'];
            var v_browsing_url = obj[key]['data']['browsing'];
            var v_status = obj[key]['status'];
            var v_time = obj[key]['timestamp'];
            var v_type = obj[key]['type'];
            var v_action = obj[key]['action'];
            var v_status_string = wplc_get_status_name(parseInt(v_status));
            var v_ip_address = obj[key]['data']['ip'];

            var v_vis_html = "<span class='wplc_headerspan_v'>"+v_name+"</span>";
            var v_nr_html = "<span class='wplc_headerspan_nr'><span class='browser-tag'>"+v_browser+"</span> "+wplc_get_type_box(v_type)+"</span>";
            var v_time_html = "<span class='wplc_headerspan_t'><span class='wplc_status_box wplc_status_1'>"+v_time+"</span></span>";
            var v_nr_data = "<span class='wplc_headerspan_d'><span class='wplc-sub-item-header'>Page:</span> <a href='"+v_browsing_url+"' target='_BLANK'>"+v_browsing+"</a><br /><span class='wplc-sub-item-header'>Email:</span> <a href='mailto:"+v_email+"' target='_BLANK'>"+v_email+"</a><br/><span class='wplc-sub-item-header'>IP: </span>"+v_ip_address+"</span>";
            var v_nr_status_html = "<span class='wplc_headerspan_s'>"+v_status_string+"</span>";
            var v_nr_action_html = "<span class='wplc_headerspan_a'>"+v_action+"</span>";

            var wplc_v_html = "\
                <ul id='wplc_p_ul_"+key+"' class='wplc_p_cul' cid='"+key+"'>\n\
                        <li>"+v_vis_html+"</li>\n\
                        <li>"+v_time_html+"</li>\n\
                        <li>"+v_nr_html+"</li>\n\
                        <li>"+v_nr_data+"</li>\n\
                        <li>"+v_nr_status_html+"</li>\n\
                        <li>"+v_nr_action_html+"</li>\n\
                <ul>";
            return wplc_v_html;

            
        }
    
    function wplc_update_chat_list(update,obj) {

        /* first compare existing elements with the elements on the page */
        if (update === false) {
            jQuery( ".wplc_chat_ul" ).html("");

            for (var key in obj) {
                if (obj.hasOwnProperty(key) && key !== "ids") {
                    wplc_v_html = wplc_create_chat_ul_element_after_eating_vindaloo(obj,key);
                    jQuery( "#wplc_chat_ul" ).append(wplc_v_html).hide().fadeIn(2000);
                    
                }
            }
            current_chat_ids = obj["ids"];

        } else {
            
            for (var key in current_chat_ids) {
                current_id = key;
                if (document.getElementById("wplc_p_ul_"+current_id) !== null) {
                    /* element is already there */
                    /* update element */
                    if (typeof obj[current_id] !== "undefined") { /* if this check isnt here, it will throw an error. This check is here incase the item has been deleted. If it has, it will be handled futher down */
                        jQuery("#wplc_p_ul_"+current_id).remove();
                        wplc_v_html = wplc_create_chat_ul_element_after_eating_vindaloo(obj,current_id);
                        jQuery( "#wplc_chat_ul" ).append(wplc_v_html);
                        //jQuery( ".wplc_chats_container" ).append(obj[current_id]['content']);
                    }


                } else {
                    jQuery("#nifty_c_none").hide();
                    /* new element to be created */
                    if (typeof obj[current_id] !== "undefined") { /* if this check isnt here, it will throw an error. This check is here incase the item has been deleted. If it has, it will be handled futher down */
                        
                        wplc_v_html = wplc_create_chat_ul_element_after_eating_vindaloo(obj,current_id);
                        jQuery( "#wplc_chat_ul" ).append(wplc_v_html);
                        
                        jQuery("#wplc_p_ul_"+current_id).hide().fadeIn(2000);
                        
                    }
                }


            }

   
            /* compare new elements to old elements and delete where neccessary */
            jQuery(".wplc_p_cul").each(function(n, i) {
                var cid = jQuery(this).attr("cid");
                if (typeof cid !== "undefined") {
                    if (typeof current_chat_ids[cid] !== "undefined") { /* element still there dont delete */ }
                    else {
                        jQuery("#wplc_p_ul_"+cid).fadeOut(2000).delay(2000).remove();
                        
                    }
                    var size = Object.size(current_chat_ids);
                    wplc_handle_count_change(size);
                }
                // do something with it
            });
            if(jQuery('.wplc_p_cul').length < 1) {
                wplc_handle_count_change(0);
                current_chat_ids = {};
            }
       
        }
    }

        

    jQuery(document).ready(function () {
        jQuery('body').on("click", "a", function (event) {
            if (jQuery(this).hasClass('wplc_open_chat')) {

                if (event.preventDefault) {
                    event.preventDefault();
                } else {
                    event.returnValue = false;
                }
                window.open(jQuery(this).attr("href"), jQuery(this).attr("window-title"), "width=800,height=620,scrollbars=yes", false);
            }
        });
        wplc_call_to_server(data);
    });
    </script>
    <?php 
}