/* Author: 

*/


/* from http://www.sohtanaka.com/web-design/mega-drop-downs-w-css-jquery/  */
//Set custom configurations


$(function() {
	var url_hash = window.location.hash;
	var url_query = window.location.search;
	var url_path = window.location.pathname.split('/');
	_.mixin(_.string.exports());
	
	// Bind the event.
	$(window).hashchange( function(e){
		
		if(location.hash != ''){
			if(location.hash === '#publications-list' || location.hash === '#background-info' ) {
				log('hello!');
				section_id = location.hash.split("-");
				var showcache = $('#content_holder > section:visible').not(section_id[0]); // find visible sections that are not the same as the location hashlet
				var hidecache = $('#content_holder > section:hidden').filter(section_id[0]); // find hidden sections that are the same as the location hashlet show them
				showcache.fadeOut(250); hidecache.fadeIn(250);
				$('#content_swap a[href='+location.hash+']').removeClass().addClass('selected'); //find the a for the location hash, style it as dominant
				$('#content_swap a[href!='+location.hash+']').removeClass().addClass('unselected'); //find the a for the location hash, style it as recessive
			} else if(url_path.length == 3 && url_path[1] === 'people') {
				// process get location hash. FIND a with that href call isotope
				// if hash ends with filter
				location_id = location.hash.replace('#','').split("-");
				log(location_id);
				if(location.hash.endsWith('filter')){
					$("#filters_filter").linkselect("val", location_id[0]);
				} else {
					$('li.filter-on').removeClass('filter-on');
					$('#filters a[href='+location.hash+']').closest('li').addClass('filter-on');
					filter_element = $('#filters a[href='+location.hash+']');
					filter_group = filter_element.attr('id').split("_");
					$("#filters_filter").linkselect("val", filter_group[1]);
					$('#people_cards').isotope({ filter: filter_element.attr('data-filter') });
					log(filter_element.attr('data-filter'));
				}
				//$("#filters_filter").linkselect("val", "role");
			} else if(url_path.length == 3 && url_path[1] === 'publications') {
				location_id = location.hash.replace('#','').split("|");
				var filter_string = '.ref_line_header, .ref_line_footer';
				if(location_id.length === 1){
					
				} else {
					//log(location_id);
					var allready = false;
					$('li.filter-on').removeClass('filter-on');
					if(location_id[0]==='all'){
						$('#type_filters li.filter_all').addClass('filter-on'); // find the appropriate a by href go closest set class
						filter_string+=', .has_project'; allready = true;
						$('ul.pub_list:hidden').show();
					} else {
						$('#type_filters li a[href="#'+location_id[0]+'"]').closest('li').addClass('filter-on');
						filter_string+=', .'+location_id[0];
						log('ul.pub_list:not("#'+location_id[0]+'")');
						$('ul.pub_list#pub_'+location_id[0]+'_list').show();
						$('ul.pub_list:not("#pub_'+location_id[0]+'_list")').hide();
					}
					if(location_id[1]==='all'){
						//$('#project_filters li');
						$('#project_filters li.filter_all').addClass('filter-on');
						if(!allready){ filter_string+='.has_project'; allready = true; }
					 } else {
						$('#project_filters li a[href="#'+location_id[1]+'"]').closest('li').addClass('filter-on');
						filter_string+='.'+location_id[1];
					}
					if(location_id[2]==='all'){
						//$('#year_filters li');
						$('#year_filters li.filter_all').addClass('filter-on');
						if(!allready){ filter_string+='.has_project'; allready = true; }
					} else {
						$('#year_filters li a[href="#'+location_id[2]+'"]').closest('li').addClass('filter-on');
						filter_string+='.year-'+location_id[2];
					}
				}
				log(filter_string);
				$('.pub_list').isotope({ filter: filter_string });
				$('.pub_list').each(update_pubcounts);
			}
		}
	});
	
	/*
	URL PARSING CODE - ANYTHING THAT NEEDS TO MODIFY THE URL GOES HERE
	first check url hash, if domain
	$('#people-filter_role')[0].checked=true;
	$('#people-filter_role').button("refresh"); other wise set both
	
	*/
	
	//url_path.length==1 is www.cpib.ac.uk
	//url_path.length==2 is www.cpib.ac.uk / file.ext (bad example)
	//url_path.length==3 is www.cpib.ac.uk / people /
	//url_path.length==3 is www.cpib.ac.uk / people / file.ext
	//url_path.length==4 is www.cpib.ac.uk / people / lord-frenchiferous /
	//etc
	
	if(url_path.length>1){
		/*log('url_path.length == '+url_path.length);
		for(var i=0;i<url_path.length;i++) log(url_path[i]);*/

		if(url_path.length===2){
			// frontpage
			if('' === url_query) $('#js-news').ticker();
			
			$("#rotator section").click(function() { log(this.id.slice(-1));frontpage_rotate(this.id.slice(-1)); });
			$('.active').click(function(){ location.href=$(this).find('.frontpage_mainlink').attr('href'); });
		} else if(url_path[1]==='people' || url_path[1]==='who-we-are') {
			if(url_path.length===3) {
				// should only really be /people/
				$('#people_cards').isotope( { itemSelector : '.person_card', layoutMode : 'fitRows' } );
				
				//$('.person_card').hover(person_card_hoverOn,person_card_hoverOff);
				$('.person_card').click(function(){log($(this));location.href=$(this).find('a').attr('href');});
				
				$('#filters').isotope({ itemSelector : '.filter_item', layoutMode : 'fitRows' });
				$("#filters_filter").linkselect({ change: function (li, value, text){ $('#filters').isotope({ filter: '.'+ value }); $('a#filter_all').click(); } });
				
				$("#filters_filter").linkselect("val", "role");
				if(url_hash === '') window.location.hash = '#all';
				
			} else if(url_path.length==4) {
				// realistically a people page
				$('.no-ie .pub_list').each(update_pubcounts);
				$('.ie9 .pub_list').each(update_pubcounts);
				$('button.button_pub').click(reveal_publications);
			}
		}
		else if(url_path[1]==='publications') {
			if(url_path.length===3) {
				$('.pub_list').isotope( { itemSelector : '.ref_line', layoutMode : 'fitRows' } );
				$('.filters').isotope( { itemSelector : '.filter_item', layoutMode   : 'fitRows' } ); // just to pretty them up
				//$("#filters_filter").linkselect({ change: function (li, value, text){ $('#filters').isotope({ filter: '.'+ value }); $('a#filter_all').click(); } });
				//$("#filters_filter").linkselect("val", "pubtype");
				//$('#filter_all').click();
				if(url_hash=='') location.href='#all|all|all';
				$('.filter_item a').click(function(e){
					e.preventDefault();
					// add to data filter for parent ul
					$(this).closest('ul').data('filter',$(this).attr('href').substring(1));// perhaps without #
					log($(this).closest('ul').data('filter'));
					// set location hash to  
					log($('#type_filters').data('filter') +'|'+ $('#project_filters').data('filter') +'|'+ $('#year_filters').data('filter'));
					window.location.hash = $('#type_filters').data('filter') +'|'+ $('#project_filters').data('filter') +'|'+ $('#year_filters').data('filter');
					// call hashchange and prevent default return condition
					//e.preventDefault();
					//return false;
					});
				$('button.button_pub').click(reveal_publications);
				//$('#manual_filter');
			} else if(url_path.length===4) {
				
			}
			
		} else if(url_path[1]==='tools-resources' ||url_path[1]==='software'||url_path[1]==='hardware'||url_path[1]==='resources') {
			if(url_path[2]==='gal4-line-browser') {
				log('fnar');
				$('area').on('click',function(e){
					e.preventDefault();
					var combo_mode = $('#binary_mode:checked').length;
					var layer = $(this).attr('id').split('_')[0];
					var filter_list = '';
					if(combo_mode) {
						// add together the tissues for a string and select
						log('fnar');
						$('#'+layer+'_layer').toggleClass('selected');
						$('.image_browser_layer.selected').each(function(){
							filter_list+='.'+$(this).attr('id').split('_')[0];
						})
					} else {
						$('.image_browser_layer.selected').removeClass('selected');
						$('#'+layer+'_layer').addClass('selected');
						filter_list+='.'+layer;
					}
					if(filter_list === '') filter_list='.none';
					log(filter_list);
					//$('.filters').isotope( { itemSelector : '.filter_item', layoutMode   : 'fitRows' } );
					//$('#image_browser_results').isotope({ filter: filter_list });
					

				});

				$('.filters').isotope( { itemSelector : '.filter_item', layoutMode   : 'fitRows' } ); // just to pretty them up
				
				$('#filter_box').bind('textchange', function (event, previousText) {
					// gazook through the visible li elements and check their data-keywords strings for anything starting with value
					var test_value = $(event.target).val();
					log('fnar');
					log(test_value);V
					$('.image_browser_card').each(function(){
						var vis = false;
						_.each($(this).data('keywords'), function(keyword){ log(keyword+' '+test_value); if( _.startsWith(keyword, test_value)){ vis = true; }  });
						if(!vis) $(this).hide();
					});
				});
					
				//$('#image_browser_results').isotope({ filter: '.filters' });
				
				$('#image_browser_results').isotope( { itemSelector : '.image_browser_card', layoutMode : 'fitRows' } );
				$('#image_browser_results').isotope({ filter: ".none" });
			$('#binary_mode:checked').on('click',function(e){
				$('.image_browser_layer.selected').removeClass('selected');
				$('#image_browser_results').isotope({ filter: '.none' });
			});
				
				
				/*$('.image_browser_layer.unselected').on('click',function(){
					log($(this).attr('id'));
					$(this).addClass('selected');
				});*/
				
			}
			
		} else if(url_path[1]==='events-activities') {
			$('button.button_calendar').click(function(){
				$(this).closest('li.side_calendar_line').find('.side_calendar_moreinfo').slideToggle('slow');
				if($(this).text()=='down'){
					$(this).removeClass('showless_calendar_desc').addClass('showmore_calendar_desc').find('span').text('up');
				} else {
					$(this).removeClass('showmore_calendar_desc').addClass('showless_calendar_desc').find('span').text('down');
				}
			});
		} else if(url_path[1]==='events' && url_path.length===4 ) {
			//log('fnar');
			$('#upcoming_seminar_list .side_calendar_title:contains("CPIB Seminar")').closest('li').css('display','block');
		} else if(url_path[1]==='root-nurgel') {
			var class_image = $('#class_image').data('imageid');
			var left_image =  $('#left_image').data('imageid');
			var right_image = $('#right_image').data('imageid');
			
			$('.nurgel_target').click(function(e) {
				// opaque down unselected say uploading results skip button to refresh
				chosen_image = $(this).data('imageid');
				chosen_offset = $(this).offset();
				$(this).addClass("chosen");
				var topcoord = e.pageY-10;
				var leftcoord = e.pageX-50;
				$('#overlay_nurgel-box').css({'top':topcoord.toString()+'px','left':leftcoord.toString()+'px'});
				$('#overlay_nurgel-box').fadeIn(500).removeClass('hidden');
				$('#nurgel-box').fadeIn(500).removeClass('hidden');
				$('#uploading').fadeIn(500).removeClass('hidden');
				$('#nurgel-toohard').fadeOut(250);
				$('.nurgel_target').unbind('click');
				$('.nurgel_target[data-imageid!="'+chosen_image+'"]').animate({ opacity: 0.1 }, 500).addClass('not_nurgel_target').removeClass('nurgel_target');
				$.post( 'http://www.cpib.ac.uk/wp-admin/admin-ajax.php',
					{
						action : 'nurgel_submit',
						class_image : class_image,
						left_image  : left_image,
						right_image : right_image,
						chosen_image: chosen_image,
						user_id : piwikTracker.getVisitorId(),
						postCommentNonce : $('#nonce').val()
					},
					function( response ) {
						// say uploaded offer to get new images do a page refresh
						if (response.success){
							$('#uploading').fadeOut(100).addClass('hidden');
							$('#uploaded-success').fadeIn(250).removeClass('hidden');
							
							//remove click handlers for images
							//alert( response );
						}
					}
				);
			});
			$('.nurgel-leave').click(function() { $('#nurgel-box').fadeOut(100).addClass('hidden'); });
		}
		if(url_path.length===4){
			$("figure a:not('.post_video_link')").fancybox({
				//'width'				: '85%',
				//'height'			: '550',
				'transitionIn'	:	'elastic',
				'transitionOut'	:	'elastic',
				'autoScale'     	: true,
				'speedIn'		:	600,
				'speedOut'		:	200
				//'type'				: 'iframe'
				//'onComplete'	: 'map_init'
			});
			// .figure_holder .figure_holder  width is number of figures inside *20 +, each width of figure a img
			$('.figure_center').each(function()
			{
				var figures = $(this).find('figure');
				var overall_width = 0; var max_height = 0;
				figures.each(function(){
					overall_width+=$(this).outerWidth(true)+parseInt($(this).css('marginRight').slice(0,2));
						if($(this).outerHeight(true) > max_height) max_height = $(this).outerHeight(true);
					});
					$(this).width(overall_width).height(max_height);
				}
			);
			if(url_path[2]==="root-ct-measures"){
				// need a poll - updating poll and code to handle the 
				// For horizontal bar charts, x an y values must will be "flipped"
				// from their vertical bar counterpart.
				
				$('.awesomebar > a').click(function(){
					var button_parts = $(this).attr('id').split('-');
					var button_id = button_parts[2].split('_')[0];
					var button_vote_type = button_parts[1];
					log(button_parts);
					log(button_id);
					log(button_vote_type);
					// set this button to selected, selected to not
					$(this).parent().find('.selected').removeClass('selected green').addClass('grey');
					$(this).removeClass('grey').addClass('selected green');
					
				});
				$('a.RM_switch_comment_form').click(function(){
					var button_parts = $(this).attr('id').split('-');
					var button_id = button_parts[1];
					log('parp');
					$('li#RM_entry-'+button_id+' div.RM-comments-holder').toggle(250);
					if($('li#RM_entry-'+button_id).css('height')==='150px') {$('li#RM_entry-'+button_id).css('height','100%');} else {$('li#RM_entry-'+button_id).css('height','150px');}
				});
				
			}
		}
	}
	
	
	//log('new');
	/*$('form[action^="http://ssbcpib04.nottingham"]').each(function(){
		log($(this).attr('action'));
		var link = $(this).attr('action').replace('ssbcpib04.nottingham','www.cpib');
		$(this).attr('action',link);
	});*/
	$('a[href^="http://ssbcpib04.nottingham"]').each(function(){
		var link = $(this).attr('href').replace('ssbcpib04.nottingham','www.cpib');
		$(this).attr('href',link);
	});
	
	//all pages
	LiveSearch.init();
	$('#s_label').placeholder();
	
	$('.boxlist').click(function(){ location.href=$(this).find('a').attr('href'); });
	
	$(window).hashchange();
	
});

$(document).ready(function () {
	$(".cb-enable").click(function(){
		var parent = $(this).parents('.switch');
		$('.cb-disable',parent).removeClass('selected');
		$(this).addClass('selected');
		$('.checkbox',parent).attr('checked', true);
	});
	$(".cb-disable").click(function(){
		var parent = $(this).parents('.switch');
		$('.cb-enable',parent).removeClass('selected');
		$(this).addClass('selected');
		$('.checkbox',parent).attr('checked', false);
	});
});


