/**
 * Base JavaScript file for GenealogyBank.com
 */

// overwite this from 404/500 template (analytics helper)
response_code = 200;

$.cookie = $.cookie || function(){ return 0; };

sourcelist_fix = function(start, end, total){

	/*********************************************************************
		displays "next" and "previous" links, highlights current page
	*********************************************************************/

	var jb = $('div.jumpbar');
	if (jb.length){
		var pnum = window.location.pathname.split('/').pop().split('.')[0];
		var ext = window.location.href.split('?')[1];
		ext = ext == undefined ? '.html' : '.html?' + ext;

		pnum = (pnum == 'index' || pnum == '') ? 1 : Number(pnum);
		$("a[class='number']:contains('"+pnum+"'):first",jb).addClass('current');
		if (total > end){
			$("a[class='next']",jb).attr('href',String(pnum+1)+ ext).show();
		}
		if (start != 1){
			$("a[class='previous']",jb).attr('href',String(pnum-1)+ ext).show();
		}
	}
}



function numeric_commas(s){
	s += '';
	var re = /(\d+)(\d{3})/;
	while (re.test(s)) {
		s = s.replace(re,['$1','$2'].join(','));
	}
	return s;
}




// container for pty/classification scripts/properties
context_map = {}

context_map['init'] = function(){
		
	var explore_div = $('#context_explore');
	if (explore_div.length){	
		// .click() not .change() - IE7 jquery issue
		$('#context_explore input').click( function() {			
			context_map['update']();
		});				
	}
	
}


context_map['update'] = function(){
	
	var explore_div = $('#context_explore');
	if (!explore_div.length){		
		return undefined
	}
	
	var explore_div = $('#context_explore');
	var input_options = $('input',explore_div);
	var selected_pairs = [];
	var refresh_url = './data.xml?';
	
	input_options.each(function() {			
		if ($(this).attr('checked')){			
			var nv_pair = {name:$(this).attr('name'),value:$(this).attr('value')}
		    selected_pairs.push(nv_pair)
		    
		    
		}
	});	
	
	for (var i=0;i<selected_pairs.length;i++){
		refresh_url += selected_pairs[i]['name'] + '=' + escape(selected_pairs[i]['value']) + '&';
	}
	
	try{
		flashmap = document.getElementById("context_explore_hud")
		flashmap.JStoASviaExternalInterface(refresh_url)
	}catch(e){
		alert(e)
	}
	
}


pty_form_control = {}

pty_form_control['search'] = function(pty_list){
	
	// clear all checkmarks
	var control_div = $('#pty_form_list');
	var input_options = $('input',control_div);
	input_options.removeAttr('checked')
	
	// create the test
	list_truth = {}
	for (var i=0;i<pty_list.length;i++){
		list_truth[pty_list[i]] = true;
	}
	
	// check all requested pty
	input_options.each(function() {			
		if ($(this).attr('value') in list_truth){
			$(this).attr('checked', 'checked')
		}		
	});
	
	$("#search-form").submit();
}

pty_form_control['init'] = function(){
	
	var control_div = $('#pty_form_list');
	if (control_div.length){
		
		var pty_options = $('label',control_div);
				
		var sidebar = $('#sidebar');
		var output = $('<div id="pty_sidebar" class="wrap">');		
		
		var ul = $('<ul/>')
		
		// first order of business, if we are presently limited allow results expansion
		var checked_inputs = $('input[checked]',control_div);		
		if (checked_inputs.length == pty_options.length){
			var category = $('label:first',control_div).text();
			output.append('<p>Category limited to <span class="limit">'+category+'</span></p>');
			ul.append('<li><a href="javascript:pty_form_control[\'search\']([])">Search all Categories</a></li>');			
		}else{
		
			var deduped_options = [];
			var sorted_options = [];
			
			output.append('<p>'+$('h4',control_div).text()+'</p>')
						
			pty_options.each(function() {
				
				var pty_label = $(this).text();
				var pty_value = $('input',$(this)).val();
				var pty_count = Number($('span.count',$(this).parent()).text());
				
				if (pty_label in deduped_options){				
					deduped_options[pty_label]['value'].push(pty_value);
					deduped_options[pty_label]['count'] += pty_count;
				}else{
					var o = [];
					o['label'] = pty_label;
					o['value'] = [pty_value];
					o['count'] = pty_count;
					deduped_options[pty_label] = o;
					sorted_options.push(o);					
				}				
			});			
			
			sorted_options.sort(function(a, b) {
			  if (a['count'] > b['count']) return -1
			  if (a['count'] < b['count']) return 1
			  return 0
			});			
						
			for (var i=0;i<sorted_options.length;i++){
				var o = sorted_options[i];
				ul.append('<li><a href="javascript:pty_form_control[\'search\'](['+o['value'].join(',')+'])">'+o.label+'</a> <span class="count">('+numeric_commas(o['count'])+')</span></li>')
			}
			
		}
		
		output.append(ul)	
		sidebar.append($(output))
		
	}
}


// container for imgdoc scripts/properties
imgdoc_control = {}

imgdoc_control['toc'] = {}
imgdoc_control['toc']['update_session'] = function(display_toc){
	var request = './doc_properties.json?display_toc='+display_toc;
	$.get(request);
}

imgdoc_control['toc']['toggle'] = function(){

	/*********************************************************************
		toggles the full toc on and off
		requires tileViewerToc 1.01+
	*********************************************************************/

	var toc_list = $('#'+tileViewerToc.props['list_id']);
	var toc_list_link_div = $('#toggle_toc');
	var toc_list_count = $('li', toc_list).length;

	switch(true){

		// if there are no list items, assume it has not been initialized
		case !toc_list_count:
			tileViewerToc.init()
			toc_list_link_div.html('loading..');
			tileViewerToc.postProcess = function(){
				toc_list_link_div.html('Displaying all pages <a href="javascript:imgdoc_control[\'toc\'][\'toggle\']()">(hide)</a>');
				imgdoc_control['toc']['update_session']('true');
			}
			break;

		// if it is displayed, "collapse" it
		case toc_list.css('display') == 'block':
			toc_list.css('display','none');
			toc_list_link_div.html('<a href="javascript:imgdoc_control[\'toc\'][\'toggle\']()">List all pages in this issue.</a>');
			imgdoc_control['toc']['update_session']('false');
			break;

		// if it is collapsed, "display" it
		case toc_list.css('display') == 'none':
			toc_list.css('display','block');
			toc_list_link_div.html('Displaying all pages <a href="javascript:imgdoc_control[\'toc\'][\'toggle\']()">(hide)</a>');
			imgdoc_control['toc']['update_session']('true');
			break;

		// shouldn't be here
		default:
			alert('unhandled exception');
			break;

	}
}

imgdoc_control['citation_title'] = {}

// some properties
imgdoc_control['citation_title']['text'] = '';
imgdoc_control['citation_title']['maxchar'] = 300;
imgdoc_control['citation_title']['less_text'] = 'Truncated Title';
imgdoc_control['citation_title']['more_text'] = 'Full Title';

imgdoc_control['citation_title']['get_element'] = function(){

	/*********************************************************************
		returns the dom container of the title
	*********************************************************************/

	return $('#citation h1');
}

imgdoc_control['citation_title']['append_link'] = function(n){

	/*********************************************************************
		appends the link that toggles the title citation
	*********************************************************************/

	title_link = $('<a href="javascript:imgdoc_control[\'citation_title\'][\'toggle\'](this)">'+n+'</a>')
	imgdoc_control['citation_title']['get_element']().append(title_link)
}

imgdoc_control['citation_title']['toggle'] = function(){

	/*********************************************************************
		toggles the full title in citation on and off
	*********************************************************************/

	// get the link text - jquery selector '#citation h1 a'
	var link_text = $('#citation h1 a').text();

	// get the h1 element
	var citation_element = imgdoc_control['citation_title']['get_element']();

	// clear the contents
	citation_element.empty();

	if (link_text == imgdoc_control['citation_title']['less_text']){
		// tighten up the title followed by an elipse
		max_text = imgdoc_control['citation_title']['text'].substring(0,imgdoc_control['citation_title']['maxchar'])
		citation_element.text(max_text.substring(0,max_text.lastIndexOf(' ')) + '... ')
		imgdoc_control['citation_title']['append_link'](imgdoc_control['citation_title']['more_text']);

	}else{
		// show all text
		citation_element.text(imgdoc_control['citation_title']['text'])
		imgdoc_control['citation_title']['append_link'](imgdoc_control['citation_title']['less_text']);
	}
}

imgdoc_control['citation_title']['init'] = function(){

	/*********************************************************************
		initializes the citation title toggle, if non-initializable it will
		return undefined.
	*********************************************************************/

	try{
		// set text property once at the outset.
		imgdoc_control['citation_title']['text'] = imgdoc_control['citation_title']['get_element']().text();
		if (imgdoc_control['citation_title']['text'].length > imgdoc_control['citation_title']['maxchar']){
			// append the link as less (all text is showing)
			imgdoc_control['citation_title']['append_link'](imgdoc_control['citation_title']['less_text']);
			imgdoc_control['citation_title']['toggle']();
		}
	}catch(e){
		return undefined;
	}
}


// Create a hash of frequently used strings to help with DRY
var _stringHash = {
	'simpleSearch': 'Simple Search',
	'advancedSearch': 'Advanced Search',
	'clearForm': 'Clear Form'
};

/**
 * Code to execute when the document is ready
 */

$(document).ready(
function() {
	
	pty_form_control['init']()
	context_map['init']()

	if (typeof(loadSnippets) == 'function') {
		loadSnippets();
	}

	if ($("#kwsearch").length > 0) {
		if ($("body#home").length > 0 || $("body#landing").length > 0) {
			var searchMode = $.cookie("searchMode") || "simple";
			var display = (searchMode == "advanced") ? "block" : "none";
			$("#kwsearch").css("display", display);
		}
	}
	
	if ($("#search-form").length > 0) {
		addClearForm();
	}

	if ($("#home").length > 0 || $("#landing").length > 0) {
		addSearchModeToggle(searchMode);
	}

	

	$("#sort").change(function() {
		$("#search-form").submit();
	});

	$("#birthy_0").change(function() {
		if($("#birthy_1").attr("value") == ""){
			$("#birthy_1").attr("value", $("#birthy_0").attr("value"));
		}
	});

	$("#deathy_0").change(function() {
		if($("#deathy_1").attr("value") == ""){
			$("#deathy_1").attr("value", $("#deathy_0").attr("value"));
		}
	});

	$("#search-tips").click(showSearchTips);
	$("#search-note a").click(showSearchTips);

	imgdoc_control['citation_title']['init']();
	
	
	// replace the property setting url with javascript
	if (typeof(tileViewerToc) == 'object' && !($.browser.msie && $.browser.version < 7)){
		$("#toc_display_control").attr('href',"javascript:imgdoc_control['toc']['toggle']()");
	}
	
	if ($("#home #lname").length > 0) {
		$("#lname").focus()
	}
	
	
	
	handle_analytics()

});

/**
 * Adds a special link to toggle between basic and advanced
 * search mode for js enabled browsers that are compatible
 * with jQuery.
 */
function addSearchModeToggle(mode) {
	if ($('#home').length > 0 || $('#landing').length > 0) {
		if (mode == 'advanced') {
			$('#search_links').append('<a id=mode-toggle href="javascript:toggleMode(this)">' +
					_stringHash['simpleSearch'] + '</a>');
		} else {
			$('#search_links').append('<a id=mode-toggle href="javascript:toggleMode(this)">' +
					_stringHash['advancedSearch'] + '</a>');
		}
	}

}

function clearSearchForm() {
	$("#search-form input.text").each(function() {
		$(this).attr("value", "");
	});
	
	$("#search-form input:checkbox").each(function() {
		this.checked = false;
	});

	$("#search-form select").each(function() {
		if (this.id != "sort") {
			this.selectedIndex = 0;
		}
	});
	context_map['update']()
	
}

function addClearForm() {
	$('#search_links').append('<a id="do-clear" href="javascript:clearSearchForm()" title="Clear the fields on this form">' +
			_stringHash['clearForm'] + '</a>');
}

function showSearchTips() {
	window.open(
		this.href,
		'tipswindow',
		'width=525,height=575,toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
	void(0);
	return false;
}

/**
 * Toggles between display of basic and advanced search forms
 * on the home page, and sets a cookie to remember the user's
 * preference.
 */
function toggleMode(source) {
	var searchMode = $.cookie('searchMode') || 'simple';
	if (searchMode == 'advanced') {
		$.cookie('searchMode', 'simple', {expires:30});
		$('#kwsearch').css('display', 'none');
		$('#mode-toggle').text(_stringHash['advancedSearch']);
	} else {
		$.cookie('searchMode', 'advanced', {expires:30});
		$('#kwsearch').css('display', 'block');
		$('#mode-toggle').text(_stringHash['simpleSearch']);
	}
}

handle_analytics = function () {
	
	/*********************************************************************
		google analytics is creating a drag on page load, this function allows
		the script to be loaded and run after the page is loaded to promote
		a better end user experience.
	*********************************************************************/
	
	var current_path = window.location.pathname;
	var current_query_string = window.location.search;
	var page_reference = undefined;
	
	/*********************************************************************
		a collection of mappings that maintain consistency w/ version 1, ordering
		is important. The mappings were formerly peppered throughout the templates
		as onload urchin calls. The script to be loaded and run after the page is
		loaded to promote a better end user experience.
		[page_reference, [path_regex_truth[,]], [query_string_regex_truth[,]]]
	*********************************************************************/
	
	var analytics_map = [];		
	analytics_map.push( ["list.html", [], [new RegExp("sort="), new RegExp("pg=") ] ] );
	analytics_map.push( ["search.html", [], [new RegExp("sort=") ] ] );
	
	/*
	analytics_map.push( ["/keyword.html", [new RegExp("^/gbnk/$")], [] ] );
	analytics_map.push( ["/doc.html", [new RegExp("^/gbnk/.+/doc/")], [] ] );
	analytics_map.push( ["/account.html", [new RegExp("^/gbnk/account/$")], [] ] );
	analytics_map.push( ["/cancel.html", [new RegExp("^/gbnk/cancel/$")], [] ] );
	analytics_map.push( ["/norenew.html", [new RegExp("^/gbnk/norenew/$")], [] ] );
	analytics_map.push( ["/subscribe.html", [new RegExp("^/gbnk/subscribe/$")], [] ] );	
	analytics_map.push( ["/legacy0107.html", [new RegExp("^/gbnk/legacy")], [] ] );
	analytics_map.push( ["/legacy01302007.html", [new RegExp("^/gbnk/legacy2")], [] ] );
	analytics_map.push( ["/obitsemail1206.html", [new RegExp("^/gbnk/email_offer")], [] ] );
	*/
	
	page_reference = current_path;
	
	for (var i=0;i<analytics_map.length;i++){
		
		var reference = analytics_map[i][0];
		var path_regex_truth = analytics_map[i][1];
		var query_string_regex_truth = analytics_map[i][2];
		
		var re_match = true;		
		
		for (var j=0;j<path_regex_truth.length;j++){
			var pci = path_regex_truth[j].exec(current_path)
			if (pci == null) {
				re_match = false;
				break;			
			}
		}
		
		if (!re_match) continue;
		
		for (var j=0;j<query_string_regex_truth.length;j++){
			var qci = query_string_regex_truth[j].exec(current_query_string);
			if (qci == null) {
				re_match = false;
				break;
			}
		}
		
		if (!re_match) continue;
		
		// 'search' and 'list' are better represented in-context, others should be at web root
		if (reference.indexOf('/') == 0){
		page_reference = reference;		
		}else{
			page_reference += reference;	
		}
		
		break;
		
	}
		
	// this variable should be global
	if (!('_gat' in window)){
		return undefined	
	}
	
	pageTracker = _gat._getTracker("UA-126152-4");
	
	// http://www.google.com/support/googleanalytics/bin/answer.py?answer=55524
	pageTracker._setDomainName(".genealogybank.com");
	
	if (response_code != 200){
		pageTracker._trackPageview('/' + String(response_code) + '/?page=' + current_path);
	}else if (page_reference != current_path){
		pageTracker._trackPageview(page_reference);		
	}else{
		pageTracker._trackPageview();
	}
		
	// outgoing links, connect to analytics.
	var outgoing_links = $("a[href ^= 'http']");
	$.each(outgoing_links, function(){
		$(this).click( function() { 
			var ahref = $(this).attr('href');
			if (ahref.indexOf('genealogybank.com') == -1){				
				var cleaned_href = ahref.replace(/https?:\/\//,'');
				var analytics_path = '/outgoing/'+cleaned_href;
	     		pageTracker._trackPageview(analytics_path);
	     	}
	});
	});
	
	
	
}