// Init Object
var ScripLink = ScripLink ||
{
    initialized: false,
    translation:'NASB',
    verse_hover: true,
    hideDelayTimer: null,
    hideDelay: 350,
    linkCounter: 0,
    box: '\<div id="scripLinkPopUp" onMouseOver="ScripLink.scriply_popupMover()" onMouseOut="ScripLink.scriply_popupMout()">\
                    <div id="scripLinkWrap">\
                    <div id="scripLinkLoading"></div> \
                        <div id="scripLinkTitle"> \
                                <a id="scripLinkSearchTitle" href="#">John 3.16-17</a><a href="#" id="scripLinkshortUrl">http://scrip.ly/Jn3.16-17</a><a href="#" id="scripLinkShare"></a> \
                        </div> \
                        <a href="#" id="scripLinkBible"> \
                            <span class="verse_num first">16</span><np>"For God so loved the world, that He gave His only begotten Son, that whoever believes in Him shall not perish, but have eternal life.<span class="verse_num">17</span>"For God did not send the Son into the world to judge the world, but that the world might be saved through Him.</np> \
                            <span class="verse_num first">16</span><np>"For God so loved the world, that He gave His only begotten Son, that whoever believes in Him shall not perish, but have eternal life.<span class="verse_num">17</span>"For God did not send the Son into the world to judge the world, but that the world might be saved through Him.</np> \
                        </a> \
                    </div> \
                    <div id="scripLinkFoot"> \
                    <a href="http://www.scriplybible.com"><img src="http://www.scriplybible.com/img/mobile/logo.png" alt="Scriply Bible" width="96" height="20" border="0" /><span id="scripLinkAbout">Scriply Bible : Discover and share the word of God.</span></a> \
                    <a href="#" target="_blank" id="scripLinkExpand">expand &raquo;</a> \
                        \
                </div></div>',

    loadCss: function() {
        var headID = document.getElementsByTagName("head")[0]; // End of Header
        var cssNode = document.createElement('link');
        cssNode.type = 'text/css';
        cssNode.rel = 'stylesheet';
        cssNode.href = 'http://scriply.info/extensions/scriplink/wp-plugin.css';
        cssNode.media = 'screen';
        headID.appendChild(cssNode);
    },

    linker: function() {
        if (ScripLink.initialized || typeof Logos != "undefined") { // No Ref Linker
            return 0;
        }

        ScripLink.loadCss();

        var x = document.body.innerHTML;

        var book_names = "(?:&nbsp;)?genesis|gen?|exodus|exod?|leviticus|lev|numbers|numb|deuteronomy|deut?|joshu?a?|judge?s?|ruth?|isaiah|isa|(?:2|ii|second|2 nd) ?samuels?|(?:2|ii|second|2 nd) ?sam|(?:(?:1|i|first|1 st) ?)?samuels?|(?:1|i|first|1 st) ?sam|(?:2|ii|second|2 nd) ?kings|(?:(?:1|i|first|1 st) ?)?kings|(?:2|ii|second|2 nd) ?chronicles?|(?:2|ii|second|2 nd) ?chr|(?:2|ii|second|2 nd) ?chron?|(?:(?:1|i|first|1 st) ?)?chronicles?|(?:1|i|first|1 st) ?chr|(?:1|i|first|1 st) ?chro?n?|ezra?|nehemiah|esther|job|psa?lms?|psa|proverbs?|pro?v?|prvbs?|ecclesiastes?|eccl|eccles|(?:the ?)?song ?of ?solomon|(?:the ?)?song ?of ?songs|sn?gs?|songs?|jeremiah?|jer|lamentations?|lam?|ezekiel|ezek|daniel|dan|hosea|hos|joel?|amo?s?|obadiah?|obad|obd|jonah|micah?|nahum|nahu|habakk?uk|habk?|zephaniah?|zeph?|haggai|hagg?|zechariah?|ze?ch?|malachi?|mal|matthew|matt?|mark|luke?|(?:1|i|first|1 st) ?john?|(?:1|i|first|1 st) ?jhn|(?:1|i|first|1 st) ?jon|(?:2|ii|second|2 nd) ?john?|(?:2|ii|second|2 nd) ?jhn|(?:2|ii|second|2 nd) ?jon|(?:3|iii|third|3 rd) ?john?|(?:3|iii|third|3 rd) ?jhn|(?:3|iii|third|3 rd) ?jon|john|acts|romans?|rom|roms|(?:2|ii|second|2 nd) ?corinthians?|(?:2|ii|second|2 nd) ?cor|(?:2|ii) ?corint?h?|(?:2|ii) ?corth|(?:(?:1|i|first|1 st) ?)?corinthians?|(?:1|i|first|1 st) ?cor|(?:1|i|first|1 st) ?corint?h?|(?:1|i|first|1 st) ?corth|galatians?|gal|galat?|ephesians?|eph|ephe?s?|philippians?|phil|phi|philipp?|colossi?ans?|col|(?:2|ii|second|2 nd) ?thessalonians?|(?:2|ii|second|2 nd) ?thes{1,}|(?:2|ii|second|2 nd) ?thes|(?:2|ii|second|2 nd) ?th|(?:(?:1|i|first|1 st) ?)?thessalonians?|(?:(?:1|i|first|1 st) ?)?thes{1,}|(?:(?:1|i|first|1 st) ?)?thes|(?:(?:1|i|first|1 st) ?)?th|(?:2|ii|second|2 nd) ?timothy?|(?:2|ii|second|2 nd) ?tim|(?:2|ii|second|2 nd) ?tm|(?:(?:1|i|first|1 st) ?)?timothy?|(?:1|i|first|1 st) ?tim|(?:1|i|first|1 st) ?tm|titus|tit|philemon|phl?mn?|philem?|hebrews?|heb|james?|(?:2|ii|second|2 nd) ?peter?|(?:2|ii|second|2 nd) ?petr?|(?:(?:1|i|first|1 st) ?)?peter?|(?:1|i|first|1 st) ?petr?|jude|revelations?|rev|revel";

        //var begining = '[\\("\' >]';
        var begining = '';
        var no_end_links = "(?!<\/a>)";
        //var empty_spaces = "(?:\\s*?)";
        var empty_spaces = '';
        var tags = '(<(a|h1|h2|h3|h4|h5|h6).*?(?:title="(.*)")?>)?';
        var scr_names = "("+book_names+")\\.? ?";
        var chapter_verses = '(\\d+)(?:-|:|–|\\.)?(\\d*)?(?:-|:|–)?(\\d*)?';
        //var translations = " ?(nasb|esv|asv|kjv)?";
        var translations = "(nasb|esv|asv|kjv)?";
        var ending = "";

        // Replace non-links with Links
        var verseExpression = new RegExp(begining + tags + empty_spaces + scr_names + chapter_verses + translations + ending, 'gi');

        x = x.replace(verseExpression, function($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
            //alert($0);
            $0 = $0.replace(/>/,"");
            if ($2 == 'a') {
                // Return Original
                // add in scriply links
                return $0;
            } else {
                linkCounter = linkCounter + 1;
                var scriply_link = '';
                if ($3>0) {
                    scriply_link = $3
                }
                scriply_link = scriply_link+$4;
                if ($5 > 0) {
                    scriply_link = scriply_link+$5;
                }
                if ($6 > 0) {
                    scriply_link = scriply_link+'.'+$6;
                }
                if ($7 > 0) {
                    scriply_link = scriply_link+'-'+$7;
                }
                if ($8 != '' && $8 !=undefined) {
                    scriply_link_long = scriply_link+'/'+$8;
                } else {
                    $8 = '';
                    scriply_link_long = scriply_link;
                }
                return '<a id="scripLink'+linkCounter+'" class="scriply_tag scriply_hover" onMouseOver="this.scriplink.mOver(this)" onMouseOut="this.scriplink.mOut(this)" rel="'+$8+'" name="'+scriply_link+'" target="_blank" href="http://scrip.ly/'+scriply_link_long+'">'+$0+'</a>';
            }
        });

        document.body.innerHTML = x+box;

        loadScripLinkObjs(); // Loop all links
    }, // End of Linker

    ajaxCallback: function(elID, json) {
        var trigger = document.getElementById(elID).scriplink;
        if (json.Settings.results >= 1) {
            trigger.title = json.Search.title;
            trigger.shortURL = json.Search.link;
            trigger.verses = json.Verse;
            trigger.results = json.Settings.results;
            trigger.copywrite = json.Settings.copywrite;
            trigger.searchMatch = 'passage';
        } else if (json.Settings.results <= 0 || json.Settings.results == undefined) {
            trigger.searchMatch = 'fail';
        } else {
            trigger.searchMatch = '';
        }

        trigger.verses = trigger.verses[0].text;
        trigger.fillPopup();
    },

    scriply_popupMover: function() {
        if (ScripLink.hideDelayTimer) clearTimeout(ScripLink.hideDelayTimer);
    },

    scriply_popupMout: function() {
        if (ScripLink.hideDelayTimer) clearTimeout(ScripLink.hideDelayTimer);
        ScripLink.hideDelayTimer = setTimeout(function () {
            ScripLink.hideDelayTimer = null;
            document.getElementById('scripLinkPopUp').style.display = 'none';
        }, ScripLink.hideDelay);
    }    
} // End of Obj

function loadScripLinkObjs() {
    var links = scriply_getElementsByClassName("scriply_hover");
    var el = "";
    for(var i=0; i<links.length; i++) {
        el = links[i];
        el.scriplink = new ScripLinkObj();

        // Set Vars
        el.scriplink.search = el.getAttribute('name');
        if (el.getAttribute('rel') != '') {
            el.scriplink.translation = el.getAttribute('rel');
        } else {
            el.scriplink.translation = ScripLink.translation;
        }
    }
}

function ScripLinkObj() {
    this.search = "";
    this.title = "";
    this.shortURL = "";
    this.copywrite = "";
    this.verses = "";
    this.results = "";
    this.searchMatch = "";

    // Ajax handles
    var bibleSearchCall = null;
    var ID = '';

    // Mouse over
    this.mOver = function(el) {
        if (ScripLink.verse_hover) {
            ID = el.getAttribute('id');
            this.ajaxLoad();
            var popup = document.getElementById("scripLinkPopUp");

            // Reset Timer
            if (ScripLink.hideDelayTimer) clearTimeout(ScripLink.hideDelayTimer);

            // Move Popup
            el.style.position = 'relative'; // Show
            el.appendChild(popup);

            // Remove the undeline
            // document.getElementById("scripLinkBible").style.textDecoration='none';

            // Top
            //alert(el.offsetHeight);
            var setTop = el.offsetHeight;

            // Left
            var setLeft = 0;
            if(el.offsetLeft > (document.documentElement.clientWidth-351)) { // Too close to right
                setLeft = setLeft-350+el.offsetWidth; // Popup is 350 wide
            }

            popup.style.top = setTop+'px';
            popup.style.left = setLeft+'px';
            popup.style.display = 'block'; // Show
        }
    }

    // Mouse Out
    this.mOut = function(el) {
        if (ScripLink.verse_hover) {
            if (ScripLink.hideDelayTimer) clearTimeout(ScripLink.hideDelayTimer);
            ScripLink.hideDelayTimer = setTimeout(function () {
                ScripLink.hideDelayTimer = null;
                document.getElementById('scripLinkPopUp').style.display = 'none';
            }, ScripLink.hideDelay);
        }
    }

    this.fillPopup = function() {
        // Show Loading
        document.getElementById('scripLinkLoading').style.display = 'block';

        // Fill elements
        scriply_replaceHtmlbyID('scripLinkSearchTitle', this.title);
        scriply_replaceHtmlbyID('scripLinkshortUrl', this.shortURL);
        document.getElementById('scripLinkshortUrl').setAttribute('href', this.shortURL);
        document.getElementById('scripLinkExpand').setAttribute('href', this.shortURL);
        scriply_replaceHtmlbyID('scripLinkBible', this.verses);

        // Hide Loading Div
        if (this.title != "") {
            document.getElementById('scripLinkLoading').style.display = 'none';
        }
    };

    // Bible Search
    this.ajaxLoad = function() {
        this.fillPopup();
        if (bibleSearchCall == null) {
            bibleSearchCall = 1; // End future calls
            var searchTerm = this.search.replace(":","."); // Clean Search
            //    jsoncallbackElem
            var obj=new JSONscriptRequest("http://scriply.info/api/bible/query?q="+searchTerm+"&app=ScripLink&translation="+ScripLink.translation+"&jsoncallbackElem="+ID+"&jsoncallback=ScripLink.ajaxCallback");
            obj.buildScriptTag(); // Build the script tag
            obj.addScriptTag(); // Execute (add) the script tag
        }
    };
}

function scriply_getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

function scriply_replaceHtmlbyID(id, html) {
    var replace=document.getElementById(id);
    if (replace)
    {
        try{
            replace.innerHTML=html;
        }
        catch(e){
            if (replace.childNodes[0]) {
                replace.childNodes[0].nodeValue=html;
            } else if (replace.value) {
                replace.value=html;
            }
        }
    }
}

// JSONscriptRequest -- a simple class for accessing Yahoo! Web Services
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// Constructor -- pass a REST request URL to the constructor
//

function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl;
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");

    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}

// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

ScripLink.linker();
