block, a block, or a tag // we skip tags because something like John 3:16 should not be messed with $anchor_regex = ''; $pre_regex = '
.*<\/pre>';
    $code_regex = '.*<\/code>';
    $tag_regex = '<(?:[^<>\s]*)(?:\s[^<>]*){0,1}>'; // $tag_regex='<[^>]+>';
    $split_regex = "/((?:$anchor_regex)|(?:$pre_regex)|(?:$code_regex)|(?:$tag_regex))/i";

    $parsed_text = preg_split($split_regex,$text,-1,PREG_SPLIT_DELIM_CAPTURE);
    $linked_text = '';

    while (list($key,$value) = each($parsed_text)) {
        if (preg_match($split_regex,$value)) {
	    $linked_text .= $value; // if it is an HTML element or within a link, just leave it as is
	} else {
            $linked_text .= scripturizeAddLinks($value,$bible); // if it's text, parse it for Bible references
	}
    }
    
    return $linked_text;
}

function scripturizeAddLinks($text = '',$bible = DEFAULT_BIBLE_TRANSLATION) {
    $volume_regex = '1|2|3|I|II|III|1st|2nd|3rd|First|Second|Third';

    $book_regex  = 'Genesis|Exodus|Leviticus|Numbers|Deuteronomy|Joshua|Judges|Ruth|Samuel|Kings|Chronicles|Ezra|Nehemiah|Esther';
    $book_regex .= '|Job|Psalms?|Proverbs?|Ecclesiastes|Songs? of Solomon|Song of Songs|Isaiah|Jeremiah|Lamentations|Ezekiel|Daniel|Hosea|Joel|Amos|Obadiah|Jonah|Micah|Nahum|Habakkuk|Zephaniah|Haggai|Zechariah|Malachi';
    $book_regex .= '|Mat+hew|Mark|Luke|John|Acts?|Acts of the Apostles|Romans|Corinthians|Galatians|Ephesians|Phil+ippians|Colossians|Thessalonians|Timothy|Titus|Philemon|Hebrews|James|Peter|Jude|Revelations?';

    // split these up from the Perl code because I want to be able to have an optional period at the end of just the abbreviations

    $abbrev_regex  = 'Gen|Ex|Exo|Lev|Num|Nmb|Deut?|Josh?|Judg?|Jdg|Rut|Sam|Ki?n|Chr(?:on?)?|Ezr|Neh|Est';
    $abbrev_regex .= '|Jb|Psa?|Pr(?:ov?)?|Eccl?|Song?|Isa|Jer|Lam|Eze|Dan|Hos|Joe|Amo|Oba|Jon|Mic|Nah|Hab|Zeph?|Hag|Zech?|Mal';
    $abbrev_regex .= '|Mat|Mr?k|Lu?k|Jh?n|Jo|Act|Rom|Cor|Gal|Eph|Col|Phi|The?|Thess?|Tim|Tit|Phile|Heb|Ja?m|Pe?t|Ju?d|Rev';

    $book_regex='(?:'.$book_regex.')|(?:'.$abbrev_regex.')\.?';

    $verse_regex="\d{1,3}(?::\d{1,3})?(?:\s?(?:[-&,]\s?\d+))*";

    $translation_regex = 'NIV|NASB|AMP|NLT|KJV|ESV|CEV|NET|NKJV|KJ21|ASV|WE|YLT|DARBY|WYC|NIV-UK|TNIV|MSG|NIRV';

    // note that this will be executed as PHP code after substitution thanks to the /e at the end!

    $passage_regex = '/(?:('.$volume_regex.')\s)?('.$book_regex.')\s('.$verse_regex.')(?:\s?[,-]?\s?((?:'.$translation_regex.')|\s?\((?:'.$translation_regex.')\)))?/e';

    $replacement_regex = "scripturizeLinkReference('\\0','\\1','\\2','\\3','\\4','$bible')";

    $text=preg_replace($passage_regex,$replacement_regex,$text);

    return $text;
}

function scripturizeLinkReference($reference='',$volume='',$book='',$verse='',$translation='',$user_translation='') {
    if ($volume) {
       $volume = str_replace('III','3',$volume);
       $volume = str_replace('II','2',$volume);
       $volume = str_replace('I','1',$volume);
       $volume = $volume{0}; // will remove st,nd,and rd (presupposes regex is correct)
    }

   if(!$translation) {
         if (!$user_translation) {
             $translation = DEFAULT_BIBLE_TRANSLATION;
         } else {
             $translation = $user_translation;
         }
   } else {
       $translation = trim($translation,' ()'); // strip out any parentheses that might have made it this far
   }

   $passage = $volume ."+". $book."+".$verse;
   $Verse = $volume . " " . $book . " " . $verse;
   
   // if necessary, just choose part of the verse reference to pass to the web interfaces
   // they wouldn't know what to do with John 5:1-2, 5, 10-13 so I just give them John 5:1-2
   // this doesn't work quite right with something like 1:5,6 - it gets chopped to 1:5 instead of converted to 1:5-6
   if ($verse) {
       $verse = strtok($verse,',& ');
   }

   switch ($translation) {
        case 'ESV':
        	//The ESV API allows us to do much more with this translation.  Options for the ESV are set on the settings page of the plugin
			If(variable_get("scripturefilter_default_displaystyle", 'tooltip')=='tooltip'){
			$link = esv_tooltip($passage, $Verse);
			}
			elseif(variable_get("scripturefilter_default_displaystyle", 'tooltip')=='inline'){
			$link = esv_inline($passage,$Verse);
			}
	break;
        case 'NET':
             $link = 'http://net.bible.org/passage.php?passage=';
             $title = 'New English Translation';
             $link = sprintf('%s',$link,htmlentities(urlencode(trim("$volume $book $verse"))),$title,trim($reference));
             break;
	case 'TNIV':
             $link = 'http://www.tniv.info/bible/passagesearch.php?passage_request=';
             $title = 'Today\'s New International Version';
             $link = sprintf('%s',$link,htmlentities(urlencode(trim("$volume $book $verse"))),$title,trim($reference));
	     break;
        default:
             $link = "http://biblegateway.com/cgi-bin/bible?language=english&version=$translation&passage=";
             $title = 'Bible Gateway';
             $link = sprintf('%s',$link,htmlentities(urlencode(trim("$volume $book $verse"))),$title,trim($reference));
             break;
    }

    return $link;
}

function esv_getverse($passage){
//Set options for ESV text
		$options =  "&include-footnotes=".variable_get("scripturefilter_esv_include-footnotes",TRUE);
		$options .= "&include-audio-link=".variable_get("scripturefilter_esv_audio",TRUE);
		$options .= "&audio-format=".variable_get('scripturefilter_esv_audio-format', 'flash');
		$options .= "&audio-version=".variable_get('scripturefilter_esv_audio-version', 'mm');
		$options .= "&include-headings=".variable_get("scripturefilter_esv_include-headings",TRUE);
		$options .= "&include-subheadings=".variable_get("scripturefilter_esv_include-subheadings",TRUE);
		$options .= "&include-verse-numbers=".variable_get("scripturefilter_esv_include-verse-numbers",TRUE);


             $url = "http://www.gnpcb.org/esv/share/get/?key=" . variable_get("scripturefilter_esv_$API_key",IP). "&passage=" . $passage ."&action=doPassageQuery".$options;
             
			 //Pulls text from the ESV website via curl or fopen
				if (function_exists("curl_init")) {
					$ch = curl_init($url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					$VerseText = curl_exec($ch);
					curl_close($ch);
				} else if (ini_get('allow_url_fopen') == true) {
					if ($rvs = fopen($url, 'r')) {
						$VerseText = "";

						while (!feof($rvs)) {
							$VerseText .= fgets($rvs);
						}

						fclose($rvs);
					}
				} else {
					$readerr = 1;
					$VerseText = "Error retrieving passage text - curl and remote fopen both seem to be disabled on your host.";
				}

				if ($readerr == 0)
				{
					if (strpos($VerseText, "You have exceeded your quota of 500 requests per day.") === false) {
					} else {
						$VerseText = "Error retrieving Bible passage. Please check again tomorrow.";
					}
				}
				   				
	Return $VerseText;
}

function esv_getcache($passage,$reset = FALSE) {
    //This function will check if the passage requested is currently in cache, if it is it will use the cached text, if not it will request the text and add it to the cache for 24hours
	
	if (!$reset && ($cache = cache_get('scripture'.$passage)) && !empty($cache->data)) {
      $VerseText = unserialize($cache->data);
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
	  $VerseText = esv_getverse($passage);
	  //Cache Bible Verse for 24hours - 60*60*24 = 86400
      cache_set('scripture'.$passage, 'cache', serialize($VerseText), time() + 86400);
    }
  return $VerseText;
}

function esv_inline($passage, $Verse){
		//This function generates the link to pass back for the collapsed inline block

				$VerseText = esv_getcache($passage);
				//clean up text
   				$VerseText = str_replace("\n", "", $VerseText);
				$VerseText = str_replace("\r", "", $VerseText);
				$VerseText = str_replace("'", "’", $VerseText);

				//Style the collasible block
				$esv_div_style ="white-space: normal;";
				$esv_div_style.="display: none;"; 
				$esv_div_style.="padding: 10px;";
				$esv_div_style.="border: ". variable_get('scripturefilter_esv_inline-border-style', 'dotted').' '.variable_get("scripturefilter_esv_inline-border-colour",'blue').' '.variable_get("scripturefilter_esv_inline-border-width",'1')."px;";
				$esv_div_style.="border-left: solid ".variable_get("scripturefilter_esv_inline-border-colour",'blue')." ".variable_get("scripturefilter_esv_inline-left-border",'5')."px;";
				$esv_div_style.="color: ".variable_get("scripturefilter_esv_inline-text-colour",'black').";";
	
		$esvSpanId = 'scripturefilter' .mt_rand(); //prefix the rand number with "id" to pass XHTML validation
    $output_dynamic = " ".$Verse." [+/-]" .$VerseText . "";


	Return $output_dynamic;
}

function esv_tooltip($passage, $Verse){
		//This function generates the link to pass back for the hover tooltip
				$VerseText = esv_getcache($passage);

				//Clean up the Text
   				$VerseText = str_replace("\n", "", $VerseText);
				$VerseText = str_replace("\r", "", $VerseText);
				$VerseText = strip_tags($VerseText, "

"); $VerseText = str_replace("(Listen)", "", $VerseText); $VerseText = str_replace("'", "’", $VerseText); preg_match('/

(.*?)
/i', $VerseText, $matches); $VerseRef = $matches[0]; $VerseRef = strip_tags($VerseRef, ""); $VerseText = preg_replace('/
(.*?)
/i', '', $VerseText); IF (variable_get("scripturefilter_esv_show-header",TRUE) == TRUE){ $tooltipheader = trim($Verse); } $ReturnText = ''. trim($Verse) .''; return $ReturnText; } ?>