/**
 * Scripturizer for Javascript.
 *
 * Link scripture references to ESV at Good News Publisher or Bible Gateway.
 * Instead of having a server side solution in Perl or PHP, the Javascript
 * version provides a solution to drop into any web page and then
 * automatically scan through the document and generate links.
 *
 * For more information, see
 *
 *   http://fucoder.com/code/scripturizer-js/
 *
 * @author Scott Yang <scotty@yang.id.au>
 * @version 2.2
 */ 

/*************************************************************************
 * Configuration section - Here is the place where you can tune the behaviour
 * of Scripturizer for Javascript.
 *************************************************************************/
var ajaxRequest = createXMLHttpRequest();
var div;
function createXMLHttpRequest() 
{  
	var ua;  
	if(window.XMLHttpRequest) 
	{  
		try 
		{  
			ua = new XMLHttpRequest();  
		} 
		
		catch(e) 
		{  
			ua = false;  
		}  
	} 
	else if(window.ActiveXObject) 
	{  
		try 
		{  
			ua = new ActiveXObject("Microsoft.XMLHTTP");  
		} 
		
		catch(e)
		{  
			ua = false;  
		}  
	}  
	return ua;  
}  

function getVersePopup(passage)
{
	var queryString = "?passage=" + passage;
	ajaxRequest.open("GET", "./include/scripturizer_popup_backend.php" + queryString, true);
	ajaxRequest.onreadystatechange = handleVerseResponse;
	ajaxRequest.send(null);
}

function handleVerseResponse()
{
	if(ajaxRequest.readyState == 4)
	{
		var ajaxDisplay = document.getElementById("verseTarget");
		ajaxDisplay.innerHTML = ajaxRequest.responseText;
	}
}

var Scripturizer = {
    /**
     * The document element ID used by Scripturize.doDocument(). If it is
     * empty, or the element cannot be found, then document.body will be used,
     * i.e. the entire document will be passed through scripturizer.
     */
    element: 'content',

    /**
     * Maximum number of DOM text nodes to process before handing the event
     * thread back to GUI and wait for the next round. Smaller value leaders
     * to more responsive UI, but slower to finish parsing.
     */
    max_nodes: 500,

    /**
     * Whether a link will open in a new window. This option does not apply to
     * "esvpopup"
     */
    new_window: true,

    /**
     * Version of Bible to be used. If version is 'esv', link to GNP will be
     * created. If version is 'esvpopup', and 'esvpopup.js' is loaded, then we
     * will use the ESV Popup Reference. Otherwise, link to Bible Gateway will
     * be created.
     */  
    version: 'net'
};



/**
 * Scripturize a DOM element.
 */
Scripturizer.doElement = function(elm) {
    var vol = 'I+|1st|2nd|3rd|First|Second|Third|1|2|3';
    var bok = 'Genesis|Gen|Exodus|Exod?|Leviticus|Lev|Levit?|Numbers|'+
        'Nmb|Numb?|Deuteronomy|Deut?|Joshua|Josh?|Judges|Jdg|Judg?|Ruth|Ru|'+
        'Samuel|Sam|Sml|Kings|Kngs?|Kin?|Chronicles|Chr|Chron|Ezra|Ez|'+
        'Nehemiah|Nehem?|Esther|Esth?|Job|Jb|Psalms?|Psa?|Proverbs?|Prov?|'+
        'Ecclesiastes|Eccl?|Songs?ofSolomon|Song?|Songs|Isaiah|Isa|Jeremiah|'+
        'Jer|Jerem|Lamentations|Lam|Lament?|Ezekiel|Ezek?|Daniel|Dan|Hosea|'+
        'Hos|Joel|Jo|Amos|Am|Obadiah|Obad?|Jonah|Jon|Micah|Mic|Nahum|Nah|'+
        'Habakkuk|Hab|Habak|Zephaniah|Zeph|Haggai|Hag|Hagg|Zechariah|Zech?|'+
        'Malachi|Malac?|Mal|Mat{1,2}hew|Mat?|Matt|Mark|Mrk|Luke|Lu?k|John|Jhn|Jo|Jn|'+
        'Acts?|Ac|Romans|Rom|Corinthians|Cor|Corin|Galatians|Gal|Galat|'+
        'Ephesians|Eph|Ephes|Philippians|Phili?|Colossians|Col|Colos|'+
        'Thessalonians|Thess?|Timothy|Tim|Titus|Tts|Tit|Philemon|Phil?|'+
        'Hebrews|Hebr?|James|Jam|Jms|Jas|Peter|Pete?|Jude|Ju|Revelations?|Rev|'+
        'Revel';
    var ver = '\\d+(:\\d+)?(?:\\s?[-–&]\\s?\\d+)?';
    var regex = '\\b(?:('+vol+')\\s+)?('+bok+')\\.?\\s+('+ver+'(?:\\s?,\\s?'+
        ver+')*)\\b';

    regex = new RegExp(regex, "m");

    var textproc = function(node) {
        var match = regex.exec(node.data);
        if (match) {
            var val = match[0];
            var node2 = node.splitText(match.index);
            var node3 = node2.splitText(val.length);
            var anchor = node.ownerDocument.createElement('A');
            anchor.setAttribute('href', '#');
            anchor.onmouseover = Scripturizer.onmouseover;
           

            node.parentNode.replaceChild(anchor, node2);
            anchor.className = 'scripturized';
            anchor.appendChild(node2);
            return anchor;
        } else {
            return node;
        }
    };

    __traverseDOM(elm.childNodes[0], 1, textproc);
};

/**
 * Scripturize the current document.
 */
Scripturizer.doDocument = function() {
    if ((Scripturizer.element && 
         (e = document.getElementById(Scripturizer.element))) ||
        (e = document.body))
    {
	Scripturizer.doElement(e);
    }
};

/**
 * Initialise the module. It only needs to be done once to create/compile
 * regular expression object.
 */
Scripturizer.init = function() {
	 var onload = 1;
    return onload;
};

Scripturizer.onmouseover = function(ev) {
    ev = ev || window.event;
    var verse = this.childNodes[0].data;
	var link = verse.replace(/ /g, '+');
    link = link.replace(/[,&;]/g, '%2C');
    link = link.replace(/:]/g, '%3A');
	link = 'http://net.bible.org/?' + link;
	stm('Loading verse...',Style[1], 'string', verse) //create popup stm is in include/tooltip.js
	getVersePopup(verse);
    return false;
};

function __decodeQS(qs) {
    var k, v, i1, i2, r = {};
    i1 = qs.indexOf('?');
    i1 = i1 < 0 ? 0 : i1 + 1;
    while ((i1 >= 0) && ((i2 = qs.indexOf('=', i1)) >= 0)) {
        k = qs.substring(i1, i2);
        i1 = qs.indexOf('&', i2);
        v = i1 < 0 ? qs.substring(i2+1) : qs.substring(i2+1, i1++);
        r[unescape(k)] = unescape(v);
    }
    return r;
}

function __traverseDOM(node, depth, textproc) {
    var skipre = /^(a|script|style|textarea)/i;
    var count = 0;
    while (node && depth > 0) {
        count ++;
        if (count >= Scripturizer.max_nodes) {
            var handler = function() {
                __traverseDOM(node, depth, textproc);
            };
            setTimeout(handler, 50);
            return;
        }

        switch (node.nodeType) {
            case 1: // ELEMENT_NODE
                if (!skipre.test(node.tagName) && node.childNodes.length > 0) {
                    node = node.childNodes[0];
                    depth ++;
                    continue;
                }
                break;
            case 3: // TEXT_NODE
            case 4: // CDATA_SECTION_NODE
                node = textproc(node);
                break;
        }

        if (node.nextSibling) {
            node = node.nextSibling;
        } else {
            while (depth > 0) {
                node = node.parentNode;
                depth --;
                if (node.nextSibling) {
                    node = node.nextSibling;
                    break;
                }
            }
        }
    }
}

Scripturizer.doDocument();