$(document).ready(function() {
    //everything here is done only once the page is loaded.
    Globals.getTheme();
});
var ModalDiv = (function()
{

    var mouseY = 0, relY, offsetY, drag = false,
	oldW, oldH, oldF, bStyle, curW, curH, imgDescription,
	leftLimit = 1, // right bounding limit
	rightLimit = 1, //left bounding limit
	pgStart, pgEnd, //Page verse start and end IDs
	EditionID = 1, // edition of the bible.
	verseStart, // current verse start
	verseEnd, //current verse end
	bookName, //literal book name "John"
	pageSize = 20, //from the pulldown list
    //these have no bearing on the paging mechanism
	chStart, //beginning of the current chapter
	chEnd, //end of the current chapter
	refType,
	waiting = false; //waiting for a response from the server?

    //Internet Explorer fix
    if (!Array.prototype.forEach)
    {
        Array.prototype.forEach = function(fun /*, thisp*/)
        {
            var len = this.length;
            if (typeof fun != "function")
                throw new TypeError();
            var thisp = arguments[1];
            for (var i = 0; i < len; i++)
            {
                if (i in this) fun.call(thisp, this[i], i, this);
            }
        };
    }
    if (!String.prototype.trim)
    {
        String.prototype.trim = function()
        {
            return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        };
    }

    function o(o) { return document.getElementById(o) }

    function _addEvent(obj, type, fn)
    {
        if (obj.attachEvent)
        {
            obj['e' + type + fn] = fn;
            obj[type + fn] = function() { obj['e' + type + fn](window.event); }
            obj.attachEvent('on' + type, obj[type + fn]);
        }
        else
        {
            obj.addEventListener(type, fn, false);
        }
    }
    function _bibleParse(ref)
    {
        var original = ref;
        function RegList(arr)
        {
            var len = arr.length;
            function _exec(str)
            {
                var i = 0, item;
                for (i; i < len; i++)
                { //loop through every entry in the array
                    item = arr[i]
                    switch (typeof item[0])
                    {
                        case "string":
                            str = str.replace(new RegExp(item[0], "g"), item[1]);
                            break;
                        default: //assume its a regular expression
                            str = str.replace(item[0], item[1])
                            break;
                    }
                }
                return str;
            }
            return { exec: _exec }
        }
        //fix user input
        var bookFix = new RegList([
	        [/(?:\bgenesis\b|\bgen\b|\bgn\b)/gi, "{1}"], [/(?:\bexodus\b|\bexod\b|\bexo\b|\bex\b)/gi, "{2}"], [/(?:\bleviticus\b|\blev\b)/gi, "{3}"],
			[/(?:\bnumbers\b|\bnum\b)/gi, "{4}"], [/(?:\bdeuteronomy\b|\bdeut\b)/gi, "{5}"], [/(?:\bjoshua\b|\bjosh\b|\bjos\b)/gi, "{6}"],
			[/(?:\bjudges\b|\bjudg\b|\bjdg\b|\bjd\b)/gi, "{7}"], [/(?:\bruth\b)/gi, "{8}"], [/(?:\b1\s*samuel\b|\b1\s*sam\b|\b1\s*sa\b)/gi, "{9}"],
			[/(?:\b2\s*samuel\b|\b2\s*sam\b|\b2\s*sa\b)/gi, "{10}"], [/(?:\bezra\b)/gi, "{15}"], [/(?:\bjob\b)/gi, "{18}"],
			[/(?:\brevelation\b|\brev\b|\bre\b)/gi, "{66}"], [/(?:\b1\s*kings\b|\b1\s*kgs\b|\b1\s*ki\b)/gi, "{11}"],
			[/(?:\b2\s*kings\b|\b2\s*kgs\b|\b2\s*ki\b)/gi, "{12}"], [/(?:\b1\s*chronicles\b|\b1\s*chr\b|\b1\s*chro\b|\b1\s*ch\b)/gi, "{13}"],
			[/(?:\b2\s*chronicles\b|\b2\s*chr\b|\b2\s*chro\b|\b1\s*ch\b)/gi, "{14}"], [/(?:\bnehemiah\b|\bneh\b)/gi, "{16}"],
			[/(?:\besther\b|\besth\b|\best\b)/gi, "{17}"], [/(?:\bpsalms\b|\bps\b|\bpsa\b)/gi, "{19}"], [/(?:\bproverbs\b|\bpr\b|pro\b)/gi, "{20}"],
			[/(?:\becclesiastes\b|\beccl\b|\becc\b)/gi, "{21}"], [/(?:\bsong\s*of\s*songs\b|\bsong\b|\bsng\b|\bsos\b|\bsong\s*of*solomon\b)/gi, "{22}"],
	        [/(?:\bisaiah\b|\bisa\b|\bis\b)/gi, "{23}"], [/(?:\bjeremiah\b|\bjer\b)/gi, "{24}"], [/(?:\blamentations\b|\blam\b)/gi, "{25}"],
			[/(?:\bezekiel\b|\bezek\b|\beze\b|\bezk\b)/gi, "{26}"], [/(?:\bdaniel\b|\bdan\b)/gi, "{27}"], [/(?:\bhosea\b|\bhos\b)/gi, "{28}"],
			[/(?:\bjoel\b)/gi, "{29}"], [/(?:\bamos\b)/gi, "{30}"], [/(?:\bobadiah\b|\bobad\b|\boba\b)/gi, "{31}"],
			[/(?:\bjonah\b|\bjon\b|\bjnh\b)/gi, "{32}"], [/(?:\bmicah\b|\bmic\b)/gi, "{33}"], [/(?:\bnahum\b|\bnah\b)/gi, "{34}"],
			[/(?:\bhabakkuk\b|\bhab\b|\bhbk\b)/gi, "{35}"], [/(?:\bzephaniah\b|\bzeph\b|\bzep\b)/gi, "{36}"],
			[/(?:\bhaggai\b|\bhagg\b|\bhag\b|\bhg\b)/gi, "{37}"], [/(?:\bzechariah\b|\bzech\b|\bzec\b)/gi, "{38}"], [/(?:\bmalachi\b|\bmal\b)/gi, "{39}"],
			[/(?:\bmatthew\b|\bmatt\b|\bmt\b)/gi, "{40}"], [/(?:\bmark\b|\bmk\b|\bmar\b)/gi, "{41}"], [/(?:\bluke\b|\blk\b|\bluk\b)/gi, "{42}"],
	        [/(?:\bacts\b|\bact\b|\bac\b)/gi, "{44}"], [/(?:\bromans\b|\brom\b)/gi, "{45}"], [/(?:\b1\s*corinthians\b|\b1\s*cor\b|\b1\s*co\b)/gi, "{46}"],
			[/(?:\b2\s*corinthians\b|\b2\s*cor\b|\b2\s*co\b)/gi, "{47}"], [/(?:\bgalatians\b|\bgal\b)/gi, "{48}"], [/(?:\bephesians\b|\beph\b)/gi, "{49}"],
			[/(?:\bphilippians\b|\bphil\b|\bphp\b)/gi, "{50}"], [/(?:\bcolossians\b|\bcol\b)/gi, "{51}"], [/(?:\b1\s*thessalonians\b|\b1\s*th\b|\b1\s*thes\b)/gi, "{52}"],
			[/(?:\b2\s*thessalonians\b|\b2\s*th\b|\b2\s*thes\b)/gi, "{53}"], [/(?:\b1\s*timothy\b|\b1\s*tim\b|\b1\s*ti\b)/gi, "{54}"],
			[/(?:\b2\s*timothy\b|\b2\s*tim\b|\b2\s*ti\b)/gi, "{55}"], [/(?:\btitus\b|\btit\b)/gi, "{56}"], [/(?:\bphilemon\b|\bphlm\b|\bphile\b|\bphm\b|\bphi\b)/gi, "{57}"],
			[/(?:\bhebrews\b|\bheb\b|\bhe\b)/gi, "{58}"], [/(?:\bjames\b|\bjas\b|\bjam\b|\bja\b)/gi, "{59}"], [/(?:\b1\s*peter\b|\b1\s*pet\b|\b1\s*pe\b)/gi, "{60}"],
	        [/(?:\b2\s*peter\b|\b2\s*pet\b|\b2\s*pe\b)/gi, "{61}"], [/(?:\b1\s*john\b|\b1\s*jn\b)/gi, "{62}"], [/(?:\b2\s*john\b|\b2\s*jn\b)/gi, "{63}"],
			[/(?:\b3\s*john\b|\b3\s*jn\b)/gi, "{64}"], [/(?:\bjohn\b|\bjn\b)/gi, "{43}"], [/(?:\bjude\b)/gi, "{65}"]
		])
        var BookList = [, //index 0 empty on purpose
		    "Genesis", "Exodus", "Leviticus", "Numbers", "Deuteronomy", "Joshua", "Judges", "Ruth", "1 Samuel", "2 Samuel", "1 Kings", "2 Kings", "1 Chronicles",
		    "2 Chronicles", "Ezra", "Nehemiah", "Esther", "Job", "Psalms", "Proverbs", "Ecclesiastes", "Song of Solomon", "Isaiah", "Jeremiah", "Lamentations",
		    "Ezekiel", "Daniel", "Hosea", "Joel", "Amos", "Obadiah", "Jonah", "Micah", "Nahum", "Habakkuk", "Zephaniah", "Haggai", "Zechariah", "Malachi", "Matthew",
            "Mark", "Luke", "John", "Acts", "Romans", "1 Corinthians", "2 Corinthians", "Galatians", "Ephesians", "Philippians", "Colossians", "1 Thessalonians",
            "2 Thessalonians", "1 Timothy", "2 Timothy", "Titus", "Philemon", "Hebrews", "James", "1 Peter", "2 Peter", "1 John", "2 John", "3 John", "Jude", "Revelation"
        ]
        //Replace "Ruth 1 1" with "Ruth 1:1",remove spaces,Replace "Ruth 1.1" with "Ruth 1:1",put a booknumber after every comma, remove any book numbers side by side
        //{B}C1:V1-C2:V2 --> ["B.C1.V1","B.C2.V2"]
        //{B}C1:V1-V2 --> ["B.C1.V1","B.C1.V2"]
        //{B}C1-C2:V1 --> ["B.C1.V1","B.C2.V1"]
        //{B}C1:V1 --> ["B.C1.V1","B.C1.V1"]
        //{B}C1-C2 ---> ["B.C1.1","B.C2.End"]
        //{B}C1 --> ["B.C1.1","B.C1.End"]
        //{B} --> ["B.1.1","B.End.End"]
        var refFix = new RegList([
			[";", ","], [/\}(\d+)\s*(\d+)/g, "}$1:$2"], [/\s*/g, ""], [/(\d+)\.(\d+)/g, "$1:$2"],
			[/(\{\d+\})([^{]+)/g, function(match, bookNum, contents) { return (bookNum + contents.replace(/\,/g, "," + bookNum)) } ], [/\d+\}\{/, ""],
			[/\{(\d+)\}(\d+)\:(\d+)\-(\d+)\:(\d+)/g, function(match, $1, $2, $3, $4, $5)
			{
			    refType = "range";
			    return "[\"" + BookList[$1] + "." + $2 + "." + $3 + "\",\"" + BookList[$1] + "." + $4 + "." + $5 + "\"]";
			} ],
			[/\{(\d+)\}(\d+)\:(\d+)\-(\d+)/g, function(match, $1, $2, $3, $4)
			{
			    refType = "range";
			    return "[\"" + BookList[$1] + "." + $2 + "." + $3 + "\",\"" + BookList[$1] + "." + $2 + "." + $4 + "\"]";
			} ],
			[/\{(\d+)\}(\d+)\-(\d+)\:(\d+)/g, function(match, $1, $2, $3, $4)
			{
			    refType = "range";
			    return "[\"" + BookList[$1] + "." + $2 + "." + $4 + "\",\"" + BookList[$1] + "." + $3 + "." + $4 + "\"]";
			} ],
			[/\{(\d+)\}(\d+)\:(\d+)/g, function(match, $1, $2, $3)
			{
			    refType = "single";
			    return "[\"" + BookList[$1] + "." + $2 + "." + $3 + "\",\"" + BookList[$1] + "." + $2 + "." + $3 + "\"]";
			} ],
			[/\{(\d+)\}(\d+)\-(\d+)/g, function(match, $1, $2, $3)
			{
			    refType = "range";
			    return "[\"" + BookList[$1] + "." + $2 + ".1\",\"" + BookList[$1] + "." + $3 + ".End\"]";
			} ],
			[/\{(\d+)\}(\d+)/g, function(match, $1, $2)
			{
			    refType = "range";
			    return "[\"" + BookList[$1] + "." + $2 + ".1\",\"" + BookList[$1] + "." + $2 + ".End\"]";
			} ],
			[/\{(\d+)\}/g, function(match, $1)
			{
			    refType = "range";
			    return "[\"" + BookList[$1] + ".1.1\",\"" + BookList[$1] + ".End.End\"]";
			} ]
		])
        ref = bookFix.exec(ref) //normalize booknames
        ref = refFix.exec(ref) //normalize the references
        ref = "[" + ref + "]";
        try
        {
            ref = eval("(" + ref + ")")
            if (!ref[0])
            {
                alert("Unrecognized reference: " + original);
                return false;
            }
        } catch (e)
        {
            alert("Unrecognized reference: " + original);
            return false;
        }
        if (ref.length > 1)
        {
            alert("Please enter a single reference");
            return false;
        }
        return ref[0]; //only the first bible reference
        //return ref
    }

    function _content()
    {
        if (!o("modalContent"))
        {
            throw "ModalDiv.create() must be called before ModalDiv.content()";
        }
        return o("modalContent");
    }

    function _create(x, y, w, h)
    {
        y = (y || 20) + "px";
        w = (w || 913) + "px";
        h = (h || 735) + "px";
        if (!o("modalDiv"))
        {
            var modal = document.createElement("div");
            //Internet Explorer is buggy with setAttribute() so we have to do it the hard way
            modal.id = "modalDiv";
            modal.style.position = "absolute";
            modal.style.top = "0px";
            modal.style.left = "0px";
            modal.style.bottom = "0px";
            modal.style.right = "0px";
            modal.style.display = "none";
            modal.style.zIndex = 25;
            var modalWindow = document.createElement("div");
            modalWindow.id = "modalWindow";
            modalWindow.style.position = "relative";
            modalWindow.style.width = w || "913px";
            modalWindow.style.height = h || "300px";
            modalWindow.style.minHeight = "300px";
            modalWindow.style.maxHeight = "90%";
            modalWindow.style.marginLeft = "auto";
            modalWindow.style.marginRight = "auto";
            modalWindow.style.top = y;
            modalWindow.style.overflow = "hidden";
            modalWindow.innerHTML = [
				"<div id='modalHeader' style='display:block;margin:0px;width:100%;top:0px;z-index:4'>",
					"<input type='button' value='' style='visibility:hidden' id='biblePrev1' class='biblePrev' onclick='ModalDiv.pageLeft()'/>",
					"<input type='button' value='' style='visibility:hidden' id='bibleNext1' class='bibleNext' onclick='ModalDiv.pageRight()'/>",
					"<div id='biblePassageLookup'>QuickPassage Lookup ",
						"<form style='display:inline' action='#' method='POST' onsubmit='return ModalDiv.findPassage(this.firstChild,this.firstChild.value)'>",
							"<input id='passage' name='passage' type='text' value=''/>",
							"<input type='button' id='bibleGo' onclick='ModalDiv.findPassage(this.previousSibling,this.previousSibling.value)' /> ",
							"&nbsp;&nbsp;<select id='bibleEdition' onchange='ModalDiv.updateEdition(this.options[this.selectedIndex].value)'>",
								"<option value='1'>KJV</option>",
							"</select>",
						"</form>",
						"&nbsp;&nbsp;<select id='biblePageSize' onchange='ModalDiv.updateSize(this.options[this.selectedIndex].value)'>",
							"<option value ='1'>1</option>",
							"<option value ='2'>2</option>",
							"<option value ='3'>3</option>",
							"<option value ='4'>4</option>",
							"<option value ='5'>5</option>",
							"<option value ='6'>6</option>",
							"<option value ='7'>7</option>",
							"<option value ='8'>8</option>",
							"<option value ='9'>9</option>",
							"<option value ='10'>10</option>",
							"<option value ='15'>15</option>",
							"<option value ='20' selected='selected'>20</option>",
							"<option value ='25'>25</option>",
							"<option value ='30'>30</option>",
							"<option value ='35'>35</option>",
							"<option value ='40'>40</option>",
							"<option value ='45'>45</option>",
							"<option value ='50'>50</option>",
						"</select>",
						"&nbsp;&nbsp;Results per page",
					"</div>",
					"<input type='button' value='' class='bibleClose' onclick='ModalDiv.hide()' />",
				"</div>",
				"<div id='modalContent' style='display:block;overflow-x:hidden;overflow-y:auto;z-index:1'></div>",
				"<div id='modalFooter' style='display:block;bottom:0px;left:0px;margin:0px;width:100%;'>",
					"<input type='button' value='' style='visibility:hidden' id='biblePrev2' class='biblePrev' onclick='ModalDiv.pageLeft()'/>",
					"<input type='button' value='' style='visibility:hidden' id='bibleNext2' class='bibleNext' onclick='ModalDiv.pageRight()'/>",
				"</div>"
			].join("");
            modal.appendChild(modalWindow);
            document.body.appendChild(modal);
        }
    }

    function _getFooter()
    {
        return o("modalFooter");
    }

    function _getHeader()
    {
        return o("modalHeader");
    }

    function _getURLArgument(name)
    {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
        {
            return "";
        }
        else
        {
            return results[1];
        }
    }

    function _destroy()
    {
        document.body.removeChild(o("modalDiv"));
    }
    function _findPassage(el, ref)
    {
        if (ref.trim() !== "")
        {
            ref = _bibleParse(ref);
            if (!ref)
            {
                o("passage").focus();
                return false
            }
            //EditionID = 1;
            verseStart = parseInt(ref[0].split(".")[2], 10) || 1;
            verseEnd = parseInt(ref[1].split(".")[2], 10) || 0;
            bookName = ref[0].split(".")[0];
            chStart = parseInt(ref[0].split(".")[1], 10) || 1;
            chEnd = parseInt(ref[1].split(".")[1], 10) || 0;
            _updateContent(true);
            el.value = "";
        }
        return false;
    }
    function _hide()
    {
        if (o("modalDiv"))
        {
            o("modalDiv").style.display = "none";
            bStyle.height = oldH;
            bStyle.width = oldW;
            document.documentElement.style.overflow = oldF;
        }
        if ($.browser.msie && $.browser.version == '6.0')
        {
            $('select').show();
        }
    }

    function _closePopup()
    {
        if ($.browser.msie && $.browser.version == '6.0')
        {
            $('select').hide();
            $('#modalWindow select').show();
        }

        var t = o("popupModal")
        t.parentNode.removeChild(t);
    }

    function _popup(flag, str)
    {
        //is the popup going to contain and image or text content?
        var img = (str.indexOf("'img'") > -1) ? true : false;

        if (!o("popupModal"))
        {
            var modal = document.createElement("div");
            //Internet Explorer is buggy with setAttribute() so we have to do it the hard way
            modal.id = "popupModal";
            modal.style.position = "relative";
            modal.style.top = "0px";
            modal.style.left = "0px";
            modal.style.bottom = "0px";
            modal.style.right = "0px";
            modal.style.zIndex = 50;
            var smallModal = document.createElement("div")
            var smallStyle = smallModal.style;
            smallModal.id = "popupDiv";
            smallStyle.position = "absolute";
            smallStyle.visibility = "visible";
            modal.appendChild(smallModal);
            document.body.appendChild(modal);
        }
        o("popupModal").style.display = "block";

        if ($.browser.msie && $.browser.version == '6.0')
        {
            $('select').hide();
            $('#popupDiv select').show();
        }

        o("popupDiv").innerHTML = "<img id='showPopDescription' style='display:none' src='/App_Themes/Bible/images/btn_resourceInfo.png' alt='Show Description' onclick='ModalDiv.showDescription()'/><img id='popClose' src='/app_themes/" + Globals.theme() + "/images/btn_resourceClose.png' alt='Close' onclick='ModalDiv.closePopup()'/>Loading your request..."

        $.ajax({
            type: 'POST',
            url: (flag) ? "/BibleServices.asmx/FetchResourceByContentID" : "/BibleServices.asmx/FetchRelatedLists",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: str,
            success: function(d)
            {
                var txt = d.d;
                // Persisted
                txt.Body = "<img id='showPopDescription' src='/App_Themes/Bible/images/btn_resourceInfo.png' style='display:none' alt='Show Description' onclick='ModalDiv.showDescription()'/><img id='popClose' src='/app_themes/" + Globals.theme() + "/images/btn_resourceClose.png' onclick='ModalDiv.closePopup()'/><div id='popContent'>" + txt.Body + "</div>";
                $(o("popupDiv")).empty().append(txt.Body);
                imgDescription = txt.Description;

                if (!img)
                {
                    if (o("popupDiv").offsetHeight > screen.availHeight * .6)
                    {
                        o("popupDiv").style.height = screen.availHeight * .6 + "px";
                    }
                    o("popupDiv").style.top = ((o("popupModal").offsetHeight) - (o("popupDiv").offsetHeight)) / 2 + "px";
                    o("popupDiv").style.left = ((o("popupModal").offsetWidth) - (o("popupDiv").offsetWidth)) / 2 + "px";
                    o("popupDiv").style.overflow = "auto";
                    _resize();
                    smallStyle.visibility = o("popupModal").style.visibility = "visible";
                }
                else
                {
                    var popImg = o("popupDiv").getElementsByTagName("img")[0];
                    _resize();
                    (imgDescription.trim() !== "") ?
                        o("showPopDescription").style.display = "" :
                        o("showPopDescription").style.display = "none";


                    if (popImg.complete)
                    {
                        o("popupDiv").style.visibility = o("popupModal").style.visibility = "visible";
                        o("popContent").style.position = "relative";
                        o("popContent").style.overflow = "hidden";
                        _resize()
                    } else
                    {
                        popImg.onload = function()
                        {
                            o("popupDiv").style.visibility = o("popupModal").style.visibility = "visible";
                            o("popContent").style.position = "relative";
                            o("popContent").style.overflow = "hidden";
                            _resize()
                        }
                    }
                }
            },
            error: function(xhr, msg)
            {
                console.log('error');
                console.log(xhr);
                console.log(msg);
            }
        });
    }

    function _pageLeft()
    {
        if (!waiting)
        {
            pgStart = parseInt(pgStart, 10);
            pgEnd = parseInt(pgEnd, 10);
            pageSize = parseInt(pageSize, 10);
            leftLimit = parseInt(leftLimit, 10);
            leftLimit = parseInt(leftLimit, 10);

            pgEnd = pgStart - 1;
            //left bounding limit
            if (pgStart - pageSize > leftLimit)
            {
                pgStart -= pageSize;
            }
            else
            {
                pgStart = leftLimit;
            }
            _updateContent();
        }
    }
    function _pageRight()
    {
        if (!waiting)
        {
            pgStart = parseInt(pgStart, 10);
            pgEnd = parseInt(pgEnd, 10);
            pageSize = parseInt(pageSize, 10);
            leftLimit = parseInt(leftLimit, 10);
            rightLimit = parseInt(rightLimit, 10);

            pgStart = parseInt(pgEnd, 10) + 1;
            //right bounding limit
            if (pgEnd + pageSize < rightLimit)
            {
                pgEnd += pageSize;
            }
            else
            {
                pgEnd = rightLimit;
            }
            _updateContent();
        }
    }
    function _request(str, init)
    {
        waiting = true;
        XHR({
            callBack: function(txt)
            {
                var json = eval("(" + txt + ")");
                if (init)
                {//if this is the first request, set the bounding limits and remember the current page size
                    /*if(refType == "single"){
                    leftLimit = json.Edition.FirstVerseID;
                    rightLimit = json.Edition.LastVerseID;
                    pgStart = json.StartBookmark.VerseID;
                    pgEnd = pgStart + pageSize-1;
                    }
                    else{
                    leftLimit = json.StartBookmark.VerseID;
                    rightLimit = json.EndBookmark.VerseID;
                    pgStart = leftLimit
                    pgEnd = leftLimit + pageSize-1;
                    }*/
                    leftLimit = json.Edition.FirstVerseID;
                    rightLimit = json.Edition.LastVerseID;
                    pgStart = json.StartBookmark.VerseID;
                    pgEnd = pgStart + pageSize - 1;
                }

                //show pageLeft/Right
                if (rightLimit > pgEnd)
                { //show the nextbutton if there is more content
                    o('bibleNext1').style.visibility = o('bibleNext2').style.visibility = "visible";
                }
                else
                {
                    o('bibleNext1').style.visibility = o('bibleNext2').style.visibility = "hidden";
                }

                if (leftLimit < pgStart)
                { //show previous button if there is more content
                    o('biblePrev1').style.visibility = o('biblePrev2').style.visibility = "visible";
                }
                else
                {
                    o('biblePrev1').style.visibility = o('biblePrev2').style.visibility = "hidden";
                }

                //json.PassageText = '<div><a href="#"><img src="/App_Themes/bible/images/ico_audio.png" alt="Audio" border="0" class="resourceIcon" /></a> <a href="#"><img src="/App_Themes/bible/images/ico_video.png" alt="Video" border="0" class="resourceIcon" /></a> <a href="#"><img src="/App_Themes/bible/images/ico_article.png" alt="Article" border="0" class="resourceIcon" /></a></div>' + json.PassageText
                o('modalContent').innerHTML = json.PassageText

                waiting = false;
            },
            url: (init) ? "/BibleServices.asmx/FetchPassageByRangeAndSize" : "/BibleServices.asmx/FetchPassageByRange",
            method: "POST",
            data: str,
            requestHeaders: [
				["Content-type", "application/json; charset=utf-8"],
				["Content-length", str.length],
				["Connection", "close"]
			]
        })
    }
    function _resize()
    {
        if (o("modalContent"))
        {
            $("#modalDiv").css("top", $(window).scrollTop() + "px");
            $("#modalDiv").css("height", $(window).height() + "px");

            var mW = $("#modalWindow"), mH = $("#modalHeader"), mC = $("#modalContent"), mF = $("#modalFooter");

            mW.css("height", ($(window).height() - $('#modalWindow').position().top * 2) + "px");

            var iContentHeight = mW.outerHeight({ margin: true });
            iContentHeight -= mH.outerHeight({ margin: true }) + mF.outerHeight({ margin: true }) + (mC.outerHeight({ margin: true }) - mC.height());

            mC.css("height", iContentHeight + "px");
        }

        if (o("popupDiv"))
        {
            $('#popupModal').css('top', $(window).scrollTop() + 'px');
            $('#popupModal').css('height', $(window).height() + 'px');

            var pd = o("popupDiv");
            var pm = o("popupModal");
            var pc = o("popContent")
            var img = o("popContent").getElementsByTagName("img")[0];
            var w = pm.offsetWidth, h = pm.offsetHeight
            pd.style.width = pd.style.height = "";

            if (img)
            {
                pc.style.overflow = "hidden"

                //center
                img.style.marginLeft = "auto"
                img.style.marginRight = "auto"
                img.style.display = "block";

                if (img.offsetHeight > pm.offsetHeight * .6)
                {
                    img.style.height = pm.offsetHeight * .6 + "px"
                }
                else
                {
                    img.style.height = "auto";
                    if (img.offsetHeight > pm.offsetHeight * .6)
                    {
                        img.style.height = pm.offsetHeight * .6 + "px"
                    }
                }

                if (img.offsetWidth > pm.offsetWidth * .6)
                {
                    img.style.width = pm.offsetWidth * .6 + "px";
                }
                else
                {
                    img.style.width = "auto";
                    if (img.offsetWidth > pm.offsetWidth * .6)
                    {
                        img.style.width = pm.offsetWidth * .6 + "px";
                    }
                }
            }
            else
            {
                pc.style.overflow = "auto"
                pd.style.width = pm.offsetWidth * .6 + "px";
                pd.style.height = pm.offsetHeight * .6 + "px";
            }

            //browser lag...
            window.setTimeout((function(pd, h, w)
            {
                return function()
                {
                    pd.style.top = h / 2 - pd.offsetHeight / 2 + "px";
                    pd.style.left = w / 2 - pd.offsetWidth / 2 + "px";
                }
            })(pd, h, w), 200)
        }

        if (o("ModalDescription"))
        {
            var md = o("ModalDescription");
            md.style.overflow = "auto";

            if (md.offsetHeight > img.offsetHeight)
                md.style.height = img.offsetHeight * .2 + "px";
            if (md.offsetWidth > img.offsetWidth)
                md.style.width = img.offsetWidth * .6 + "px";

            md.style.top = img.offsetHeight / 2 - md.offsetHeight / 2 + "px";
            md.style.left = img.offsetWidth / 2 - md.offsetWidth / 2 + "px";
        }

    }

    function _show(obj)
    {
        waiting = false;
        if ($.browser.msie && $.browser.version == '6.0')
        {
            $('select').hide();
            $('#modalWindow select').show();
        }
        if (o("modalDiv"))
        {
            bStyle = document.body.style;
            //IE6 Fix
            oldH = bStyle.height;
            oldW = bStyle.width;
            oldF = document.documentElement.style.overflow;
            bStyle.width = "100%";
            bStyle.height = "100%";
            document.documentElement.style.overflow = "hidden"
            if (obj)
            {
                //update vars
                EditionID = 1;
                verseStart = obj.vbegin || 1;
                verseEnd = obj.vend || 0;    // we hope the end will always get specified, but if not, we set to 0
                bookName = obj.book.replace(/\'/g, "");
                chStart = obj.cbegin || 1;
                chEnd = obj.cend || 0;      // we hope the end will always get specified, but if not, we set to 0
                _updateContent(true);
            }
            o("modalDiv").style.display = "block";
            _resize(); //check and fix offsets
            return true;
        }
        _create(); //create with defaults
        _show(obj);
    }

    function _showDescription()
    {
        var descPop, description = "";

        if (!o("ModalDescription"))
        {
            descPop = document.createElement("DIV");
            descPop.id = "ModalDescription";
            var ds = descPop.style
            ds.position = "absolute";
            ds.display = "none";
            ds.backgroundColor = "#F3EDDD";
            ds.border = "5px solid #281E13";
            ds.padding = "1em";
            ds.width = "80%";
            ds.height = "80%";
            ds.overflow = "auto";

            o("popContent").appendChild(descPop)
        }
        else
            descPop = o("ModalDescription");

        descPop.innerHTML = imgDescription
        descPop.style.display = "block";
        _resize();
    }
    function _updateContent(init)
    {
        var objParse;
        if (init)
        { //initial request?
            objParse = "{" +
				"'StartingBookmark':{" +
					"'EditionID':" + EditionID + "," +
					"'BookShortName':'" + bookName + "'," +
					"'ChapterNbr':" + chStart + "," +
					"'VerseNbr':" + verseStart +
				"}," +
				"'EndingBookmark':{" +
					"'EditionID':" + EditionID + "," +
					"'BookShortName':'" + bookName + "'," +
					"'ChapterNbr':" + chEnd + "," +
					"'VerseNbr':" + verseEnd +
				"}," +
				"'VerseCount':" + pageSize +
			"}";
        }
        else
        {
            objParse = "{" +
				"'StartingBookmark':{" +
					"'EditionID':" + EditionID + "," +
					"'VerseID':" + pgStart +
				"}," +
				"'EndingBookmark':{" +
					"'EditionID':" + EditionID + "," +
					"'VerseID':" + pgEnd +
				"}" +
			"}";
        }
        _request(objParse, init);
        return false;
    }

    function _updateEdition(n)
    {
        EditionID = parseInt(n, 10);
    }

    function _updateSize(n)
    {
        pageSize = n;
        pgEnd = parseInt(pgStart, 10) + parseInt(n, 10) - 1;
        if (refType != "single")
        {
            if (pgEnd > rightLimit)
            {
                pgEnd = rightLimit;
            }
        }
        _updateContent();
    }

    function XHR(o)
    {
        //IE6 does not support XMLHttpRequest. "MSXML2.XMLHTTP.3.0" comes with IE6
        var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");

        xhr.onreadystatechange = function()
        {
            if (xhr.readyState === 4)
            {
                if (xhr.status === 200)
                {
                    if (o.callBack)
                    {
                        o.callBack(xhr["response" + (o.responseType || "Text")]);
                    }
                    else
                    {
                        return xhr["response" + (o.responseType || "Text")];
                    }
                }
                else
                {
                    alert("AJAX Error: " + xhr.responseText);
                }
            }
        };
        xhr.open((o.method || "GET"), (o.url || document.location), (o.async || true));
        if (o.requestHeaders)
        {//headers must be set after an open call
            for (var i = 0; i < o.requestHeaders.length; i++)
            {
                xhr.setRequestHeader(o.requestHeaders[i][0], o.requestHeaders[i][1]);
            }
        }
        xhr.send(o.data || null);
    }
    //check for url arguments
    _addEvent(window, "load", function()
    {
        if (_getURLArgument("book") !== "")
        { // book is required
            _show({
                "book": "'" + _getURLArgument("book") + "'",
                "cbegin": _getURLArgument("cbegin"),
                "cend": _getURLArgument("cend"),
                "vbegin": _getURLArgument("vbegin"),
                "vend": _getURLArgument("vend")
            })
        }
    });
    //listen for page resizing
    _addEvent(window, "resize", _resize)
    _addEvent(document, "click", function(e)
    {
        e = e || window.event;
        var tg = e.target || e.srcElement;

        if (tg.id !== "showPopDescription")
        {
            if (o("ModalDescription"))
            {
                o("ModalDescription").innerHTML = "";
                o("ModalDescription").style.display = "none";
            }
        }
    })

    document.onmousedown = document.onmousemove = document.ondragstart = window.oncontextmenu = document.oncontextmenu = function(e)
    {
        e = e || window.event;
        var tg = e.target || e.srcElement;
        var type = (tg.title && tg.title == "protected") ? false : true;
        if (!type)
        {
            if (e.preventDefault) { e.preventDefault() };
            return false;
        }
    }

    return {
        closePopup: _closePopup, //close the sub popup
        create: _create,
        destroy: _destroy,
        findPassage: _findPassage, //the search box
        getFooter: _getFooter,
        getHeader: _getHeader,
        getContent: _content,
        hide: _hide,
        /*
        flag 0   -   /BibleServices.asmx/FetchRelatedLists
        "{'type':"img|comm|vlist|alist|article",'StartingBookmark':{'EditionID':#,'VerseID':#},'EndingBookmark':{'EditionID':#,'VerseID':#}}
        flag 1    -   /BibleServices.asmx/FetchResourceByContentID
        "{'ContentID' : #}"
        */
        popup: _popup, //the small subpopup
        pageLeft: _pageLeft,
        pageRight: _pageRight,
        resize: _resize,
        show: _show, //{book:'John',cbegin:3,cend:3,vbegin:16,vend:16}
        showDescription: _showDescription,
        updateEdition: _updateEdition,
        updateSize: _updateSize
    }
})();
