/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
(function (window, $) {

    var lastFocus;

    function closeSocialModal(dialog) {
        dialog.data.fadeOut('fast', function () {
                dialog.container.slideUp('fast', function () {
                        dialog.overlay.fadeOut('fast', function () {
                            $.modal.close(); // must call this!
                            $('#page').attr('aria-hidden','false');
                            lastFocus.focus();
                            removeOldIframe();
                        });
                });
        });
    }


    function jq_escape( myid ) {

        return myid.replace( /(:|\.|\[|\]|,|=|@)/g, "\\$1" );

    }

    function createSocialModal(event,id, sectionTitles){
         event.preventDefault();
        //window.console&&console.log('id',id);


        var target = event.target.className;
        var social_modal_string = socialModalHtml(target,id, sectionTitles)

         $social_modal = $('<div/>').html(social_modal_string).contents();
        //$("#testdialog").dialog();
       // $social_modal.dialog();
         $.modal($social_modal, {
            closeHTML: "<a href='#' title='Close' role='button' aria-label='close' class='modal-close'></a>",
            //position: ["10%","2%"],
             position: ["10%",],
            opacity: 85,
            //minWidth: $(window).width() - (($(window).width())/6),
            //width: '19em',
             maxWidth: '20em',
             minWidth: '20em',
            overlayId: 'modal-overlay',
            containerId: 'social-container',
            containerCss: {
              'maxHeight' : '100%',
              'overflow' : 'auto',
                'width': '20em'
            },
            autoresize:true,
            focus:true,
            onOpen: function (dialog) {
                $('#page').attr('aria-hidden','true');
                $('#social-container').attr('role','DIALOG')
                                        .attr('aria-label','Print')
                                        .attr('tabindex','0')
                                        .focus();
               // openSocialModal(target, dialog);
                openSocialModal(dialog);
                resizeSocialModal();
            },
            onShow: function(dialog){
                lastFocus = document.activeElement;
                //modalPrintEvents(dialog);
                modalSocialEventsHandler(target,dialog)
            },
            onClose: function (dialog) {
                closeSocialModal(dialog);
            }
       });


    }



    function socialModalHtml(target,id, sectionTitles){

        var checkboxList='';
        var target_type = '';
        var optionList='<select>';
        for (var i = 0; i < sectionTitles.length; i++) {
            checkboxList += '<input type="checkbox" class="listOfSections" name="sectionList" value="' + sectionTitles[i] + '">' + sectionTitles[i] + '<br />';
            optionList += '<option  class="listOfSections"  value="' + sectionTitles[i].replace(/ /g,"-") + '">' + sectionTitles[i] + '</option>';
        }
        optionList += '</select>';


        var title ='';
        if(target == 'social-facebook'){
            target_type = "social";
            title = 'Share on Facebook';
        }else if(target == 'social-linkedin'){
            target_type = "social";
            title = 'Share on Linkedin';
        }else if(target == 'social-twitter'){
            target_type = "social";
            title = 'Share on Twitter';
        }else if(target == 'social-mail'){
            target_type = "social";
            title = 'Share by Mail';
        }else{

            var printSections =  '';
            var printSectionsTitle  = '';
            if(sectionTitles.length > 0){
                printSectionsTitle = '<div class="socialButton printSomeSections"><a class="modbutton" id="Print-Some-Sections">Print only some sections</a></div>';
                printSections = '<div class="socialButton printTheseSections hide"><a class="modbutton disabled" type="submit" data-node-id="' + id + '" id="Print">Print these sections only</a></div>';
            }
            social_modal_string = '<div id="simplemodal-data-print">\n\
            <div class="socialModal">\n\
                <h3>Print Page</h3>\n\
                <hr />\n\
                 <div class="socialButton printAllSections"><a class="modbutton" type="submit" data-node-id="' + id + '" id="Print-All">Print everything</a></div>\n\
                ' + printSectionsTitle + '\n\
                 <form class="print-sections hide">\n\
                        ' + checkboxList + '\n\
                     </form>\n\
                     ' +  printSections + ' \n\
                     <div class="socialButton"><a class="modbutton" type="reset" id="Cancel">Cancel</a></div>\n\
                     <a class="hide" id="Print-All-Link" data-node-id="' + id + '" href ="#">Actually, just print everything</a>\n\
            </div></div>';


        }


        if(target_type == 'social'){
            var socialSections =  '';
            var socialSectionsTitle  = '';
            if(sectionTitles.length > 0){
                socialSectionsTitle = '<div class="socialButton shareSomeSections"><a class="modbutton" id="Share-Some-Sections">Share a section</a></div>';
                socialSections = '<div class="socialButton shareTheseSections hide"><a class="modbutton disabled" type="submit" data-share-type="' + target + '" id="Share">Share this section only</a></div>';
            }

            social_modal_string = '<div id="simplemodal-data-print">\n\
            <div class="socialModal">\n\
                <h3>' + title + '</h3>\n\
                <hr />\n\
                 <div class="socialButton shareAllSections"><a class="modbutton" type="submit" data-share-type="' + target + '" id="Share-All">Share Page</a></div>\n\
                ' + socialSectionsTitle +'\n\
                 <form class="share-sections hide">\n\
                        ' + optionList + '\n\
                     </form>\n\
                      ' + socialSections +'\n\
                     <div class="socialButton"><a class="modbutton" type="reset" id="Cancel">Cancel</a></div>\n\
                     <a class="hide" id="Share-All-Link" data-share-type="' + target + '" href ="#">Actually, just share page</a>\n\
            </div></div>';
        }


        return social_modal_string;

    }


    function modalSocialEventsHandler(target,dialog){

        if(target == 'social-print'){
            modalPrintEvents(dialog);
        }else{
            modalSocialEvents(dialog);
        }
    }

    /**
     * detect IE
     * returns version of IE or false, if browser is not Internet Explorer
     */
    function detectIE() {
        var ua = window.navigator.userAgent;

        // Test values; Uncomment to check result ...

        // IE 10
        // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

        // IE 11
        // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

        // Edge 12 (Spartan)
        // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

        // Edge 13
        // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

        var msie = ua.indexOf('MSIE ');
        if (msie > 0) {
            // IE 10 or older => return version number
            return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        }

        var trident = ua.indexOf('Trident/');
        if (trident > 0) {
            // IE 11 => return version number
            var rv = ua.indexOf('rv:');
            return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
        }

        var edge = ua.indexOf('Edge/');
        if (edge > 0) {
            // Edge (IE 12+) => return version number
            return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
        }

        // other browser
        return false;
    }

    function printIframe(frame, callback) {
        var target = document.getElementById('printIframe');
        target.removeAttribute("style");
        var version = detectIE();
        if (version === false) {
            frame.contentWindow.focus();
            frame.contentWindow.print();
        } else {
            target.contentWindow.document.execCommand('print', false, null);
        }
        callback();
    }

    function removeOldIframe() {
        var oldFrame = document.getElementById("printIframe");
        if (oldFrame) {
            oldFrame.parentNode.removeChild(oldFrame);
        }
    }

    function createIframe(id) {
        removeOldIframe();
        var newPrintUrl = window.location.origin + '/print/' + id;
        $('<iframe id="printIframe">')
            .attr("src",newPrintUrl)
            .appendTo("body")
            .hide();
        return document.getElementById("printIframe");
    }




    function modalSocialEvents(dialog, id) {
        $( window ).resize(function() {
            resizeSocialModal();
        });

        $('#Share-All, #Share-All-Link').click(function(event){
            event.preventDefault();
            var share_type =  this.getAttribute('data-share-type');
            //
            switch(share_type) {
                case "social-facebook":
                    $uri = 'http://www.facebook.com/share.php?u=' + encodeURIComponent(window.location.origin + window.location.pathname);
                    window.open($uri);
                    break;
                case "social-linkedin":
                    $uri = 'http://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(window.location.origin + window.location.pathname);
                    window.open($uri);
                    break;
                case "social-twitter":
                    //$uri =  'http://twitter.com/home?status=' +  $('.breadcrumb-current').html()  + ' ' + encodeURIComponent(window.location.origin + window.location.pathname  );
                    $uri =  'http://twitter.com/intent/tweet?url=' + encodeURIComponent(window.location.origin + window.location.pathname) + '&text=' + $('.breadcrumb-current').html();
                    window.open($uri);
                    break;
                case "social-mail":
                    var mail_str = "mailto:?subject=Link to the National Heart, Lung, and Blood Institute";
                    mail_str += "&body=I thought you might be interested in this Web page from the NHLBI";
                    //var name = social_link_get_name(this);
                    //+ encodeURIComponent(name)
                    mail_str += ". You can view it at " + window.location.origin + window.location.pathname ;
                    location.href = mail_str;
                    break;
            }


        });

        $('#Share-Some-Sections').click(function(){
            $('.shareSomeSections, .shareAllSections').addClass('hide');
            $('.share-sections, .shareTheseSections, #Share-All-Link').removeClass('hide');


        });


        $( document ).on("click",'#Share', function(e) {

            e.preventDefault();
            $ = jQuery;
            var share_type =  this.getAttribute('data-share-type');
            var name = $('.share-sections select').val();
            //
            switch(share_type) {
                case "social-facebook":
                    $uri = 'http://www.facebook.com/share.php?u=' + encodeURIComponent(window.location.origin + window.location.pathname + '#' + name  );
                    window.open($uri);
                    break;
                case "social-linkedin":
                    $uri = 'http://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(window.location.origin + window.location.pathname + '#' + name);
                    window.open($uri);
                    break;
                case "social-twitter":
                    //$uri =  'http://twitter.com/home?status=' +   $('.breadcrumb-current').html() + ' ' + encodeURIComponent(window.location.origin + window.location.pathname + '#' + name )  ;
                    $uri =  'http://twitter.com/intent/tweet?url=' + encodeURIComponent(window.location.origin + window.location.pathname + '#' + name) + '&text=' + $('.breadcrumb-current').html();
                    window.open($uri);
                    break;
                case "social-mail":
                    var mail_str = "mailto:?subject=Link to the National Heart, Lung, and Blood Institute";

                    mail_str += "&body=I thought you might be interested in this Web page from the NHLBI";
                    //var name = social_link_get_name(this);
                    //+ encodeURIComponent(name)
                    mail_str += ". You can view it at " + window.location.origin + window.location.pathname  + '#' + name ;
                    location.href = mail_str;
                    break;
            }

        });


        $('#Cancel').click(function() {
            window.console&&console.log('Cancel');
            closeSocialModal(dialog);
        });
    }



    function modalPrintEvents(dialog, id) {
       $( window ).resize(function() {
           resizeSocialModal();
        });

        $('#Print-All, #Print-All-Link').click(function(event){
            event.preventDefault();
            var id =  this.getAttribute('data-node-id');
            var frame = createIframe(id);
            var $frame = $('#printIframe');
            $frame.load(function() {
                window.console&&console.log('Print All');
                $frame.contents().find(".social_media_header").remove();
                printIframe(frame, function(){
                    frame.hide();
                    closeSocialModal(dialog);
                });
            });
        });

        $('#Print-Some-Sections').click(function(){
            $('.printSomeSections, .printAllSections').addClass('hide');
            $('.print-sections, .printTheseSections, #Print-All-Link').removeClass('hide');
        });

        $('.listOfSections').change(function(){
            var numberOfUnCheckSections = $('.listOfSections:checked').length;
            if (numberOfUnCheckSections>0) {
                $('#Print').removeClass('disabled');
            } else {
                $('#Print').addClass('disabled');
            }
        });

        $('#Print').click(function() {
            if (!$(this).hasClass('disabled')) {
                var id = this.getAttribute('data-node-id'),
                    listOfUnCheckedSections = [],
                    $checkboxList = $('.listOfSections');
                $checkboxList.each(function(index){
                    if (this.checked != true) {
                        listOfUnCheckedSections[index] = this.value;
                    }
                });
                var frame = createIframe(id);
                var $frame = $('#printIframe');
                if (listOfUnCheckedSections.length>0) {
                    $frame.load(function(){
                        for (var i=0; i<listOfUnCheckedSections.length;i++)
                        {
                          //  window.console&&console.log('listOfUnCheckedSections[i]',listOfUnCheckedSections[i]);
                            if (listOfUnCheckedSections[i]) {
                                //var name = ".accordion-header-secondary a[name='" + listOfUnCheckedSections[i] + "']";
                                //$frame.contents().find(name).parent().next().remove()
                                //$frame.contents().find(name).parent().remove();
                                // changed html
                                var name = "#" + listOfUnCheckedSections[i] + "";

                                name = jq_escape( name );
                                console.log(name);
                                $frame.contents().find(name).next().remove()
                                $frame.contents().find(name).remove();
                                var x = 1;
                            }
                        }
                        $frame.contents().find(".newsEventsSection").remove();
                        $frame.contents().find(".healthEducationBlock").remove();
                        $frame.contents().find(".social_media_header").remove();
                        printIframe(frame, function(){
                            frame.hide();
                            closeSocialModal(dialog);
                        });
                    });
                } else {
                    $frame.load(function() {
                        $frame.contents().find(".social_media_header").remove();
                        printIframe(frame, function(){
                            frame.hide();
                            closeSocialModal(dialog);
                        });
                    });
                }
            }
        });

        $('#Cancel').click(function() {
            window.console&&console.log('Cancel');
            closeSocialModal(dialog);
        });
     }

    function openSocialModal(dialog) {
        dialog.data.fadeIn('slow', function () {
                dialog.container.slideDown('slow', function () {
                        dialog.overlay.fadeIn('slow', function () {
                             dialog.data.slideDown('slow');
                        });
                });
        });
    }

    function resizeSocialModal() {
            var screenWidth = $(window).width(),
                bufferWidth = screenWidth/6;
               // containerWidth = screenWidth - bufferWidth;
            //window.console&&console.log('screenWidth',screenWidth);
            //window.console&&console.log('bufferWidth',bufferWidth);
            //$("#print-container").css('width', containerWidth)
        $("#social-container").css('height','auto'); //To reset the container.
            $(window).trigger('resize.simplemodal');
    }





$( document ).ready(function() {

    $('a.nhlbi-social-modal').click(function(event) {
        event.preventDefault();
        var id = this.getAttribute('data-node-id'),
            node_type = this.getAttribute('data-node-type'),
            $sections = $('.accordion-header-secondary'),
            sectionTitles = [];

            $sections.each(function (index) {
                sectionTitles[index] = $(this).attr('id');
            });
        //window.console && console.log('sectionTitles', sectionTitles);
        if (node_type == 'health_topic') {
            createSocialModal(event, id, sectionTitles);
        }else{
            createSocialModal(event, id, []);
        }
        });
    });

}(window, window.jQuery));