/*! floshare.js alias ccshare v0.0.7 | (c) C.I.R.C.E.'s & affini | https://ima.circex.org/LICENSE.md */
/* === LICENZA = LICENSE ===
* This file is released under license Against DRM 2.0 - We do not like DRM
*
* The license guarantees the rights to: reproduce, distribute, publish, perform, broadcast, modify, elaborate, transcribe, translate, lend, rent and sell the content.
* It prohibits to use the content, when distributed togeher with Digital Rights Management mechanisms.
* For more information on DRM see https://www.defectivebydesign.org/what_is_drm_digital_restrictions_management
*
* Every re-distribution, sharing, modification has to maintain the same conditions, mentioning the original authors
* Read the full license at https://web.archive.org/web/20170327160245/http://www.freecreations.org/Against_DRM2.html
* or in the file called LICENSE.md that comes together with this file.
* 
* The original authors of this piece of code can be contacted, supported, etc. by email: info at circe dot org
*
* Please keep the following (C) notice, if you are working on this file.
* [Original work] Copyright (C) [2019] [C.I.R.C.E.'s & affini  https://circex.org]
*
* === "The method is content" = "Il metodo e' contenuto" ===
*/

$( document ).ready(function() {
if ( (window.location.pathname.indexOf('storie')!=-1) || (window.location.pathname.indexOf('html')==-1)  || (window.location.pathname.indexOf('index')!=-1) ){

$('body').append(
    $('<div/>', {id: 'ccshare_panel'}).append([
      $('<div/>', {id: 'ccshare_head'}).append([      
      $('<div/>', {id: 'ccshare_botton'}).append([
              $('<a/>', { id: 'ccchtml', class:"fabutt",title: "Copy",href: "#", html:"&#xf0c5;"}),
              $('<a/>', { id: 'cccemail', class:"fabutt",title: "Email",href: "#", html:"&#xf0e0;"}),
              $('<a/>', { id: 'ccctwitter', class:"fabutt",title: "Twitter",href: "#",html:"&#xf099;"})
              ]
            ),
        $('<div/>', {id: 'ccshare_title',class:'ccshare_icon',html:'Condividi via FLOShare'})
        ]),
        $('<div/>', {id: 'command_line'}).append([
            $('<a/>', {href: "https://creativecommons.org/licenses/by-nc-sa/4.0/",target:'_blank'}).append($('<div/>',{id: 'ccshare_cc',class:'ccshare_icon'})),
            $('<div/>',{id: 'ccshare_cctext'}).append(
              $('<a/>', { text: "CC 4.0(BY-NC-SA)",href: "https://creativecommons.org/licenses/by-nc-sa/4.0/",target:'_blank'})
            )
          ]
        ),
        $('<div/>', {id: 'ccshare_copyarea'}).append([
            $('<div/>', {id: 'ccshare_reference',class:'ccshare_icon'}),
            $('<div/>', {id: 'ccshare_link',class:'ccshare_icon'}),
            $('<div/>', {id: 'ccshare_text'})
          ]
        )
      ]
    )
);

$('#cccopia').click(function(){SelectionManager.copySelection();return false;});
$('#ccchtml').click(function(){SelectionManager.copySelection(false);return false;});
$('#ccctwitter').click(function(){SelectionManager.twitterBtn();return false;});
$('#cccemail').click(function(){SelectionManager.emailBtn();return false;});


let SelectionManager = {
  // Initialize.
  init(panel, page) {
    document.addEventListener("selectionchange",
     this._selectionChangeReceived.bind(this));
    this._panel = panel;
  this._page = page;
    this._hidePanel();
  },
 
 


 
 
  // Sharing selection.
  shareSelection(selection) { 
    if (!selection || selection.type != 'Range') {
      return;
    }

    let content;
    try {
      let range = selection.getRangeAt(0);
    this._selectionRange = this._saveSelection(selection);
      content = range.cloneContents();
    r = selection.getRangeAt(0).getBoundingClientRect();
    relative=document.body.getBoundingClientRect();
    } catch(e) {
      return;
    }

    var text = "";
    content.childNodes.forEach(node => {
      text += this._getTextFromNode(node);
    });
  //mostra testo+ nel div
  var llink=window.location.href.split('#')[0];
  document.getElementById('ccshare_text').innerHTML= text;
  document.getElementById('ccshare_reference').innerHTML= 'Agnese Trocchi ~ Internet Mon Amour';
  document.getElementById('ccshare_link').innerHTML= "<a href='"+llink+"'>"+llink+"</a>";
   
    if(!this._isSamllDevice()){
    this._panel.style.top = ((r.top) - relative.top)  + 'px'; //this will place ele below the selection
    // this._panel.style.left = ((r.left+30) - relative.left)  + 'px';
    this._panel.style.bottom = 'unset';
    }else{
    // this._panel.style.left = 0;
    this._panel.style.top = 'unset';
    this._panel.style.bottom=0;}
    //console.log("ccshare: " + text +"BY-NC-ND");
  },

  twitterBtn() {
  var llink=window.location.href.split('#')[0];
  var text = "";  
  text= '"'+document.getElementById("ccshare_text").innerText.replace(/\r?\n|\r/g,' ') +'"'+'\r\r'+document.getElementById("ccshare_reference").innerText ;

    var _twitterConfig = {
      username: "@ledizioni",
      url: 'https://twitter.com/intent/tweet?text=',
    };
      var txt = text+'\r' + llink + '\r' + 'CC-BY-NC-SA ' +  _twitterConfig.username ;

        window.open(_twitterConfig.url + encodeURIComponent(txt), 'Share', 'width=550, height=280');

    },

  emailBtn() {

      var llink=window.location.href.split('#')[0];
      var sost= "Sostieni: https://ima.circex.org/contacts.html"
      var quote= '"'+document.getElementById("ccshare_text").innerText.replace(/\r?\n|\r/g,' ') +'"'
      var txt= quote +'\r\r'+ 'Da: '+llink+'\r'+document.getElementById("ccshare_reference").innerText + ' ~ CC 4.0 (BY-NC-SA)\r'+sost;
      var mailtxt=encodeURI(txt);
      window.location.href = "mailto:?subject=Internet%20Mon%20Amour&body="+mailtxt;
  },

  copySelection(html = false) {
    var llink=window.location.href.split('#')[0];
    var sost= "Sostieni: https://ima.circex.org/contacts.html"
    var text = "";  

    if (html == true) text= this.getHTMLOfSelection()+document.getElementById("ccshare_link").outerHTML+document.getElementById("ccshare_reference").outerHTML+document.getElementById("ccshare_cc").outerHTML;
    else {
        var quote= '"'+document.getElementById("ccshare_text").innerText.replace(/\r?\n|\r/g,' ') +'"'
        var text= quote +'\r\r'+ 'Da: '+llink+'\r'+document.getElementById("ccshare_reference").innerText + ' ~ CC 4.0 (BY-NC-SA)\r'+sost;
    }
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text); 

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        if (this._isOS()) {
          // save current contentEditable/readOnly status
        var editable = textarea.contentEditable;
        var readOnly = textarea.readOnly;
    
        // convert to editable with readonly to stop iOS keyboard opening
        textarea.contentEditable = true;
        textarea.readOnly = true;
    
        // create a selectable range
        var range = document.createRange();
        range.selectNodeContents(textarea);
    
        // select the range
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        textarea.setSelectionRange(0, 999999);
    
        // restore contentEditable/readOnly to original state
        textarea.contentEditable = editable;
        textarea.readOnly = readOnly;
        } else {
            textarea.select();
        }
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
      if (this._isOS()) {
      this._restoreSelection(this._selectionRange);
      }
        }
    }


    },
  
  //funzione per estrarre html
  getHTMLOfSelection () {
      var range;
      if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        return range.htmlText;
      }
      else if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
          range = selection.getRangeAt(0);
          var clonedSelection = range.cloneContents();
          var div = document.createElement('div');
          div.appendChild(clonedSelection);
          return div.innerHTML;
        }
        else {
          return '';
        }
      }
      else {
        return '';
      }
    },
    
  // Internal methods.
  _getTextFromNode(node) {
    if (node.nodeType == Node.TEXT_NODE) {
      return node.wholeText;
    }

    if (node.nodeType == Node.ELEMENT_NODE) {
  
      var text = "";
      node.childNodes.forEach(node => {
        text += this._getTextFromNode(node);
      });
      return text;
    }

    return "";
  },
  
   _isOrContains(node, container) {
    while (node) {
        if (node === container) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
  },
  
  _isSamllDevice() {
    return (window.innerWidth <= 740);
  },
  
  _isOS() {
        return navigator.userAgent.match(/ipad|iphone/i);
  },
  
  _elementContainsSelection(el, sel) {
    if (sel) {
      if (sel.rangeCount > 0) {
        for (var i = 0; i < sel.rangeCount; ++i) {
          if (!this._isOrContains(sel.getRangeAt(i).commonAncestorContainer, el)) {
            return false;
          }
        }
        return true;
      }
    } else if ( (sel = document.selection) && sel.type != "Control") {
      return this._isOrContains(sel.createRange().parentElement(), el);
    }
    return false;
  },
  
 

  _selectionChangeReceived() {
    let selection = document.getSelection();
    if (!selection || selection.type != 'Range') {
    if(this._page.classList.contains("out-ccpanel")){
      this._hidePanel();
      return;
    }else{
    this._restoreSelection(this._selectionRange);
    }
    }

    clearTimeout(this._timerId);
    this._timerId = setTimeout(this._showPanel.bind(this), 300);
  },
  

  _hidePanel() {
    clearTimeout(this._timerId);
    if (this._panelShown) {
      this._panel.style.display = "none";
      this._panelShown = false;
    }
  },

  _showPanel() {
    let selection = document.getSelection();
    this.shareSelection(selection);
    if (!this._panelShown) {
    if(this._elementContainsSelection(this._page, selection)){
      this._panel.style.display = "block";
      this._panelShown = true;
    }
    
    }
  },
  
  _saveSelection(sel) {
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    return null;
  }, 
  
  _restoreSelection(range) {
    if (range) {
           let selection = document.getSelection();
           selection.removeAllRanges();
           selection.addRange(range);
    }
},
  

  _timerId: 0,
  _panel: null,
  _panelShown: true,
  _selectionRange: null
  
};

var page = document.getElementById('content');

page.setAttribute("class", "out-ccpanel");
SelectionManager.init(document.getElementById("ccshare_panel"),page);
document.getElementById("ccshare_panel").addEventListener("mouseover", function( event ) {   
    page.setAttribute("class", "over-ccpanel");
  }, false);
document.getElementById("ccshare_panel").addEventListener("mouseout", function( event ) {   
    page.setAttribute("class", "out-ccpanel");
  }, false);
  
page.addEventListener('touchend', function( event ) {   
    page.setAttribute("class", "out-ccpanel");
  }, false);
}

});


