var TimeToFade = 500.0;

function fade(eid)
{
  var element = document.getElementById(eid);
  if(element == null)
    return;
   
  if(element.FadeState == null)
  {
    if(element.style.opacity == null
        || element.style.opacity == ''
        || element.style.opacity == '1')
    {
      element.FadeState = -2;
    }
    else
    {
      element.FadeState = 2;
    }
  }
   
  if(element.FadeState == 1 || element.FadeState == -1)
  {
    element.FadeState = element.FadeState == 1 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
  }
  else
  {
    element.FadeState = element.FadeState == 2 ? -1 : 1;
    element.FadeTimeLeft = TimeToFade;
    element.style.display = element.FadeState == 2
        ? 'none' : 'block';
    setTimeout("animateFade(" + new Date().getTime()
        + ",'" + eid + "')", 33);
  }
}

function animateFade(lastTick, eid)
{
  var curTick = new Date().getTime();
  var elapsedTicks = curTick - lastTick;
 
  var element = document.getElementById(eid);
 
  if(element.FadeTimeLeft <= elapsedTicks)
  {
    element.style.display = element.FadeState == 1
        ? 'block' : 'none';
    element.style.opacity = element.FadeState == 1
        ? '1' : '0';
    element.style.filter = 'alpha(opacity = '
        + (element.FadeState == 1 ? '100' : '0') + ')';
    element.FadeState = element.FadeState == 1 ? 2 : -2;
    return;
  }
 
  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/TimeToFade;
  if(element.FadeState == 1)
    newOpVal = 1 - newOpVal;

  newOpVal = newOpVal*1;
  element.style.opacity = newOpVal;
  element.style.filter =
      'alpha(opacity = ' + (newOpVal*100) + ')';
 
  setTimeout("animateFade(" + curTick
      + ",'" + eid + "')", 33);
}





/**
 * 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 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: false,

    /**
     * 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: 'nkjv'
};

/*************************************************************************
 * Code section - No need to modify the code below this point.
 *************************************************************************/

Scripturizer.translations = {
    'AMP':     ['45', 'Amplified Bible'],
    'ASV':     ['8"', 'American Standard Version'],
    'CEV':     ['46', 'Contemporary English Version'],
    'DARBY':   ['16', 'Darby Translation'],
    'ESV':     ['47', 'English Standard Version'],
    'HCSB':    ['77', 'Holman Christian Standard Bible'],
    'KJ21':    ['48', '21st Century King James Version'],
    'KJV':     ['9',  'King James Version'],
    'MSG':     ['65', 'The Message'],
    'NASB':    ['49', 'New American Standard Bible'],
    'NIRV':    ['76', 'New International Reader\'s Version'],
    'NIV':     ['31', 'New International Version'],
    'NIV-UK':  ['64', 'New International Version - UK'],
    'NKJV':    ['50', 'New King James Version'],
    'NLT':     ['51', 'New Living Translation'],
    'NLV':     ['74', 'New Life Version'],
    'WE':      ['73', 'Worldwide English (New Testament)'],
    'WNT':     ['53', 'Wycliffe New Testament'],
    'YLT':     ['15', 'Young\'s Literal Translation']
};

/**
 * 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?|Mark|Mrk|Luke|Lu?k|John|Jhn|Jo|'+
        'Acts?|Ac|Romans|Rom|Corinthians|Cor|Corin|Galatians|Gal|Galat|'+
        'Ephesians|Eph|Ephes|Philippians|Phili?|Colossians|Col|Colos|'+
        'Thessalonians|Thes?|Timothy|Tim|Titus|Tts|Tit|Philemon|Phil?|'+
        'Hebrews|Hebr?|James|Jam|Jms|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.onclick = Scripturizer.onclick;
            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 es = document.getElementsByTagName('script');
    var onload = 1; // Default to onload.
    for (i = 0; i < es.length; i ++) {
        var j, p;
        if ((j = es[i].src.indexOf('scripturizer.js')) >= 0) {
            p = __decodeQS(es[i].src);
            if (p.element)
                Scripturizer.element = p.element;
            if (p.new_window)
                Scripturizer.new_window = p.new_window == '1';
            if (p.version)
                Scripturizer.version = p.version;
            else if (p.onload)
                onload = parseInt(p.onload) || 1;
            break;
        }
    }
    return onload;
};

Scripturizer.onclick = function(ev) {
    ev = ev || window.event;
    var verse = this.childNodes[0].data;

    // Check whether 'ESVPopup' variable has been initialised, i.e.
    // 'esvpopup.js' has been loaded. If not, then we will fall back to
    // external linking to GNP.
    if (Scripturizer.version == 'esvpopup') {
        try {
            ESVPopup;
        } catch (e) {
            Scripturizer.version = 'esv';
        }
    }

    if (Scripturizer.version == 'esvpopup') {
        ESVPopup.onclick(ev, verse);
    } else {
        var link = verse.replace(/ /g, '+');
        link = link.replace(/[,&;]/g, '%2C');
        link = link.replace(/:]/g, '%3A');

        switch (Scripturizer.version) {
            case 'esv':
                link = 'http://www.gnpcb.org/esv/search/?go=Go&q=' + link;
                break;
            default:
                var bgver = Scripturizer.translations[
                    Scripturizer.version.toUpperCase()];
                link = 'http://www.biblegateway.com/passage/index.php?version='+
                    bgver[0]+'&search=' + link;
        }

        if (Scripturizer.new_window)
            window.open(link);
        else
            window.location.href = link;
    }

    return false;
};

Scripturizer.onmouseover = function(ev) {
    var title = this.childNodes[0].data;

    switch (Scripturizer.version) {
        case 'esv':
        case 'esvpopup':
            title += ' - English Standard Version Bible';
            break;
        default:
            var bgver = Scripturizer.translations[
                Scripturizer.version.toUpperCase()];
            title += ' - ' + bgver[1] + ' via Bible Gateway';
    }

    if (Scripturizer.version == 'esvpopup')
        title += ' (pop-up)';
    else if (Scripturizer.new_window)
        title += ' (new window)';

    this.setAttribute('title', title);
};

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;
                }
            }
        }
    }
}

var __onload = Scripturizer.init();
if (__onload > 0) {
    if (window.attachEvent) {
        window.attachEvent('onload', Scripturizer.doDocument);
    } else if (window.addEventListener) {
        window.addEventListener('load', Scripturizer.doDocument, false);
    } else {
        __onload = window.onload;
        window.onload = function() {
            Scripturizer.doDocument();
            __onload();
        };
    }
} else if (__onload < 0) {
    Scripturizer.doDocument();
}

/*

Title:		jShowOff: a jQuery Content Rotator Plugin
Author:		Erik Kallevig
Version:	0.1.2
Website:	http://ekallevig.com/jshowoff
License: 	Dual licensed under the MIT and GPL licenses.

jShowOff Options

animatePause :		whether to use 'Pause' animation text when pausing [boolean, defaults to true]
autoPlay :			whether to start playing immediately [boolean, defaults to true]
changeSpeed :		speed of transition [integer, milliseconds, defaults to 600]
controls :			whether to create & display controls (Play/Pause, Previous, Next) [boolean, defaults to true]
controlText :		custom text for controls [object, 'play', 'pause', 'previous' and 'next' properties]
cssClass :			custom class to add to .jshowoff wrapper [string]
effect :			transition effect [string: 'fade', 'slideLeft' or 'none', defaults to 'fade']
hoverPause :		whether to pause on hover [boolean, defaults to true]
links :				whether to create & display numeric links to each slide [boolean, defaults to true]
speed :				time each slide is shown [integer, milliseconds, defaults to 3000]

*/

(function($) {


	$.fn.jshowoff = function(settings) {

		// default global vars
		var config = {
			animatePause : true,
			autoPlay : true,
			changeSpeed : 600,
			controls : true,
			controlText : {
				play :		'Play',
				pause :		'Pause',
				next :		'Next',
				previous :	'Previous'
			},
			effect : 'fade',
			hoverPause : true,
			links : true,
			speed : 3000
		};
		
		// merge default global variables with custom variables, modifying 'config'
		if (settings) $.extend(true, config, settings);

		// make sure speed is at least 20ms longer than changeSpeed
		if (config.speed < (config.changeSpeed+20)) {
			alert('jShowOff: Make speed at least 20ms longer than changeSpeed; the fades aren\'t always right on time.');
			return this;
		};
		
		// create slideshow for each matching element invoked by .jshowoff()
		this.each(function(i) {
			
			// declare instance variables
			var $cont = $(this);
			var gallery = $(this).children().remove();
			var timer = '';
			var counter = 0;
			var preloadedImg = [];
			var howManyInstances = $('.jshowoff').length+1;
			var uniqueClass = 'jshowoff-'+howManyInstances;
			var cssClass = config.cssClass != undefined ? config.cssClass : '';
			
			
			// set up wrapper
			$cont.css('position','relative').wrap('<div class="jshowoff '+uniqueClass+'" />');
			var $wrap = $('.'+uniqueClass);
			$wrap.css('position','relative').addClass(cssClass);
			
			// add first slide to wrapper
			$(gallery[0]).clone().appendTo($cont);
			
			// preload slide images into memory
			preloadImg();
			
			// add controls
			if(config.controls){
				addControls();
				if(config.autoPlay==false){
					$('.'+uniqueClass+'-play').addClass(uniqueClass+'-paused jshowoff-paused').text(config.controlText.play);
				};
			};
			
			// add slide links
			if(config.links){
				addSlideLinks();
				$('.'+uniqueClass+'-slidelinks a').eq(0).addClass(uniqueClass+'-active jshowoff-active');
			};
			
			// pause slide rotation on hover
			if(config.hoverPause){ $cont.hover(
				function(){ if(isPlaying()) pause('hover'); },
				function(){ if(isPlaying()) play('hover'); }
			);};
			
			// determine autoPlay
			if(config.autoPlay && gallery.length>1) {
				timer = setInterval( function(){ play(); }, config.speed );
			};
			
			// display error message if no slides present
			if(gallery.length<1){
				$('.'+uniqueClass).append('<p>For jShowOff to work, the container element must have child elements.</p>');
			};

			
			// utility for loading slides
			function transitionTo(gallery,index) {
				
				var oldCounter = counter;
				if((counter >= gallery.length) || (index >= gallery.length)) { counter = 0; var e2b = true; }
				else if((counter < 0) || (index < 0)) { counter = gallery.length-1; var b2e = true; }
				else { counter = index; }


				if(config.effect=='slideLeft'){
					var newSlideDir, oldSlideDir;
					function slideDir(dir) {
						newSlideDir = dir=='right' ? 'left' : 'right';
						oldSlideDir = dir=='left' ? 'left' : 'right';					
					};
					

					counter >= oldCounter ? slideDir('left') : slideDir('right') ;

					$(gallery[counter]).clone().appendTo($cont).slideIt({direction:newSlideDir,changeSpeed:config.changeSpeed});
					if($cont.children().length>1){
						$cont.children().eq(0).css('position','absolute').slideIt({direction:oldSlideDir,showHide:'hide',changeSpeed:config.changeSpeed},function(){$(this).remove();});
					};
				} else if (config.effect=='fade') {
					$(gallery[counter]).clone().appendTo($cont).hide().fadeIn(config.changeSpeed,function(){if($.browser.msie)this.style.removeAttribute('filter');});
					if($cont.children().length>1){
						$cont.children().eq(0).css('position','absolute').fadeOut(config.changeSpeed,function(){$(this).remove();});
					};
				} else if (config.effect=='none') {
					$(gallery[counter]).clone().appendTo($cont);
					if($cont.children().length>1){
						$cont.children().eq(0).css('position','absolute').remove();
					};
				};
				
				// update active class on slide link
				if(config.links){
					$('.'+uniqueClass+'-active').removeClass(uniqueClass+'-active jshowoff-active');
					$('.'+uniqueClass+'-slidelinks a').eq(counter).addClass(uniqueClass+'-active jshowoff-active');
				};
			};
			
			// is the rotator currently in 'play' mode
			function isPlaying(){
				return $('.'+uniqueClass+'-play').hasClass('jshowoff-paused') ? false : true;
			};
			
			// start slide rotation on specified interval
			function play(src) {
				if(!isBusy()){
					counter++;
					transitionTo(gallery,counter);
					if(src=='hover' || !isPlaying()) {
						timer = setInterval(function(){ play(); },config.speed);
					}
					if(!isPlaying()){
						$('.'+uniqueClass+'-play').text(config.controlText.pause).removeClass('jshowoff-paused '+uniqueClass+'-paused');
					}
				};
			};
			
			// stop slide rotation
			function pause(src) {
				clearInterval(timer);
				if(!src || src=='playBtn') $('.'+uniqueClass+'-play').text(config.controlText.play).addClass('jshowoff-paused '+uniqueClass+'-paused');
				if(config.animatePause && src=='playBtn'){
					$('<p class="'+uniqueClass+'-pausetext jshowoff-pausetext">'+config.controlText.pause+'</p>').css({ fontSize:'62%', textAlign:'center', position:'absolute', top:'40%', lineHeight:'100%', width:'100%' }).appendTo($wrap).addClass(uniqueClass+'pauseText').animate({ fontSize:'600%', top:'30%', opacity:0 }, {duration:500,complete:function(){$(this).remove();}});
				}
			};
			
			// load the next slide
			function next() {
				goToAndPause(counter+1);
			};
		
			// load the previous slide
			function previous() {
				goToAndPause(counter-1);
			};
			
			// is the rotator in mid-transition
			function isBusy() {
				return $cont.children().length>1 ? true : false;
			};
			
			// load a specific slide
			function goToAndPause(index) {
				$cont.children().stop(true,true);
				if((counter != index) || ((counter == index) && isBusy())){
					if(isBusy()) $cont.children().eq(0).remove();
					transitionTo(gallery,index);
					pause();
				};
			};	

			// load images into memory
			function preloadImg() {
				$(gallery).each(function(i){
					$(this).find('img').each(function(i){
						preloadedImg[i] = $('<img>').attr('src',$(this).attr('src'));					
					});
				});
			};
				
			// generate and add play/pause, prev, next controls
			function addControls() {
				$wrap.append('<p class="jshowoff-controls '+uniqueClass+'-controls"><a class="jshowoff-play '+uniqueClass+'-play" href="#null">'+config.controlText.pause+'</a> <a class="jshowoff-prev '+uniqueClass+'-prev" href="#null">'+config.controlText.previous+'</a> <a class="jshowoff-next '+uniqueClass+'-next" href="#null">'+config.controlText.next+'</a></p>');
				$('.'+uniqueClass+'-controls a').each(function(){
						if($(this).hasClass('jshowoff-play')) $(this).click(function(){ isPlaying() ? pause('playBtn') : play(); return false; } );
						if($(this).hasClass('jshowoff-prev')) $(this).click(function(){ previous(); return false; });
						if($(this).hasClass('jshowoff-next')) $(this).click(function(){ next(); return false; });
	
				});
			};	

			// generate and add slide links
			function addSlideLinks() {
				$wrap.append('<p class="jshowoff-slidelinks '+uniqueClass+'-slidelinks"></p>');
				$.each(gallery, function(i, val) {
					var linktext = $(this).attr('title') != '' ? $(this).attr('title') : i+1;
					$('<a class="jshowoff-slidelink-'+i+' '+uniqueClass+'-slidelink-'+i+'" href="#null">'+linktext+'</a>').bind('click', {index:i}, function(e){ goToAndPause(e.data.index); return false; }).appendTo('.'+uniqueClass+'-slidelinks');
				});
			};		
	
	
		// end .each
		});
	
		return this;

	// end .jshowoff
	};

// end closure
})(jQuery);




(function($) {

	$.fn.slideIt = function(settings,callback) {
	
		// default global vars
		var config = {
			direction : 'left',
			showHide : 'show',
			changeSpeed : 1000
		};
		
		// merge default global variables with custom variables, modifying 'config'
		if (settings) $.extend(config, settings);
		
		this.each(function(i) {	
			$(this).css({left:'auto',right:'auto',top:'auto',bottom:'auto'});
			var measurement = (config.direction == 'left') || (config.direction == 'right') ? $(this).outerWidth() : $(this).outerHeight();
			var startStyle = {};
			startStyle['position'] = $(this).css('position') == 'static' ? 'relative' : $(this).css('position');
			startStyle[config.direction] = (config.showHide == 'show') ? '-'+measurement+'px' : 0;
			var endStyle = {};
			endStyle[config.direction] = config.showHide == 'show' ? 0 : '-'+measurement+'px';
			$(this).css(startStyle).animate(endStyle,config.changeSpeed,callback);
		// end .each
		});
	
		return this;
		
	// end .slideIt
	};

// end closure
})(jQuery);