(function($){

    $(document).ready(function(){

		var scroll_value = 350;
        
        $('a[data-toggle="modal"]').each(function(i) {
            $(this).addClass('acb-open-modal-'+i)
        });


        //insert aria roles and display them at the top  of the page outline
        var aria = document.querySelectorAll("header, nav, main, footer, aside, section, article, form");

        var aria_roles = {header: "banner",
                        nav: "navigation",
                        main: "main",
                        footer: "contentinfo",
                        aside: "complementary",
                        section: "region",
                        article: "article",
                        form: "form"};
        var aria_text_arr = [];
        var countAriaText

        for (var i = 0; i < aria.length; i++){
            if($(aria[i]).is(":hidden")){
                continue;
            }
            var aria_text = aria[i].innerText.split(/\s+/).slice(0,3).join(" ");
            aria_text_arr.push(aria_text);
            countAriaText = countInArray(aria_text_arr, aria_text);
            if(countAriaText >= 2){
                continue;
            }

            // every aria has a unique class. using this class we are able to link into this aria 
            $(aria[i]).addClass("aria" + i);
            
            var aria_role = aria[i].nodeName.toLowerCase();
            $(aria[i]).attr("role", aria_roles[aria_role]);

            if(aria_text === ''){
                var aria_children = $(aria[i]).contents().filter(function() {
                        return this.nodeType == 3 && $.trim(this.textContent) != '';
                    })

                var temp_index
                if(aria_children.length >= 2){
                    temp_index = 3;
                }else{
                    temp_index = aria_children.length
                }
                for(var j = 0; j < temp_index; j++){ 
                    aria_text += $.trim(aria_children[j].innerText) + " ";
                }

            }
            var hasImg = $( aria[i] ).has( 'img' ).length;
            if (hasImg > 0) {
                var allListElements = $( 'img' );
                $( aria[i] ).find( allListElements );
                var altImg =  $( aria[i] ).find( allListElements )[0].alt
                aria_text =  altImg;
            }
            if (aria_roles[aria_role] == 'form') {
                aria_text = $(aria[i]).attr('name');

            }
            if($.trim(aria_text) !== ''){
                var header_text = "<div> <span class='acb-" + aria_roles[aria_role] + "'></span>: <br><a href='.aria"+ i +
                    "'>" + aria_text + "...</a></div>";
                
                $("#acb-structure-tab").append(header_text);                
                aria_text = "(<span class='no-text acb-no-text'></span>)"
            }


        
        }
        
        //find all the headers
        var headers = document.querySelectorAll("h1, h2, h3, h4, h5, h6");

        for(var i=0; i<headers.length; i++){
            
            if($(headers[i]).is(":hidden")){
                continue;
            }
            // every header of the page outline has a unique class. using this 
            // class we are able to link into this header 
            $(headers[i]).addClass("acb-header" + i); 

            //check if the element contains a new line character
            var match_n_l = /\r|\n/.exec($(headers[i]).innerText);
            
            //if this element contains a new line character or only whitespaces,
            //this element will not be included in the page outline
            if (match_n_l || ($.trim(headers[i].innerText) === "")) {
                continue;
            }

            // save the element tag
            var elem_tag = headers[i].nodeName.toLowerCase();

            // use the element class for linking href
            var header_text = "<div>" + elem_tag +": " + "<a href='.acb-header" + i + "''>"
                + headers[i].innerText + "</a></div>";

     
            // we insert the headers before #page_outline
            // in order to be in the right form
            $("#acb-outline-tab").append(header_text);

        }

        //toggle page outline window
        $("#acb-sub-skiplinks").on("click keypress", function(e){
        
            var keyCode = e.keyCode || e.which;

            if(keyCode === 1 || keyCode === 13){
                e.preventDefault();
                if( $(".acb-pushmenu").css("right") === "-225px" ){
                //if the bar is hidden and the user presses one of these submenu buttons,
                //the bar must become visible
                    acbPushLeft();
                    showSkipLinksWindow(keyCode);
                }else{
                    if($("#acb-header-window").is(":hidden")) {
                        showSkipLinksWindow(keyCode);
                    }else{
                        //the hotkeys window becomes invisible, if it was visible when 
                        //the user clicked on the button        
                        acbCloseSkipLinksWindow();
                    }

                    //if the bar is visible and the user presses one of these submenu buttons,
                    //we should check if the bar should become invisible
                    acbCloseBar();
                }
            }                       
            
        });

        if ($.cookie('headerwindow') != undefined) {
            if ($.cookie('headerwindow') == 'show') {
                $("#acb-sub-skiplinks").trigger( {type: "click", which: 1});
            }
        }

        function showSkipLinksWindow(keyCode){
            acbSetCookie(".fa-list-ul")           
            $("#acb-header-window").fadeIn("fast", function(){
                $("#acb-structure-title").click();
                if(keyCode === 13){
                    acbFocusElement("#acb-closeOutline")
                }
            })
            
            $.cookie('headerwindow', 'show', {path: '/'} );
            if(!$("#acb-links-window").is(":hidden")){
                $.cookie('linkswindow', 'hide', {path: '/'} );
                $("#acb-links-window").fadeOut(0);    
            }
            if(!$("#acb-hot-keys-v").is(":hidden")){
                $("#acb-hot-keys-v").fadeOut(0);
                $.cookie('hotkeys', 'hide', {path: '/'} );                     
            } 
        }

        //this button closes the page outline window
        $("#acb-closeOutline").click(function(){
            acbCloseSkipLinksWindow();
        }) 

        //show and hide the tabs
        $("#acb-structure-title, #acb-outline-title").click(function(){
            
            //hide all the tabs
            $("#acb-header-window").find(".acb-tabcontent").fadeOut();

            //remove the active class from all elements with class acb-tablinks 
            $("#acb-header-window").find(".acb-li-tablinks").removeClass("acb-active");

            //show the hotkeys
            if( $(this).attr("id") === "acb-structure-title" ){
                $("#acb-structure-tab").fadeIn();    
            }else{
                $("#acb-outline-tab").fadeIn();
            }
            

            //add an "active" class to the link that opened the tab
            $(this).addClass("acb-active");
        })

    //Header Highlight

        //highlight the header to which the user wants to redirect  
        $("#acb-header-window > div a").click(function(e){
            
            //the hrefs of the a-tags are classes, so we don't want to link into the
            //hrefs because it's prohibited  
            e.preventDefault();
            if ( $(this).text() =='Send feedback...' || $(this).text() == 'Σχόλια αξιολόγηση...' ) {
                setTimeout(function(){  acbFocusElement(".acb-modal-close"); }, 500);
                
            }
            
            //we get the class we want to link to
            var anchor_class = $(this).attr("href");

            //we scroll to the element that has this class (only one element has this class)
            //we scroll down for 100 pixels in order to read the header, in case of having a
            // fixed (on top) navigation bar 
            $('html, body').animate({scrollTop:$(anchor_class).offset().top - scroll_value });

            if ($.cookie('contrast') != undefined) {
                if ($.cookie('contrast') == 'b2-white-black') {
                    var background_color = "blue";
                    var color = "white";
                }else if ($.cookie('contrast') == 'b1-yellow-blue') {
                    var background_color = "black";
                    var color = "yellow";
                }else{
                    var background_color = "yellow";
                    var color = "black"
                }
            }else{
                var background_color = "yellow";
                var color = "black";
            }

            var first_char = anchor_class.substring(0, 3);

            if(first_char === ".he"){
                //function that sets the background color of the header
                window.setTimeout(function (){
                    $(anchor_class).css("cssText", "background-color: " + background_color + "!important; \
                                                    color: " + color + "!important;");
                    $(anchor_class).find("*").css("cssText", "background-color: " + background_color + "!important; \
                                                            color: "+ color + "!important;");
                    
                },800);
                
                //function that resets background color to default
                window.setTimeout(function (){
                    $(anchor_class).css("background-color", "");
                    $(anchor_class).css("color", "");
                    $(anchor_class).find("*").css("background-color", "");
                    $(anchor_class).find("*").css("color", "");
                },4000);       

            }else{
                var acbFormId = $(anchor_class).attr('id');
                if (acbFormId == 'acbFormName') {
                    $('.acb-modal').addClass('acb-is-visible');
                }
                //function that sets the border color of the aria
                window.setTimeout(function (){
                    $(anchor_class).addClass('header-border');
                },800);
                
                //function that resets background color to default
                window.setTimeout(function (){
                    $(anchor_class).removeClass('header-border');
                },4000);                
            }

        });


    setTimeout(function(){  
        //Open Links Window
        //the title of the window
        var outline_title = "<div id='acb-links-title'> </div>";
        $("#acb-page-links").before(outline_title);
        
        //find all the a elements
        var a = document.querySelectorAll("a");
        //var yourHost = new RegExp(location.host);

        var searchPattern = "^w+\\d*\\." ;
        var rx = new RegExp( searchPattern, "gim" ) ;
        var replacePattern = "" ;
        var yourHost = location.host.replace( rx, replacePattern ) 
        
        var links = [];
        //search each a element's href for external links
        for(var i=0; i<a.length; i++){

            var a_temp = a[i];
            var a_text = "";

            if( $(a_temp).find("img").length > 0){
                a_text = "(<span class='acb-image'></span>) " + $(a_temp).find("img").first().attr("alt");
                if ($(a_temp).find("img").first().attr("alt") == undefined) {
                    a_text = "(<span class='acb-image'></span>) " + a_temp;

                }
            }else{
                if( $.trim($(a_temp).attr("title")) != ""){
                    a_text = $(a_temp).attr("title");
                }else{
                    a_text = $(a_temp).text();
                }
            }
            
            var a_href = $(a_temp).attr("href");

            if($.trim(a_text) === ""){
                a_text = "<span class='acb-no-title'></span>: " +  $('<a>').attr('href', a_href).attr('hostname');
            }
            //if href is an external link, then we insert it in the links window
            if(  (a_href !== undefined) && (a_href.search("\\.") !== 0) && (a_href.search("#") !== 0) && 
            (a_href.search("mailto") !== 0) && (a_href.search("javascript") !== 0) && (a_href.search("tel") !== 0) && 
            (a_href !== "/") && (a_href !== "")){

                links.push(a_href);
                countLinks = countInArray(links, a_href);

                if(countLinks < 2){
                    if (!a_href.includes('prosvasimotita-amea-protipo-wcag')) {
                        
                        var link_text = "<div><a href='" +  decodeURIComponent(a_href) + 
                        "' >" + a_text + "</a></div>";                
                    
                        isInternal = a_href.indexOf(yourHost) > -1;
                        // we insert the links before in the right category    
                        if(isInternal || a_href.search("/") === 0){
                            $("#acb-internal-links-tab").append(link_text);
                            
                        }else{
                            $("#acb-external-links-tab").append(link_text);
    
                        }
                    }
                }
            }else if(a_href === undefined || a_href === "#"){
                 $(a_temp).attr("onclick","return false");
                 $(a_temp).attr("href", "#");
            }
        }
    }, 900);

/*        //insert the three links of infoscope info window at the end of the links window
        var infoscope_links = ["acb-europe", "acb-accessibility"];
        for(var i=0; i<1; i++){
            var links_text = "<div><a id='" + infoscope_links[i] + "' ></a></div>"
            $("#acb-external-links-tab").append(links_text);
        }
*/
        
        $('#acbClearImg').on('click', function(e) {
            document.getElementById('preview').src = '';
            document.getElementById('prtSc').value = '';
            $('#preview').hide();
            $('#acbClearImg').hide();
        });
        $('.acb-modal-toggle, #acb-sub-comments').on('click keypress', function(e) {
            var keyCode = e.keyCode || e.which;
            if(keyCode === 13 || keyCode === 1 ){
                e.preventDefault();
                $('.modal-msg').css('visibility','hidden');
                $('.modal-msg').html('');
                $('.acb-modal').toggleClass('acb-is-visible');
                if (keyCode == 13) {
                    setTimeout(function(){  acbFocusElement(".acb-modal-close"); }, 500);
                }
            }
        });
        
        $("#prtSc").on("change", function() {


            var file = document.getElementById('prtSc').files[0];
            $('.modal-msg').html('');
            $('.modal-msg').css('visibility','hidden');

            if (file.size >= 1000000) {
                 $('.modal-msg').css('visibility','visible');
                document.getElementById('prtSc').value = '';
                var msg;
                if (language == 'el') msg = 'Η εικόνα δεν μπορεί να είναι πάνω απο 1 MB';
                else msg = 'The image can not be more than 1 MB';
                $('.modal-msg').html('<span class="fa fa-warning fa-2x"> '+msg+' </span>');
                return
            }            

            if (file.type != 'image/png' &&  file.type != 'image/jpeg' ) {
                 $('.modal-msg').css('visibility','visible');
                document.getElementById('prtSc').value = '';
                var msg;
                if (language == 'el') msg = 'Το αρχείο πρέπει να είναι εικόνα (jpg, png)';
                else msg = 'The file must be an image (jpg, png)';
                $('.modal-msg').html('<span class="fa fa-warning fa-2x"> '+msg+' </span>');
                return
            }
            
            document.getElementById('preview').src = '';
            $('#preview').show();
            $('#acbClearImg').show();

            var reader = new FileReader();
            reader.onloadend = function() {
                var imagBased = reader.result;
                document.getElementById('preview').src = imagBased                
            }
            reader.readAsDataURL(file);  
        }); 
                
        $('#sendMail').on('click', function(e) {
            e.preventDefault();

            var acbName = document.getElementById('acbName').value;
            var acbEmail = document.getElementById('acbEmail').value;
            var mailType = document.getElementById('mailType');
            var mailOption = mailType.options[mailType.selectedIndex].value;
            var acbDescription = document.getElementById('acbDescription').value;
            var host = document.location.host;

            if (acbName == '' || acbEmail == '' || acbDescription == '') {
                $('.modal-msg').css('visibility','visible');    
                var msg;
                if (language == 'el') msg = 'Έχετε κενά πεδία';
                else msg = 'You have empty fields';
                $('.modal-msg').html('<span class="fa fa-warning fa-2x"> '+msg+' </span>');
                setTimeout(function(){ $('.modal-msg').css('visibility','hidden'); }, 3000);
                return
            }
            
            var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            var mailIsValid = re.test(String(acbEmail).toLowerCase());
            
            if (!mailIsValid) {
                $('.modal-msg').css('visibility','visible');    
                var msg;
                if (language == 'el') msg = 'Το email δεν φαίνεται έγκυρο';
                else msg = 'Mail is not valid';
                $('.modal-msg').html('<span class="fa fa-warning fa-2x"> '+msg+' </span>');
                setTimeout(function(){ $('.modal-msg').css('visibility','hidden'); }, 3000);
                return                
            }

            var file = document.getElementById('prtSc').files[0];
            if (file == undefined) {
                feedbackRequest(acbName, acbEmail, mailOption, acbDescription, host, false, '');
                return;
            }
            var reader = new FileReader();
            
            reader.onloadend = function() {
                feedbackRequest(acbName, acbEmail, mailOption, acbDescription, host, true, reader);
            }
            reader.readAsDataURL(file);            

        });

        function feedbackRequest(acbName, acbEmail, mailOption, acbDescription, host, feedHasImg, reader){
            var imagBased = null
            if (feedHasImg) {
                imagBased = reader.result;
            }
            $('.modal-msg').css('visibility','visible');
            $('.modal-msg').html('<span class="fa fa-gear fa-spin fa-2x"></span>');

            var request = $.ajax({
                url: '//cpan.infoscope.gr/wp-content/plugins/eucleides/mailFeeback.php',
                method: "POST",
                data: '{"name": "'+acbName+'","email": "'+acbEmail+'","mailOption": "'+mailOption+'","description": "'+acbDescription+'","host": "'+host+'","image": "'+imagBased+'"}',
                contentType: false,
                cache: false,
                processData:false,
            });
            request.done(function( msg ) {
                if (msg == 'success') {
                    document.getElementById('acbName').value = '';
                    document.getElementById('acbEmail').value = '';
                    document.getElementById('acbDescription').value = '';
                    document.getElementById('prtSc').value = '';
                    $('.modal-msg').html('<span class="fa fa-check fa-2x"></span>');
                }
            });              
        }

        //toggle links window
        $("#acb-sub-links").on("click keypress", function(e){

            var keyCode = e.keyCode || e.which;

            if(keyCode === 1 || keyCode === 13){
                e.preventDefault();
                if( $(".acb-pushmenu").css("right") === "-225px" ){
                //if the bar is hidden and the user presses one of these submenu buttons,
                //the bar must become visible
                    acbPushLeft();
                    showLinksWindow(keyCode);
                }else{
                    if($('#acb-links-window').css('display') == 'none') {
                        showLinksWindow(keyCode);
                    }else{
                        //the hotkeys window becomes invisible, if it was visible when 
                        //the user clicked on the button        
                        acbCloseLinksWindow();
                    }

                    //if the bar is visible and the user presses one of these submenu buttons,
                    //we should check if the bar should become invisible
                    acbCloseBar();
                }
            }             
        });     

        if ($.cookie('linkswindow') != undefined) {
            if ($.cookie('linkswindow') == 'show') {
                $("#acb-sub-links").trigger( {type: "click", which: 1});
            }
        } 

        function showLinksWindow(keyCode){
            acbSetCookie(".fa-list-ul")
            $("#acb-links-window").fadeIn("fast", function () {
                
                if ($.cookie('links') == undefined) {
                    $.cookie('links', 'internal', { path: '/'});
                }
                //the first tab of the menu becomes visible
                if ($.cookie('links') == 'internal') {
                    $("#acb-internal-links").click();
                }else{
                    $("#acb-external-links").click();
                }                
                if (keyCode === 13) {
                    acbFocusElement("#acb-closeLinks");
                }
            })
            
            $.cookie('linkswindow', 'show', {path: '/'} );

            if(!$("#acb-header-window").is(":hidden")){
                $("#acb-header-window").fadeOut(0);
                $.cookie('headerwindow', 'hide', {path: '/'} );                     
            }

            if(!$("#acb-hot-keys-v").is(":hidden")){
                $("#acb-hot-keys-v").fadeOut(0);
                $.cookie('hotkeys', 'hide', {path: '/'} );                     
            } 
        }
        function countInArray(linkArray, link) {
            //return linkArray.filter(item => item == link).length;
            var count = 0;
            linkArray.forEach(function(element) {
                if (element == link) {
                     count++
                }
            });
            return count;
        }
        //this button closes the links window
        $("#acb-closeLinks").click(function(){
            acbCloseLinksWindow();
        })       

        //show and hide the tabs
        $("#acb-internal-links, #acb-external-links").click(function(){
            
            //hide all the tabs
            $("#acb-links-window").find(".acb-tabcontent").fadeOut();

            //remove the active class from all elements with class acb-tablinks 
            $("#acb-links-window").find(".acb-li-tablinks").removeClass("acb-active");

            //show the links
            $( "#" + $(this).attr("id") + "-tab").fadeIn();
        
            //add an "active" class to the link that opened the tab
            $(this).addClass("acb-active");
        })

        $("#acb-internal-links").click(function () {
            $.cookie('links', 'internal', { path: '/' });
        })
        
        $("#acb-external-links").click(function () {
            $.cookie('links', 'external', { path: '/' });
        }) 
    });

    this.acbCloseSkipLinksWindow = function(){
        $("#acb-header-window").fadeOut(0);
        $.cookie('headerwindow', 'hide', {path: '/'} );            
    }

    this.acbCloseLinksWindow = function(){
        $("#acb-links-window").fadeOut(0);
        $.cookie('linkswindow', 'hide', {path: '/'} );           
    }
})(jQuery);


