var $hash;
var _contact; // Contact option

$(document).ready(function() {
	// Yay, we're in business
	$('html').removeClass('no-js');
	$hash = window.location.hash;
	
	//Add carousels 
	init_carousels();

	// Run home slideshows
	rotatePics(1);

  // ie6 and below message   
  if (less_than_ie7 === true) {
		var $alert_txt = '<div id="ie"><div><p>Your version of Internet Explorer is <strong>more than 10 years old</strong>. Its many shortcomings by today’s standards make it impractical for us to show you this site as we would wish. Unfortunately, you can’t upgrade to Internet Explorer 9 (which requires Windows Vista or later), but you can <a href="http://html5forxp.com/" target="_blank" title="More capable browser options for Windows XP">use another browser</a> so that this site (and many others) will work much better for you. </p></div></div>';
		
		$('#top').before($alert_txt);

		$('*:first-child').addClass('first_child');
		
		$('#ie p').append(' <a class="hide" href="#" title="Note: this message will reappear each time you load this page">Hide this message for now</a>.');
		
		// var $ypx = $('#ie div').height() + 'px';
		// $('#ie').css('margin-bottom',$ypx);
		
		$('#ie .hide').click(function(e) {
			e.preventDefault();
			$('#ie').hide();
		});
	}
	
	// Columnize
	$('.no-csscolumns .cols2').columnize({ columns: 2 });
	$('.no-csscolumns .cols3').columnize({ columns: 3, lastNeverTallest: true });
  

	// Top links on ToC
	$('#toc .h4 span').wrap('<a href="#top" title="Go up top" />');

  // Local scroll settings 
  $.localScroll({
    event:'click', //on which event to react
    axis:'y',
    offset:-45,
    duration:500,
    hash:true,
		stop:true      //avoid queuing animations
  });
  
	// Bar
	$('#bar').click(function() {
		$.scrollTo('#top','fast');
	});
	
	// Scroll follow
	scroll_follow();
	
	// Contact page stuff

		// Create contact option links
		contact_links();
		
		// Form handling
		form_hinted();
		form_guidance();
	
		// Google map
		if ($('#map_canvas').length) {
			get_gmap();
		}
		
	// Go hash on load
	if ($hash.length > 1) {
		if ($hash == '#registrar'
				|| $hash == '#pa'
				|| $hash == '#bursar'
				|| $hash == '#matron'
				|| $hash == '#boarding-staff'
				|| $hash == '#senco') {
			_contact = $hash;
			
			$('.contact ' + _contact).addClass('active').show();
			scroll_follow();
			$.scrollTo('#top',0);
		}
		else {
			$.scrollTo($hash,500, {offset: {top:-45, left:0} });
		}
	}
	
});



function form_hinted() {	  
  $('.hinted input.text, .hinted textarea').each(function() {
			$(this)
				.val($(this).attr('title'))
				.data('default', $(this).val())
				.addClass('inactive')
				.focus(function() {
					$(this).removeClass('inactive');
					if($(this).val() == $(this).data('default') || '') {
						$(this).val('');
					}
				})
				.blur(function() {
					var default_val = $(this).data('default');
					if($(this).val() == '') {
						$(this).addClass('inactive');
						$(this).val($(this).data('default'));
					}
				});
  });
}

function form_guidance() {	  
  $('.guided input.text, .guided select').each(function() {
		$(this).focus(function() {
			$(this).next('.guide').addClass('active');
		})
		.blur(function() {
			$(this).next('.guide').removeClass('active');
		});
  });
}


function toggle_css() {
	var stylesheets = $('link[rel="stylesheet"]');
	$('#toggle_css span').text('');
	
	if ($(this).hasClass('enabled')) {
		stylesheets.each(function(i) {
			stylesheets[i].disabled = true;
		});
		
		$('html').removeClass('wf-active');
		$(this).removeClass('enabled')
		       .addClass('disabled')
		       .text('Turn styling back on')
		       .attr('title','');
	}
	else {
		stylesheets.each(function(i) {
			stylesheets[i].disabled = false;
		});
		
		$('html').addClass('wf-active');
		$(this).removeClass('disabled')
		       .addClass('enabled')
		       .text('Remove most site styling')
		       .attr('title','You may re-enable styling here afterwards');
	}
	
	return false;
}


// Scroll Follow
function scroll_follow() {
	if ( $('#toc').length ) {
		/*
		var $debug = $('<div id="debug" />');
		$('body #debug').remove();
		$('body').append($debug);
		*/
		
		// Get #toc and gap heights
		var $toc_bottom = $('#toc .contents').height() + $('#toc').offset().top;
		var $win_height = $(window).height();
		var $gap = $win_height - $toc_bottom -5;
		var $foot_top = $('.foot').offset().top;
		if ( $foot_top > $toc_bottom || $('.body').hasClass('contact') ) {
			$('body').addClass('fixed');
		}
		
		$(window).scroll(function (event) {
	
			// What the y position of the scroll is
			var $y = $(this).scrollTop();
			var $foot_visible = $y + $win_height - $foot_top;
	
			// $debug.text('Footer visible = ' + $foot_visible + '; Gap = ' + $gap);
	
			// Check how close the footer is and act accordingly
			if ($foot_visible > $gap || $gap < 5) { 
				$('body').removeClass('fixed');
			}
			else {
				$('body').addClass('fixed');
			}
		});
	}
}


function get_gmap() {
	// Set coordinates	
	var $center    = new google.maps.LatLng(50.862, -0.6374);
	var $tricenter = new google.maps.LatLng(50.847, -0.7);
	var $bicenter  = new google.maps.LatLng(50.851, -0.6388);
	var $slindon   = new google.maps.LatLng(50.86793, -0.6374);
	var $barnham   = new google.maps.LatLng(50.831, -0.6402);
	var $cft       = new google.maps.LatLng(50.8411, -0.778);
	
	var $map_options = {
		zoom: 14,
		center: $center,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById('map_canvas'), $map_options);
	
  var $mk_slindon = new google.maps.Marker({
		position: $slindon, 
		map: map, 
		title: 'Slindon College'
  });
  
  var $mk_barnham = new google.maps.Marker({
		position: $barnham, 
		map: map, 
		title: 'Barnham rail station'
  });
  
  var $mk_cft = new google.maps.Marker({
		position: $cft, 
		map: map, 
		title: 'Chichester Festival Theatre car park'
  });
  
  var $lnk_barnham = $('#barnham').wrapInner('<a href="#" />');
  var $lnk_cft     = $('#cft').wrapInner('<a href="#" />');
  
  $lnk_cft.attr('title','Show pickup point on satellite map').click(function() {
  	map.setCenter($cft);
  	map.setZoom(17);
		map.setMapTypeId(google.maps.MapTypeId.HYBRID);
  	return false;
  });
  
  $lnk_barnham.attr('title','Show on map relative to Slindon').click(function() {
  	map.setCenter($bicenter);
  	map.setZoom(13);
  	return false;
  });
  
}

function contact_links() {
	$('.contact .options span').each(function() {
		$option = $(this).attr('class');
		$(this).wrapInner('<a href="#" />');
		$(this).find('a').attr('href','#'+$option).click(function() {
			_contact = $(this).attr('href');
			show_contact();
			return false;
		});
	});
	$('.contact #toc .option').hide();
}

function show_contact() {
	if ( $('.contact ' + _contact).hasClass('active') ) {
		return false;
	}
	else {
		if ( _contact == '#registrar' || _contact == '#pa' ) {
			$('.contact #toc .gen').animate({opacity: 1});
		}
		else {
			$('.contact #toc .gen').animate({opacity: 0.5});
		}
		
		if ( $('.contact #toc .active').length ) {
			$('.contact #toc .active').removeClass('active').slideUp(function() {
				$('.contact ' + _contact).addClass('active').slideDown(400,function() {
					scroll_follow();
				});
			});
		}
		else {
			$('.contact ' + _contact).addClass('active').slideDown(400,function() {
				scroll_follow();
			});
		}
		return false;
	}
}

function rotatePics(currentPhoto) {
  var numberOfPhotos = $('.slideshow img').length / 2;
  currentPhoto = currentPhoto % numberOfPhotos;
	
  $('.slideshow img').eq(currentPhoto).fadeOut(400,function() {
		// re-order the z-index
    $('.slideshow img').each(function(i) {
      $(this).css(
        'zIndex', ((numberOfPhotos - i) + currentPhoto) % numberOfPhotos
      );
    });
    $(this).show();
    setTimeout(function() {rotatePics(++currentPhoto);}, 6000);
  });

}

// Adds carousels
function init_carousels() {
  $('.carousel').wrap('<div class="carousel_wrapper" />');
  
	$('.carousel_wrapper').each(function() {
		
		// Check to see if the carousel should auto run
		var $autorun = null;
		if ( $(this).find('.carousel').hasClass('autorun') ) {
			$autorun = 4000;
		}
		
		// Check if there are go buttons 
		var $goto = null;
		if ( $('.carousel_go').length ) {
			$goto = [];
			$('.carousel_go a').each(function(i) {
				$goto[i] = '.carousel_go .' + $(this).attr('class');
			});
		}
		
		// Add a number guide
		var $cunits = $(this).find('.cunit').length;
		$(this).find('.cunit').each(function(i) {
			var $folio = $('<div class="folio" />')
									 	.html( '<a href="#" class="next" title="Next">' + (i+1) + ' of ' + $cunits + '</a>' );
			$(this).append($folio);
		});
		
		// Get the first .unit so we can check its OOCSS width
			// NB: expects all .units to be the same width!
		var $first_unit = $(this).find('.cunit:first');
		var $nv; // number we're going to make visible at a time
		
		if ( $first_unit.hasClass('size1of1') ) {
			$nv = 1;
		}
		else if ( $first_unit.hasClass('size1of2') ) {
			$nv = 2;
		}
		else if ( $first_unit.hasClass('size1of3') ) {
			$nv = 3;
		}
		else if ( $first_unit.hasClass('size1of4') ) {
			$nv = 4;
		}
		else if ( $first_unit.hasClass('size1of5') ) {
			$nv = 5;
		}
		else if ( $first_unit.hasClass('size1of6') ) {
			$nv = 6;
		}
		else {
			$nv = null; // Don't run the carousel!
		}
		
		if ($nv != null) {
			// Add controls
			var $controls = $('<div class="controls" />');
			var $next = $('<a href="#" class="next" title="Next">Next &rarr;</a>');
			$controls.append($next);
			$next.before('<a href="#" class="prev" title="Previous">&larr; Previous</a>');
			$(this).before($controls);
			
			// jCarousel Lite oocss
			$(this).jCarouselLite({
				btnNext: '.next',
				btnPrev: '.prev', 
				btnGo: $goto,
				visible: $nv,
				scroll: 1,
				speed: 800,
				circular: true,
				auto: $autorun
			});
		}
		
		// Disabled links
		$('.disabled').click(function() {
			return false;
		});
		
	});
}

/* Dev only
Disable non-functional links
$('a[href="foo"], a[href="/foo"], a[href="http://slindoncollege.co.uk/foo"]').click(function() {
	alert('Just a dummy link for now!');
	return false;
});
*/



