<?php if(!defined('PmWiki'))exit;
/**
  Active telephone links for PmWiki
  Written by (c) Petko Yotov 2014-2017

  This text is written for PmWiki; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 3 of the License, or
  (at your option) any later version. See pmwiki.php for full details
  and lack of warranty.

  Copyright 2014-2017 Petko Yotov www.pmwiki.org/petko
*/
$RecipeInfo['LinkTel']['Version'] = '20170618';

SDVA($LinkFunctions, array('tel:'=>'LinkIMap'));
SDVA($IMap, array('tel:'=>"tel:$1"));
SDVA($IMapLinkFmt, array('tel:'=>"<a class='tel' title='\$LinkAlt' href='\$LinkUrl'>\$LinkText</a>"));

Markup('tel-prefix', '<^>>', '/^\\(:prefix +(.*?) *:\\)/im', '(:div0044 class="tel-prefix" data-tel-prefix="$1":)');
Markup('tel-prefix-end', '<tel-prefix', '/^\\(:prefixend:\\)/im', '(:div0044end:)');

## bare tellinks
Markup('tellink','<urllink',
  "/\\btel:([-+\\d()]*\\d)/",
  "MakeTelLink");

function MakeTelLink($m) {
  extract($GLOBALS["MarkupToHTML"]);
  return Keep(MakeLink($pagename,$m[0],preg_replace('/\\(.*?\\)/', '', $m[1])),'L');
}

SDVA($HTMLFooterFmt, array('LinkTel'=>'<script type="text/javascript"><!--
//<![CDATA[
var TelPrefix = function() {
  try { var divs = document.getElementsByClassName("tel-prefix"); }
  catch(e) { return; }
  for (var i=0; i<divs.length; i++) {
    var prefixes = divs[i].getAttribute("data-tel-prefix").match(/(\+?[-\d+]+)[:=]([-\d,\[\]X]+)/gi);
    var pRX = [];
    if(!prefixes) continue;
    for(var p = 0; p<prefixes.length; p++) {
      var a = prefixes[p].match(/(\+?[-\d+]+)[:=]([-\d,\[\]X]+)/i)
      if(!a) continue;
      var r = "^("+ a[2].replace(/x/ig, "\\\\d").replace(",", "|")+")$";
      pRX.push([ new RegExp(r), a[1] ]);
    }
    var html = divs[i].innerHTML;
    html = html.replace(/<a.*?<\/a *>|<.*?>|\b\d+\b/g, function(str){
      if(str.charAt(0)=="<") return str;
      for(var p=0; p<pRX.length; p++) {
        if(str.match(pRX[p][0]))
          return \'\u200B<a class="tel" href="tel:\'+pRX[p][1]+str+\'">\'+str+\'</a>\u200B\';
      }
      return str;
    }
    );
    divs[i].innerHTML=html;
  }
}
setTimeout("TelPrefix()", 50);
//]]> -->
</script>'));