(function($){
  var cache = [];
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

$(document).ready(function(){
	
	// Add tips to input boxes
	
	$("input[data-tip]").focus(function(){
		if( $(this).hasClass("empty") ){
			$(this).removeClass("empty").val("");
		}
	}).blur(function(){
		if( $(this).val() == "" ){
			$(this).addClass("empty").val( $(this).attr("data-tip") );
		}
	}).blur();
	
	$("form").submit(function(){
		$(this).find("input.empty").val("");
	});
	
	// Date picker
	
	var datepicker_options = {
		dateFormat: "dd/mm/yy",
		changeYear: true,
		changeMonth: true,
		yearRange: 'c-150:c+0',
		monthNamesShort: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
		onSelect: function(dateText, inst){
			$(this).removeClass("empty");
		}
	};
	
	// Apply Online
	
	$("#f_apply_online_date_of_birth, #f_order_course_guide_date_of_birth").datepicker( datepicker_options );
	
	var course_options = [1,2,3];
	for( i in course_options ){
		(function(){
			var course_option_no = course_options[i];
			var subject_area_select = $("#f_apply_online_subject_area"+course_option_no);
			subject_area_select.change(function(){
				var select = $("#f_apply_online_course"+course_option_no);
				var select_store = select.next("select");
				select.find("option.option").appendTo( select_store );
				select_store.find("option.optiongroup_"+$(this).val()).appendTo( select );
				select.val( select.find("option.selected").removeClass("selected").attr("value") );
				if( select.find("option[selected]").length == 0 ){ select.val(""); }
				return false;
			}).change();
			
			if( subject_area_select.val() == "" ){
				subject_area_select.closest("div.field").hide().next("div.field").hide();
			}
			
		})();
		
	}
	
	$("#add_another_course").click(function(){
		$(".chooseacourse:hidden:first").show().prev("div.field").show();
		if( $(".chooseacourse:hidden").length == 0 ){
			$(this).closest("div.field").hide();
		}
		return false;
	}).click();
	
	$("a.remove_course").click(function(){
		$(this).closest("div.field").hide().prev("div.field").hide().find("select").val("").change();
		$("#add_another_course").closest("div.field").show();
		return false;
	});
	
	// Home slideshow
	
	var homeSlideshowAnimating = false;
	
	var homeSlideshowAuto = setInterval(function(){
		
		if( $("#homeSlideshowNav a.selected").closest("li").next("li").length == 1 ){
			homeSlideshowTab( $("#homeSlideshowNav a.selected").closest("li").next("li").children("a") );
		}else{
			homeSlideshowTab( $("#homeSlideshowNav a:first") );
		}
		
	}, 4500);
	
	$("#homeSlideshowNav a").click(function(){
		clearInterval( homeSlideshowAuto );
		homeSlideshowTab( $(this) );
		return false;
	});
	
	function homeSlideshowTab( tab_link ){
		
		if( homeSlideshowAnimating == true ){
			return false;
		}
		
		homeSlideshowAnimating = true;
		
		$("#homeSlideshowNav a.selected").removeClass("selected");
		
		tab_link.addClass("selected");
		
		$("#homeSlide_"+tab_link.attr("data-slide-id")).appendTo("#homeSlideshowContent ul");
		
		$("#homeSlideshowContent li:last").fadeIn( 500, function(){
			homeSlideshowAnimating = false;
		});
		
	}
	
	homeSlideshowTab( $("#homeSlideshowNav a:first") );
	
	// Facilities slides
	
	var facilitySlideshowAnimating = false;
	
	var facilitySlideshowAuto = setInterval(function(){
		facilitySlideshowSlide();
	}, 5000);
	
	$("#facilitySlideshowNext").click(function(){
		
		clearInterval( facilitySlideshowAuto );
		
		facilitySlideshowSlide();
		
		return false;
		
	});
	
	function facilitySlideshowSlide(){
		
		if( facilitySlideshowAnimating == true ){
			return false;
		}
		
		facilitySlideshowAnimating = true;
		
		$("#topperFacilities ul").animate({
			left: "-260px"
		}, 500, "swing", function(){
			
			$("#topperFacilities ul").css("left", "0").find("li:first").appendTo("#topperFacilities ul");
			
			facilitySlideshowAnimating = false;
			
		});
		
	}
	
	// Ajax - Go Back
	
	$("a.go_back").live("click",function(){
		
		$(this).closest("div.submit_status").fadeOut( 200 ).prev("div.fields").fadeIn( 200 );
		
		return false;
		
	});
	
	// Person - Email me
	
	$("a.email_me_button").click(function(){
		
		var email_wrapper = $(this).closest("div.person_info").find("div.email_me_wrapper");
		
		if( email_wrapper.height() > 0 ){
			email_wrapper.stop().animate({
				"height": "0"
			}, 400, "swing");
		}else{
			email_wrapper.stop().animate({
				"height": "224px"
			}, 400, "swing");
		}
		
		return false;
		
	});
	
	$("form.email_me").submit(function(){
		
		var form = $(this);
		
		form.height( form.height() );
		
		form.children("div.fields").fadeOut( 200 ).next("div.submit_status").html('<p class="status status_alert">Sending message, please wait...</p>').fadeIn( 200 );
		
		$.ajax({
			type: form.attr('method'),
			url: form.attr('action'),
			data: form.serialize(),
			success: function( json, textStatus, XMLHttpRequest ){
				
				try{
					var response = jQuery.parseJSON( json );
				}catch(e){
					form.children("div.submit_status").html('<p class="status status_error">Error sending message, please try again.<br /><br /><a href="" class="go_back">Go Back</a></p>').fadeIn( 200 );
					return;
				}
				
				if( response['success'] == true ){
					form.children("div.submit_status").html('<p class="status status_success">Message sent!</p>').fadeIn( 200 );
				}else{
					form.children("div.submit_status").html('<p class="status status_error">'+response['error']+'<br /><br /><a href="" class="go_back">Go Back</a></p>').fadeIn( 200 );
				}
				
			},
			error: function(){
				form.children("div.submit_status").html('<p class="status status_error">Error sending message, please try again.<br /><br /><a href="" class="go_back">Go Back</a></p>').fadeIn( 200 );
			}
		});
		
		return false;
		
	});
	
	// Link thumbs
	
	$(".links a").hover(function(){
		
		if( $(this).attr("data-thumb") ){
			
			var width = $(this).width();
			var x = $(this).position().left + ( width / 2 ) - 84;
			var y = $(this).position().top - 144;
			
			$('<div class="thumb"><img src="'+$(this).attr("data-thumb")+'" /><span></span></div>').insertBefore(this).css( "top", y ).css( "left", x );
			
		}
		
	},function(){
		
		$(this).prev("div.thumb").remove();
		
	});
	
	// Photo gallery
	
	$("a[rel=gallery]").live("click",function(){
		$.colorbox({
			href: $(this).attr("href"),
			title: $(this).attr("title")
		});
		return false;
	});
	
	var galleryTransitioning = false;
	
	function show_photo( new_pic ){
		var width = new_pic.width();
		var height = new_pic.height();
		new_pic.css("left", Math.floor( (522 - width) / 2 ) )
			.css("top", Math.floor( (522 - height) / 2 ) );
		
		new_pic.fadeTo( 200, 1, function(){
			galleryTransitioning = false;
		});
		
		new_pic.find("span.caption").width( width - 100 );
		
	}
	
	$("#gallery_thumbs a").click(function(){
		
		if( $("#gallery_photo_outer").height() == 0 ){
			$("#gallery_photo_outer").animate({ height: "524px" }, 400, "swing");
		}
		
		if( galleryTransitioning == true ){
			return false;
		}
		
		galleryTransitioning = true;
		
		var new_pic = $('<a href="'+$(this).attr("data-full")+'" rel="gallery" title="'+$(this).attr("data-caption")+'"><img src="'+$(this).attr("href")+'" /><span class="zoom"></span><span class="corners"><span class="c1"></span><span class="c2"></span><span class="c3"></span><span class="c4"></span></span></a>').prependTo("#gallery_photo").css("opacity", "0");
		
		if( $(this).attr("data-caption") ){
			new_pic.append('<span class="caption">'+$(this).attr("data-caption")+'<span class="leftbit"></span><span class="rightbit"></span></span>');
		}
		
		$("#gallery_photo a:eq(1)").fadeTo( 200, 0, function(){
			$(this).remove();
		});
		
		if( new_pic.children("img").attr("complete") ){
			show_photo( new_pic );
		}else{
			new_pic.children("img").load(function(){
				show_photo( new_pic );
			});
		}
		
		return false;
		
	});
	
	$(window).load(function(){
		$("#gallery_thumbs a").each(function(){
			$.preLoadImages( $(this).attr("href") );
		});
	});
	
	var thumbsSliding = false;
	
	$("#gallery_prev").click(function(){
		if( thumbsSliding == true ){ return false; }
		thumbsSliding = true;
		$("#gallery_thumbs li:last").prependTo("#gallery_thumbs");
		$("#gallery_thumbs").css("left","-100px").animate({ left: "0" }, 250, "swing", function(){
			thumbsSliding = false;
		});
		return false;
	});
	
	$("#gallery_next").click(function(){
		if( thumbsSliding == true ){ return false; }
		thumbsSliding = true;
		$("#gallery_thumbs").animate({ left: "-100px" }, 250, "swing", function(){
			$("#gallery_thumbs").css("left","0").children("li:first").appendTo("#gallery_thumbs");
			thumbsSliding = false;
		});
		return false;
	});
	
	// College info panel
	
	$("#button_college_information").click(function(){
		$("#topCollegeInfo").slideToggle( 500 );
		return false;
	});
	
	// Tweet!
	
	if( $(".twitter-share-button").length > 0 ){
		$('head').append('<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>');
	}
	
	// People
	/*
	$("div.person").each(function(){
		
		var content = $(this).find(".content");
		var height = content.height();
		
		if( height > 120 ){
			content.height( 120 );
			$(this).find("a.read_more").click(function(){
				$(this).remove();
				content.animate({
					"height": height+"px"
				},400,"swing");
				return false;
			});
		}else{
			$(this).find("a.read_more").remove();
		}
		
	});
	*/
	
});
