﻿
$(document).ready(function() {
	// set minimum height for document
	var diff = $(document).height() - $('body').height();
	if (diff > 0) {
		$('#view_content').css('min-height', $('#view_content').height() + diff);
	}
	

	// Set minimum widths for submenus
	$('#top_navigation li.mainitem').each(function() {
		var minWidth = $(this).width();	
/*		var subWidth = $(this).children('.submenu').width();
		
		if (mainWidth > subWidth) {
			$(this).children('.submenu').width(mainWidth);
		} else if (subWith > mainWidth) {
			$(this).width(subWidth);
		}
*/

		$(this).children('.submenu').each(function() {
			if ($(this).width() < minWidth) {
				$(this).width(minWidth);
			}
		});

	});


	$('#login_button').fancybox({
		'scrolling': 'no',
		'titleShow': false,
		'onComplete' : function() {
			$('#fancybox-content #LoginForm_username').focus();
		}
	});


	if ($('#banner.slider .feature').length > 1) {
		slideshow_interval = window.setInterval(slideSwitch, 8000);

		$('#banner #dots .dot').click(function(ev) {
			$('#banner #dots .dot').removeClass('selected')
			$(this).addClass('selected');

			var box_id = $(this).attr('href');
			$('#banner .feature:visible').fadeOut('normal', function() {
				$('#banner ' + box_id).fadeIn('normal');
			});
			
			if (typeof ev.originalEvent != "undefined") {
				window.clearInterval(slideshow_interval);
				slideshow_interval = window.setInterval(slideSwitch, 8000);
			}
			return false;
		});
	}	

	$('#search p').click(function() {
		$('#search #q').focus();
	});

});

function slideSwitch() {
	var active = $('#banner #dots .selected');
	if (active.length == 0) {
		active = $('#banner #dots .dot:eq(0)');
	}

	var next =  active.next().length ? active.next() : $('#banner #dots .dot:eq(0)');
	next.addClass('selected');
	
	next.click();
    active.removeClass('selected');
}


function hoverMenu(mainItem, subItem) {
	$('#' + mainItem).hoverIntent(
		function() {
			if (!$('#' + subItem).is(':visible')) {
				if ($('#' + subItem).length > 0) {
					$('#' + mainItem + ' a:first-child').addClass('here');
					$('#' + subItem).slideDown();
				}
			}
		},
		function() {
			if ($('#' + subItem).is(':visible')) {
				$('#' + mainItem + ' a:first-child').removeClass('here');
				$('#' + subItem).slideUp();
			}
		}
	);
}


function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);

	if (delta < 60) {
		return 'less than a minute ago';
	} else if(delta < 120) {
		return 'about a minute ago';
	} else if(delta < (60*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (120*60)) {
		return 'about an hour ago';
	} else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return (parseInt(delta / 86400)).toString() + ' days ago';
	}
}

function customTwitterCallback(data) {

	if (data == undefined || !data) { return; }

	var tweet;

	// Find first tweet that is not a reply / message 
	for (var i = 0; i < data.length; i++) {
		if (data[i].text.indexOf('@') != 0) {
			tweet = data[i];
			break;
		}
	}

	// If all are replies, then just pick the first one
	if (tweet == undefined || !tweet) {
		tweet = data[0];
	}

	var origUser = tweet.user.screen_name;

	var retweet = 0;
	if (tweet.retweeted_status) {
		retweet = 1;
		tweet = tweet.retweeted_status;
	}

	var username = tweet.user.screen_name;
	var text = tweet.text;
	if (retweet) {
		text = 'RT @' + username + ': ' + text;
	}

	var status = text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {

		return '<a target="_blank" href="'+url+'">'+url+'</a>';

	}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {

		return	reply.charAt(0)+'<a target="_blank" href="http://www.twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';

	}).replace(/\B(#[_a-z0-9]+)/ig, function(hash) {

		return '<a target="_blank" href="http://www.twitter.com/search/?q='+hash+'">'+hash+'</a>';

	});

	var time = relative_time(tweet.created_at);

	var tweetHTML = '<li class="module-list-item">' + 
		'<div class="tweet-text">' + status + '</div>' + 
		'<div class="tweet-time" style="font-size: 85%; margin-top: 10px">' + 
			'<a target="_blank" href="http://twitter.com/' + username + '/status/' + tweet.id_str + '">' + time + '</a>' + 
			' | ' + 
			'<a target="_blank" href="http://twitter.com/?status=@' + username + '%20&in_reply_to_status_id=' + tweet.id_str + '&in_reply_to=' + username + '">reply</a>' + 
		'</div>' + 
	'</li>';


	$('#twitter_update_list_' + origUser).html(tweetHTML);
}


function track(url)
{
	if (_gat) {
       var tracker = _gat._getTrackerByName();
       tracker._trackPageview(url);
    }
}

function setPermalink() {

	 if (!prefix) {
		return;
	}

	var title = $('#' + prefix + '_title_en_us').val().toLowerCase();
	title = title.replace(/ /g, '\-');
	title = title.replace(/[^\w\-]/g, '');
	title = title.substr(0, 80);

	var date = '';
	if ($('#' + prefix + '_date').val() != '') {
		date = $('#' + prefix + '_date').val().replace(/(\d+)-(\d+)-\d+/, '$1/$2');
	}

	var total = date +  '/' + title;

	$('#' + prefix + '_permalink').val(total);
}

/** old stuff: */

var arrayBibleBook = new Array();
arrayBibleBook[1] = "Genesis";
arrayBibleBook[2] = "Exodus";
arrayBibleBook[3] = "Leviticus";
arrayBibleBook[4] = "Numbers";
arrayBibleBook[5] = "Deuteronomy";
arrayBibleBook[6] = "Joshua";
arrayBibleBook[7] = "Judges";
arrayBibleBook[8] = "Ruth";
arrayBibleBook[9] = "1 Samuel";
arrayBibleBook[10] = "2 Samuel";
arrayBibleBook[11] = "1 Kings";
arrayBibleBook[12] = "2 Kings";
arrayBibleBook[13] = "1 Chronicles";
arrayBibleBook[14] = "2 Chronicles";
arrayBibleBook[15] = "Ezra";
arrayBibleBook[16] = "Nehemiah";
arrayBibleBook[17] = "Esther";
arrayBibleBook[18] = "Job";
arrayBibleBook[19] = "Psalms";
arrayBibleBook[20] = "Proverbs";
arrayBibleBook[21] = "Ecclesiastes";
arrayBibleBook[22] = "Song of Songs";
arrayBibleBook[23] = "Isaiah";
arrayBibleBook[24] = "Jeremiah";
arrayBibleBook[25] = "Lamentations";
arrayBibleBook[26] = "Ezekiel";
arrayBibleBook[27] = "Daniel";
arrayBibleBook[28] = "Hosea";
arrayBibleBook[29] = "Joel";
arrayBibleBook[30] = "Amos";
arrayBibleBook[31] = "Obadiah";
arrayBibleBook[32] = "Jonah";
arrayBibleBook[33] = "Micah";
arrayBibleBook[34] = "Nahum";
arrayBibleBook[35] = "Habakkuk";
arrayBibleBook[36] = "Zephaniah";
arrayBibleBook[37] = "Haggai";
arrayBibleBook[38] = "Zechariah";
arrayBibleBook[39] = "Malachi";
arrayBibleBook[40] = "Luke";
arrayBibleBook[41] = "Matthew";
arrayBibleBook[42] = "Mark";
arrayBibleBook[43] = "John";
arrayBibleBook[44] = "Acts";
arrayBibleBook[45] = "Romans";
arrayBibleBook[46] = "1 Corinthians";
arrayBibleBook[47] = "2 Corinthians";
arrayBibleBook[48] = "Galatians";
arrayBibleBook[49] = "Ephesians";
arrayBibleBook[50] = "Philippians";
arrayBibleBook[51] = "Colossians";
arrayBibleBook[52] = "1 Thessalonians";
arrayBibleBook[53] = "2 Thessalonians";
arrayBibleBook[54] = "1 Timothy";
arrayBibleBook[55] = "2 Timothy";
arrayBibleBook[56] = "Titus";
arrayBibleBook[57] = "Philemon";
arrayBibleBook[58] = "Hebrews";
arrayBibleBook[59] = "James";
arrayBibleBook[60] = "1 Peter";
arrayBibleBook[61] = "2 Peter";
arrayBibleBook[62] = "1 John";
arrayBibleBook[63] = "2 John";
arrayBibleBook[64] = "3 John";
arrayBibleBook[65] = "Jude";
arrayBibleBook[66] = "Revelation";

// Return a link with new language
function jsChangeLanguageLink(sNewLang)
{
	// Save language name in cookie
	document.cookie = "LastLanguage=" + sNewLang;

	// Refresh current page to display in new language
	window.location.reload();	
}

function jsEnableFormButton(bEnable)
{
	if (document.getElementById("buttonSave") != null)
	{
		document.getElementById("buttonSave").disabled = !bEnable;
	}
	
	if (document.getElementById("buttonSaveExit") != null)
	{
		document.getElementById("buttonSaveExit").disabled = !bEnable;
	}
	
	if (document.getElementById("buttonReset") != null)
	{
		document.getElementById("buttonReset").disabled = !bEnable;
	}
}

function jsOnEdit()
{
	jsEnableFormButton(true);
}

function jsReset(idForm)
{
	if (document.getElementById(idForm) != null)
	{
		document.getElementById(idForm).reset();
	}
	else
	{
		alert("Cannot reset form " + idForm);
	}
	
	jsEnableFormButton(true);
}

function jsImportOnlineESVBibleText(idElement)
{
	try
	{
		var nBookID = document.getElementById("BookID").value;
		var sBook = arrayBibleBook[(nBookID >= 1 && nBookID <= 66 ? nBookID : 1)];
		var sChapterVerse = document.getElementById("ChapterVerse").value;
		
		// Following code comes from http://www.esvapi.org/api
		$.get("http://www.esvapi.org/v2/rest/passageQuery", 
			{
				"key":								"IP",
				"passage":							sBook + " " + sChapterVerse,
				"output-format":					"plain-text",
				"include-passage-references":		"0",
				"include-short-copyright":			"0",
				"include-word-ids":					"0",
				"include-passage-horizontal-lines":	"0",
				"include-footnotes":				"0",
				"include-heading-horizontal-lines":	"0",
				"include-headings":					"0",
				"include-subheadings":				"0",
				"include-selahs":					"0",
				"line-length":						"0"
			},
		
			function(data, textStatus)
			{
				if (document.getElementById(idElement) != null)
				{
					document.getElementById(idElement).innerHTML = data;
				}
			}
		);
	}
	catch (err)
	{
		alert(err.description + "\n\n請將 http://www.ebct.org.tw 加入信任網站清單.\nPlease add http://www.ebct.org.tw into trusted websites.");
	}
}

function jsImportOnlineNIVBibleText(sPassage, idElement)
{
	alert("This function is not implemented yet.");
}


/**
 Inserts an email address via javascript so as to hide it from spammers
*/
function jemail(user, domain, suffix, link) {
    if (typeof link == "undefined" || link == "" || link == null) {
        link = user + "@" + domain + "." + suffix;
    }
    document.write('<a href="' + 'mailto:' + user + '@' + domain + '.' + suffix + '">' + link + '</a>');
}



function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

