/** Set up **/

jQuery(function($) {
	
	bindToggleResultDetails();
	
	// bindDeptDatasetMap();
	
	load_pub_hub_forms();
	
	setupPadlsBrowsing();
	
	setupHomepageContent();
	
});

/** Functions for result lists **/

function bindToggleResultDetails() {

	if ($('.result_hiddens')[0]) {
	
		// set up images to expand
		// $('.result_js').html('<a href="" onclick="return false;" title="Show more information"><img src="/images/result_expand.jpg" class="js_switch" /></a>');

		// set up text to expand
		if ($('ul.research_results')[0]) {
			// Publication hub search text
			$('.result_js').html('<strong>Details:</strong> <p class="result_field result_expand"><a href="" onclick="return false;" title="Show more information">Click here for author and abstract</a></p>');	
		} else {
			// Data search text
			$('.result_js').html('<strong>Details:</strong> <p class="result_field result_expand"><a href="" onclick="return false;" title="Show more information">Click here for further details</a></p>');
		}
		
		// <a href="" onclick="return false;" title="Show more information"><img src="/images/result_expand.jpg" class="js_switch" /></a>');

		
		// bind click
		$('.result_js a').click(function() {

			var hidden_info = $(this).parent().parent().siblings('.result_hiddens');
			if (hidden_info.is(':hidden')) {
				hidden_info.slideDown();
				$(this).children('img').attr({src: "/images/result_collapse.jpg" });
				$(this).attr({title: "Show less information" });
			} 
			/*else {
				hidden_info.slideUp();
				$(this).children('img').attr({src: "/images/result_expand.jpg" });
				$(this).attr({title: "Show more information" });
			}
			*/
			return false;
		
		});
	}
}

/** Functions for user registration form **/

function toggleReceiveAll() {
	if ($('.checkbox_all').attr('checked')) {
		// disable all others
		$('.checkbox_all_adls').attr('disabled', true);
		$('.checkbox_all_datasets').attr('disabled', true);
		$('.checkbox_single').attr('disabled', true);
	} else {
		// enable all others
		$('.checkbox_all_adls').attr('disabled', false);
		$('.checkbox_all_datasets').attr('disabled', false);
		if ($('.checkbox_all_datasets').attr('checked')) {
			$('.checkbox_single').attr('disabled', true);
		} else {
			$('.checkbox_single').attr('disabled', false);
		}
	}
	
}

function toggleReceiveAllDatasets() {
	if ($('.checkbox_all_datasets').attr('checked')) {
		// disable all datasets
		$('.checkbox_single').attr('disabled', true);
	} else {
		// enable all datasets
		$('.checkbox_single').attr('disabled', false);
	}
}

function bindDeptDatasetMap() {
	if ($('#dynamic_dept_select_pub') != null) {
		$('#dynamic_dept_select_pub').change(function() {
			changeDynamicDataset();
		});
		
		// update dept to current selection
		var current_dept = get_query_argument('dept');
		if (current_dept != "") {
			$('#dynamic_dept_select_pub').val(current_dept);
			// update both forms
			if ($('#dynamic_dept_select_data') != null) {
				$('#dynamic_dept_select_data').val(current_dept);
			}
		}
		
		// update dataset to current selection
		changeDynamicDataset();
	}
}

function changeDynamicDataset() {
	$('#dynamic_dataset_select').empty();

	var dept_code = $('#dynamic_dept_select_pub').val();

	var ds_list = null;

	if (dept_code == 0) {
		ds_list = all_datasets['list'];
	} else {
		if (window.dept_ds_map != undefined) {
			ds_list = dept_ds_map[dept_code]['datasets'];
		} else {
			ds_list = new Array();
		}
	}

	var dropdownList = document.getElementById("dynamic_dataset_select");

	var current_option = get_query_argument('ds');
	var set_current_option = false;

	for (var i = 0; i < ds_list.length; i++) {

		var ds_info = ds_list[i];

		var title = ds_info['title'];
		
		title = title.replace(/&#(\d+);/g,
				function(wholematch, parenmatch1) {
					return String.fromCharCode(+parenmatch1);
				}
			);

		var option = new Option(title, ds_info['id']);
		if ($.browser.msie) {
			dropdownList.add(option);
		} else {
			dropdownList.add(option, null);
		}
		
		// check for current selection
		if (ds_info['id'] == current_option) {
			set_current_option = true;
		}
	}
	
	if (set_current_option) {
		$('#dynamic_dataset_select').val(current_option);
	}
}

/**
 * Helper function from http://www.drupalblog.nl/content/get-url-query-arguments-javascript
 **/
function get_query_argument(name, href) {

  href = (href) || window.location.href;
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec(href);

  return (results == null ? "" : results[1].replace(/\+/g," "));
};

/**
 * Function load in hidden publication hub forms dynamically
 **/
function load_pub_hub_forms() {

	// check if element exists on this page
	if ($('#dynamic_pub_hub_form_wrap') == null) {
		return;
	}

	$.get('/scripts/load_hub_forms.php', function(data) {
		$('#dynamic_pub_hub_form_wrap').html(data);
		
		// set data search search term maybe
		var current_search = get_query_argument('search');
		if (current_search != "") {
			$('.searchterm_criterion #search').val(unescape(current_search));
		}

		
		if ($('#datasearch_publication') != null) {
			bindDeptDatasetMap()
		}


		if ($('.search_option_publications') != null) {
			// click publications link to show publications search
			$('.search_option_publications a').click(function() { syncDropDown('dynamic_dept_select_data', 'dynamic_dept_select_pub'); show_search('publication'); return false; });
			$('.search_option_publications input').click(function() { $('.search_option_publications a').click(); return true; });
		}

		if ($('.search_option_data') != null) {
			// click data link to show data search
			$('.search_option_data a').click(function() { syncDropDown('dynamic_dept_select_pub', 'dynamic_dept_select_data'); show_search('data'); return false; });
			$('.search_option_data input').click(function() { $('.search_option_data a').click(); return true; });
		}

		// Bind to result text if available
		if ($('.search_report') != null) {
			// $('.search_report').append('<a href="" id="show_search_form_link">Change your search</a>');
			// $('.further_search_options').append('<a href="" id="show_search_form_link">Change your search</a>');
			$('.change_search_text').html('<a href="" id="show_search_form_link">' + $('.change_search_text').html() + '</a>');

			$('#show_search_form_link').click(function() {

				if ($('.search_option_publications input[type="radio"]').attr('checked') == true) {
					show_search('publication');
				} else 
				if ($('.search_option_data input[type="radio"]').attr('checked') == true) {
					show_search('data');
				}

				$('.search_forms_wrap').slideDown(400, function() { $('.external_search_link').show(); });

				// disable self
				$('#show_search_form_link').unbind('click');
				$('#show_search_form_link').click(function() { return false; });

				return false;
			});
		}

		// set nonjs fields to 0
		$('input.nonjs').val(0);

		// Check if user has selected a search while we were loading
		// window.alert('checking for user input:' + $('.search_forms_wrap').is(':visible'));

		if (choose_search > 0) {
			if (choose_search == 1) {
				show_search('publication');
			} else if (choose_search == 2) {
				show_search('data');
			}
		}

		
	});
	
	


}

function show_search(search_type) {

	var to_hide = '';
	var to_show = '';

	if (search_type == 'publication') {
		to_hide = 'data';
		to_show = search_type;
		
		to_uncheck = 'data';
		to_check = 'publications'
	} else {
		to_hide = 'publication';
		to_show = search_type;

		to_uncheck = 'publications';
		to_check = 'data'
	}
	
	$('.search_option_' + to_uncheck + ' input[type="radio"]').removeAttr('checked');
	$('.search_option_' + to_check + ' input[type="radio"]').attr('checked', true);
	
	if ($('#datasearch_' + to_hide) != null) {
		$('#datasearch_' + to_hide).css({visibility: "hidden", display: "none"});
		$('div.search_options .search_option_' + to_uncheck + ' a img').css({ opacity: 0.5 });
	}
	
	if ($('#datasearch_' + to_show) != null) {
		$('#datasearch_' + to_show).css({visibility: "visible", display: "block"});
		$('div.search_options .search_option_' + to_check + ' a img').css({ opacity: 1.0 });
	}
	
}

function syncDropDown(from_list, to_list) {
	if ($('#' + to_list).val() != $('#' + from_list).val()) {
		$('#' + to_list).val($('#' + from_list).val());
		if (to_list == 'dynamic_dept_select_pub') {
			changeDynamicDataset();
		}
	}
}

function validDataProvider() {
	if (
	     ( $('#dynamic_dataset_select').val() == undefined || $('#dynamic_dataset_select').val() == 0 ) 
	     &&
	     ( $('#dynamic_dept_select_pub').val() == undefined || $('#dynamic_dept_select_pub').val() == 0 ) 
	   ) {
		window.alert('Please select an organisation.');
		return false;
	}
	return true;
}

function validSearchTerm() {
	if (jQuery.trim($('.searchterm_criterion #search').val()) == '') {
		window.alert('Please enter a search term.');
		return false;
	}
	if ($('.searchterm_criterion #search').val().search(/[\w\d]/) < 0) {
		window.alert('Please enter a search word.');
		return false;
	}
	return true;
}


/*
	Set up expanding/collapsing themes, datasets etc in PADLS Browse resource page
*/
function setupPadlsBrowsing() {

	if ($('.expand_theme') == null) {
		return;
	}
	

	// ----- Add links around expandable spans -----
	
	$('.expandable').each(function(i) {
		$(this).html(
			'<a href="" class="expandable_a">' +
			$(this).html() +
			'</a>'
		)
	});
	
	// ----- Generic toggle function for expandable hrefs -----
	
	$('.expandable_a').click(function() {
		$(this).parent().parent().children('ul').slideToggle();
		return false;
	});

}

/*
	Set up dynamic home page content if on homepage
*/
var current_tab = 'hcnav_find_admin_data';
var current_hc = 'hc_find_admin_data';

function setupHomepageContent() {

	if ($('ul.homecontent') == null) {
		return;
	}
	
	$('ul.homecontent_nav li').mouseenter(function() {

		var this_id = $(this).attr('id')
		var div_hc = $(this).attr('id').replace(/^hcnav_/, 'hc_');
		
		if (current_hc != div_hc) {

			$('#' + current_tab).removeClass('hover');
			$('#' + current_hc).fadeOut();

			$('#' + this_id).addClass('hover');
			$('#' + div_hc).fadeIn();
			
			current_tab = this_id;
			current_hc = div_hc;
			
		}
		
	});

}

