/* INVOLVE global.js, Danny Connell, Reading Room 2011 */

$(document).ready(function(){

	/** Simple, generic functionality **/
	
		/* show javascript-dependent stuff (we'll hide in css) */
		$('a.button-add-to-my-clippings, a.icon-add-to-my-clippings').css('display', 'block');
	
		/* Open external links in new tab */
		//$("a[rel=external]").attr({ target: "_blank" }).attr('title', 'This link will open in a new window/tab');
		$('a[rel=external]').each(function(index) {
			message = 'This link will open in a new window/tab';
			originalTitle = $(this).attr('title');
			if (originalTitle == '') {
				newTitle = message;
			}
			else {
				newTitle = originalTitle + ' - ' + message;
			}
			$(this).attr({ target: "_blank" }).attr('title', newTitle);
		});
		
		/* text resizer */
		$( "#text-size a" ).textresizer({
			target: "#content, #more-information, #sub-nav",
			type: "css",
			sizes: [
				{ "font-size"  : "100%"
				},
				{ "font-size"  : "114.29%"
				},
				{ "font-size"  : "128.5715%"
				}
			]
		});
		
		// Remove outlines from clicked buttons
		$("button, input.submit").click(function() {
			$(this).blur();
		});
		
		/* disappearing default field values */
		$("input.toggle, textarea.toggle").each(function() { 
			this.defaultText = this.value; 
			if (this.defaultText == 'Keyword' || this.defaultText == 'Freetext') {
				$(this).focus(function() { 
					if (this.value == this.defaultText) this.value = ""; }).blur(function() { 
						if (this.value == "" && this.defaultText) this.value = this.defaultText; 
					});
			}
		});

		
		/* Form field highlighting */
		$('input:not(.submit), textarea').focus(function() {
			$(this).addClass('active');
		});	

		$('input:not(.submit), textarea').blur(function() {
			$(this).removeClass('active');
		});	
	
	/** IE6 drop-down navigation fix **/
		
		if($.browser.msie && $.browser.version < 7){
			$("#navigation>ul>li").hover(
				function () {
					$(this).addClass('hover');
				},
				function () {
					$(this).removeClass('hover');
				}
			);
		}		

		
	/** Home page slider **/
		
		if (!$('#slideshow').length == 0) {
			$('#slideshow').cycle({ 
				timeout: 7000 
			});
		}
	
	/** publications - search collapse **/
	
		var collapsed = false;
		var animating = false;
		
		function ieCollapse() {
			animating = true;
			$("div.collapsible").slideUp(function () {
				collapsed = true;
				$.cookie('collapsed', 'true');
				$("a#collapse-toggle").html('Show');
				$("a#collapse-toggle").addClass('collapsed');
				animating = false;
			});	
		}
		
		function ieExpand() {
			animating = true;
			$("div.collapsible").slideDown(function () {
				collapsed = false;
				$.cookie('collapsed', 'false');
				$("a#collapse-toggle").html('Hide');
				$("a#collapse-toggle").removeClass('collapsed');
				animating = false;
			});		
		}
		
		function collapse() {
			animating = true;
			$('div.collapsible').animate({
				opacity: 0,
				height: 'toggle'
			}, 400, function() {
				collapsed = true;
				$.cookie('collapsed', 'true');
				$("a#collapse-toggle").html('Show');
				$("a#collapse-toggle").addClass('collapsed');
				animating = false;
			});	
		}
		
		function expand() {
			animating = true;
			$('div.collapsible').animate({
				opacity: 1,
				height: 'toggle'
			}, 400, function() {
				collapsed = false;
				$.cookie('collapsed', 'false');
				$("a#collapse-toggle").html('Hide');
				$("a#collapse-toggle").removeClass('collapsed');
				animating = false;
			});		
		}
		
		// set collapsed to true if cookie says so
		var cookieCollapsed = $.cookie('collapsed');
		if (cookieCollapsed == "true") {
			collapsed = true;
		}
		
		
		// click the collapse/expand button
		$("a#collapse-toggle").click(function () {
		
			// !! only do the transition if it's not already animating
			if (animating == false) {
		
				// Internet Exploder
				if($.browser.msie) {
					// if expanded
					if (collapsed == false) {
						ieCollapse();
					}	
					// if collapsed
					else {
						ieExpand();
					}
				}
				// good browsers
				else {
					// if expanded
					if (collapsed == false) {
						collapse();
					}
					// if collapsed
					else {
						expand();
					}
				}
			}
			return false;
		});

	
	/** Publications - tabs **/
	
		// negate non-JS styles
		$('div#tabs div.tab').not('div#tabs div.tab:first-child').css('display', 'none');
		$('div#tabs div.tab h2').css('display', 'none');
	
		$("ul#tab-nav li a").click(function () {
			$("ul#tab-nav li a").removeClass('active');
			$(this).addClass('active');
			tabAnchor = $(this).attr("href");
			// hide tabs
			$("div#tabs div.tab").css('display', 'none');
			$("div#tabs div" + tabAnchor).css('display', 'block');
			return false;
		});
		
		
	/** Publications - disable/enable before/after select boxes **/
	/*
		// before
		$('#before').change(function () {
			if (!$('#before').attr('value') == '') {
				$('#after').attr('disabled', 'disabled');
			}
			else {
				$('#after').removeAttr('disabled');
			}
		});	
		if (!$('#before').attr('value') == '') {
			$('#after').attr('disabled', 'disabled');
		}
		else {
			$('#after').removeAttr('disabled');
		}
		
		// after
		$('#after').change(function () {
			if (!$('#after').attr('value') == '') {
				$('#before').attr('disabled', 'disabled');
			}
			else {
				$('#before').removeAttr('disabled');
			}
		});	
		if (!$('#after').attr('value') == '') {
			$('#before').attr('disabled', 'disabled');
		}
		else {
			$('#before').removeAttr('disabled');
		}
		
		*/
	
	/** Search research project database **/
	
		// collapse the fieldsets on page load
		$("div.fieldset div.collapsible").addClass('collapsed');
		$("a.filter-expanded").removeClass('filter-expanded');
		
		// click the filter button
		$("a.filter").click(function () {
			$(this).parent().next('div.collapsible').toggle('fast');
			$(this).toggleClass('filter-expanded');
			return false;
		});
	
	/** Print now button **/
	
		// only do stuff with the Print now button if we're viewing the printer-friendly version
		if ($.QueryString["style"] == "print") {
		
			// slide in the button
			$('a#print-now').animate({
				left: '231'
			}, 300, function() {
				$('a#print-now').animate({
					left: '241'
				}, 100, function() {
					$('a#print-now').animate({
						left: '231'
					}, 100, function() {
						$('a#print-now').animate({
							left: '233'
						}, 75, function() {
							$('a#print-now').animate({
								left: '231'
							}, 50, function() {
								// Animation complete.
							});
						});
					});
				});
			});
		
			// open print dialog
			$("a#print-now").click(function () {
				window.print();
				return false;
			});
		
		}
		
		
	/** Add to My Clippings **/

		
		function updateNumberOfClippings(cookieVar) {
			clippingCount = cookieVar.split(",").length - 1;
			$("a#icon-my-clippings").html('My clippings ('+clippingCount+')');
			$("div#added-to-my-clippings p").html(clippingCount + ' item(s) added to My Clippings');	
		}
		
		// function to join the three cookies together so we can work out the total number of clippings
		function joinCookies() {
			allCookies = '';
			if ($.cookie('clippingsWordpress') != null) {
				allCookies = $.cookie('clippingsWordpress');
			}
			if ($.cookie('clippingsEvidence') != null) {
				allCookies += $.cookie('clippingsEvidence');
			}
			if ($.cookie('clippingsResearch') != null) {
				allCookies += $.cookie('clippingsResearch');
			}		
			return allCookies;
		}
		
		//var clippingCount = 0;
	
		// click 'add to my clippings' button
		$("a.button-add-to-my-clippings, a.icon-add-to-my-clippings").click(function () {
				
			if (!$(this).hasClass('added-to-my-clippings')) {
				
				// change the clicked button
				$(this).addClass('added-to-my-clippings');
				$(this).html('Added to My Clippings');
				$(this).attr('title', 'Added to My Clippings');
				
				// scroll to the top
				$('html, body').animate({
					scrollTop: 0
				}, 400, function() {
				
					// stop pop-up animating
					$("div#added-to-my-clippings").stop();
					
					// fade in pop-up
					$('div#added-to-my-clippings').animate({
						opacity: 1,
						top: '28'
					}, 250, function() {
						$('div#added-to-my-clippings').animate({
							opacity: 1,
							top: '28'
						}, 1200, function() {
							// fade out popup
							$('div#added-to-my-clippings').animate({
								opacity: 0,
								top: '8'
							}, 250, function() {
								// Animation complete.
							});
						});
					});
					
				});

				/* get the cookie we want to used from data-type='?' on the link */
				dataType = $(this).attr('data-type');
				if (dataType == 'wordpress') {
					cookieToEdit = 'clippingsWordpress';
				}
				else if (dataType == 'evidence') {
					cookieToEdit = 'clippingsEvidence';
				}
				else if (dataType == 'research') {
					cookieToEdit = 'clippingsResearch';
				}
				
				/* get the current list of id's from cookie */
				if ($.cookie(cookieToEdit) != null) {
					currentCookie = $.cookie(cookieToEdit);
				}
				else {
					currentCookie = '';
				}
				
				/* get clicked clip id */
				clipId = $(this).attr('data-id');
				
				/* check if current list already has clicked id, if not, add it to list */
				if (currentCookie.indexOf(clipId) != -1) {
					// cookie has id
					newCookie = currentCookie;
				}
				else {
					// cookie doesn't have id, so add it to cookie
					newCookie = currentCookie + clipId + ',';
				}			
				
				/* create cookie */
				$.cookie(cookieToEdit, newCookie, { path: '/', expires: 300 });	

				/* update number of clippings */
				allCookies = joinCookies();
				updateNumberOfClippings(allCookies);
			
			}
			return false;
		});
		
		/* update number of clippings on page load */
		allCookies = joinCookies();
		updateNumberOfClippings(allCookies);
		

		
	/** My Clippings - remove item **/
	
		$("div.clipping a.button-remove").click(function () {
			/* fade out the clipping on the page */
			$(this).parent().fadeOut();
			
			/* figure out which cookie we're removing item from */
			dataType = $(this).attr('data-type');
			if (dataType == 'wordpress') {
				cookieToEdit = 'clippingsWordpress';
			}
			else if (dataType == 'evidence') {
				cookieToEdit = 'clippingsEvidence';
			}
			else if (dataType == 'research') {
				cookieToEdit = 'clippingsResearch';
			}			
			/* get the current list of id's from cookie */
			currentCookie = $.cookie(cookieToEdit);
			
			//alert('Current cookie: ' + currentCookie);
			
			/* get clicked clip id */
			clipId = $(this).attr('data-id');
			
			/* check if current list already has clicked id, if not, add it to list */
			if (currentCookie.indexOf(clipId + ',') != -1) {
				// remove id from cookie
				newCookie = currentCookie.replace(clipId + ",", "")
			}
			
			/* create cookie */
			$.cookie(cookieToEdit, newCookie, { path: '/', expires: 300 });	
			//alert('New cookie: ' + newCookie);
			
			/* update number of clippings */
			allCookies = joinCookies();
			updateNumberOfClippings(allCookies);
				
			return false;
		});
	
	/** Resource for researchers **/
	
		var buttonSliderText = "Open"
	
		// collapse the collapsibles on page load
		$("#resource-for-researchers div.collapsible").addClass('collapsed');
		$("#resource-for-researchers h2 a span").addClass('closed');
		$("#resource-for-researchers a.button-slider span").html('Open');
		
		// click the slider button
		$("a.button-slider").click(function () {
			if($.browser.msie){
				$(this).parent().next('div.collapsible').toggleClass('collapsed');
			}
			else {
				$(this).parent().next('div.collapsible').slideToggle('fast');
			}
			
			$(this).children('span').toggleClass('closed');
			if ($(this).children('span').text() == "Close") {
				$(this).children('span').text("Open");
			}
			else {
				$(this).children('span').text("Close");
			}
			return false;
		});	
		
		
	/** JS to level up headings on landing pages **/
	
		var maxheight = 0;
		$("#features").each(		
			function(){
				var count = 0;
				var times = 0;
				$(this).find('h2').each(	
				function(index){	
						if($(this).height() > maxheight) { maxheight = $(this).height() };
						
						if(count<2 && (($("#features").find('h2').length)-1 > (index))) {
							count++;
							
						}
						else {
							//alert('last, count:'+count);
							if(count==0)
							{
								var item1 = count+(times*3);
								$('#features').find('h2:eq('+item1+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');			
							}
							else if(count==1) {
								var item1 = (count-1)+(times*3);
								var item2 = count+(times*3);	
								$('#features').find('h2:eq('+item1+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');
								$('#features').find('h2:eq('+item2+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');			
							}
							else {
								var item1 = (count-2)+(times*3);
								var item2 = (count-1)+(times*3);
								var item3 = count+(times*3);							
								$('#features').find('h2:eq('+item1+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');
								$('#features').find('h2:eq('+item2+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');
								$('#features').find('h2:eq('+item3+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');				
							}					
							times++;
							count = 0;
							maxheight = 0;
						}
					}
				);
				}
		);
		
	/** JS to level up headings on landing pages **/
		var maxheight = 0;
		$(".features").each(		
			function(){
				var count = 0;
				var times = 0;
				$(this).find('h2').each(	
				function(index){	
						if($(this).height() > maxheight) { maxheight = $(this).height() };
						
						
						
						if(count<2) {
							count++;
						}
						else {
							var item1 = (count-2)+(times*3);
							var item2 = (count-1)+(times*3);
							var item3 = count+(times*3);	
							$('.features').find('h2:eq('+item1+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');
							$('.features').find('h2:eq('+item2+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');
							$('.features').find('h2:eq('+item3+')').attr('style','min-height: '+maxheight+'px;height:auto!important;height:'+maxheight+'px');
							times++;
							count = 0;
							maxheight = 0;
						}
					}
				);
				}
		);
		
	/* Edit project page - button text toggle */
		
		if ($('#project-edit-form').length != 0) {
			
			function changeButtonText() {
				if ($('#Confirmed').attr('checked')) {
					buttonText = 'Submit project';
				}
				else {
					buttonText = 'Save project';
				}		
				$('#project-edit-submit').val(buttonText);
				$('#project-edit-submit').attr('title', buttonText);
			}
			
			changeButtonText();
			
			$('#Confirmed').change(function () {
				changeButtonText();
			});
			
		}
		
			if ($('#project-add-form').length != 0) {
			
			function changeButtonText() {
				if ($('#Confirmed').attr('checked')) {
					buttonText = 'Submit project';
				}
				else {
					buttonText = 'Save project';
				}		
				$('#project-edit-submit').val(buttonText);
				$('#project-edit-submit').attr('title', buttonText);
			}
			
			changeButtonText();
			
			$('#Confirmed').change(function () {
				changeButtonText();
			});
			
		}	
		
	/* Reset button */
	
	/* $('input[type=reset]').click(function () {
		window.location = '?';
	}); */
	
	
	$('div.collapsible input[type=reset]').click(function (e) {
		e.preventDefault();
		$('form#filter-publications input:not(.submit)').each(function() {
			inputType = $(this).attr('type');
			$(this).removeAttr('checked');
			if (inputType == 'text') {
				$(this).attr('value', '');
			}
		});
		
		$('form select option').each(function() {
			$(this).removeAttr('selected');
		});
		
		$('form select').val('');
	}); 
	
	
	
		
});
