$(document).ready(function() {
   
	$("body").addClass("js");
	var ie6 = $.browser.msie && $.browser.version == "6.0";
	
	// if loaded in iframe, load popup styles
	var inFrame = (window.location != window.parent.location) ? true : false;
	if(inFrame) {
		// add popup styles
		$("head").append('<link rel="stylesheet" href="/media/web/css/popup.css" type="text/css" media="all" />');
		if($.cookie("side") == "true") {
			$("head").append('<link rel="stylesheet" href="/media/web/css/popup-side.css" type="text/css" media="all" />');
		}
		// make links external
		$("a[href^='http']").attr("target", "_blank");
	}

	$("#faqs").accordion({
		"header": "h3, h4",
		"autoHeight": false,
		"active": false,
		"collapsible": true
	});
	
	$("#rotate .photos").cycle({
		speed: 3000,
		timeout: 5000
	});
	
	$(".image-rotate").cycle({
		speed: 2000,
		timeout: 4000
	});
	
	
	/*$(".feature-accom div div").cycle({
		speed: 1000,
		timeout: 3000
	});*/
	
	$("a[rel=gallery]").fancybox({
		titlePosition: "outside",
		centerOnScroll: true,
		overlayOpacity: 0.8,
		overlayColor: "#000000",
		padding: 15
	});
	
	
	$(".cando-link").fancybox({
		centerOnScroll: true,
		overlayOpacity: 0.8,
		overlayColor: "#000000",
		padding: 15,
		type: "inline"
	});
	
	
	menuOpen = function() {
		if($(this).children(".menu").length > 0) {
			$(this).addClass("over");
			//$("#frame-inner, #subnav li").css({"opacity": 0.2});
		}
	}
	menuClose = function() {
		$(this).removeClass("over");
		//$("#frame-inner, #subnav li").css({"opacity": 1, "filter": "none"});
	}
	
	if(!ie6) {
		$("#nav > li").hoverIntent({
			over: menuOpen,
			out: menuClose,
			timeout: 0
		});
	}
	

	
	



	// staff images
	$("#staff li").each(function() {
		contact = ""
		img = $(this).find("img");
		cls = "s" + $(this).prevAll("li").length;
		if($(this).find("a").attr("href") != "#") {
			contact = '<p class="contact">Click on my photo to contact me.</p>';
		}
		$(this).parent().append('<div class="' + cls + '"><span></span><p class="title"><strong>' + img.attr("alt").split(", ")[0] + '</strong> ' + img.attr("alt").split(", ")[1] + '</p><p>' + img.attr("title") + '</p>' + contact + '</div>');
		img.removeAttr("title").removeAttr("alt");
	});
	$("#staff li a").click(function() {
		if($(this).attr("href") == "#") { return false; }
	});
	$("#staff li:not(.blank)").mouseenter(function() {
		index = $(this).prevAll("li").length;
		$(this).parent().find("div:eq(" + index + ")").show();
	});
	$("#staff li:not(.blank)").mouseleave(function() {

		index = $(this).prevAll("li").length;
		$(this).parent().find("div:eq(" + index + ")").hide();
	});
	
	$("#tabs a[title]").tooltip({ predelay: 200, effect: "fade", fadeInSpeed: 100, fadeOutSpeed: 100 });


	$("#search").focus(function() {
		if($(this).val()=="Search...") { $(this).val(""); }
	}).blur(function() {
		if($(this).val()=="") { $(this).val("Search..."); }
	});



	// staff videos
	$(".video a").click(function() {
		$(this).parent().html('<div id="video-container-staff"></div>');
		url = $(this).attr("class").split(",");
		jwplayer("video-container-staff").setup({
		    flashplayer: "/media/web/video/player.swf",
		    file: "http://video.english-in-chester.co.uk/" + url[0] + ".mp4",
			image: "/media/web/video/" + url[0] + "-button.jpg",
		    autostart: "true",
		    controlbar: "over",
			stretching: "none",
		    width: url[1],
		    height: url[2],
			skin: "/media/web/video/simple.zip"
		  });
		return false;
	});
	
	
	$("#videos a").click(function() {
		cont = $("#rotate");
		// LOAD VIDEO
		if(!$(this).parent().hasClass("on") && !cont.hasClass("loading")) {
			// parse data from url
			url = $(this).attr("class").split(",");
			// record as loading
			cont.addClass("loading");
			// remove any existing video players and containers
			try {
				jwplayer("video-container").remove();
			} catch(err) {}
			cont.children("#video-container").remove();
			// pause photos, then fade out
			cont.children(".photos").cycle("pause").fadeOut(500, function() {
				// resize container
				cont.animate({ height: url[2] }, 500, function() {
					// when done, add video container and load into it
					cont.append('<div id="video-container"></div>');
					jwplayer("video-container").setup({
					    flashplayer: "/media/web/video/player.swf",
					    file: "http://video.english-in-chester.co.uk/" + url[0] + ".mp4",
					    autostart: "true",
					    controlbar: "over",
						stretching: "none",
					    width: url[1],
					    height: url[2],
						skin: "/media/web/video/simple.zip",
						events: {
							onReady: function() {
								cont.removeClass("loading");
							}
						}
					  });
				});
			});
			// change menu
			$(this).parent().parent().children("li.on").removeClass("on");
			$(this).parent().addClass("on");
		}
		// BACK TO PHOTOS
		if($(this).parent().hasClass("on") && !cont.hasClass("loading")) {
			// record as loading
			cont.addClass("loading");
			// remove video player and container
			try {
				jwplayer("video-container").remove();
			} catch(err) {}
			cont.children("#video-container").remove();
			// resize container
			cont.animate({ height: "270px" }, 500, function() {
				// fade back in photos and resume
				cont.children(".photos").fadeIn(500, function() {
					$(this).cycle("resume");
					cont.removeClass("loading");
				})
			});
			// change menu
			$(this).parent().parent().children("li.on").removeClass("on");
		}
		return false;
	});
	
	
	
	
	if(!ie6) {
		$(".apply .description a").click(function() {
			href = $(this).attr("href");
			// set cookie to show/hide side column (persists across form posts e.g. placement test)
			if(href.indexOf("?side") == -1) {
				$.cookie("side", null, { path: "/" });
			} else {
				$.cookie("side", "true", { path: "/" });
			}
			w = $(this).attr("class").split("-")[0];
			h = $(this).attr("class").split("-")[1];
			$.fancybox({
				enterOnScroll: true,
				overlayOpacity: 0.8,
				overlayColor: "#000000",
				type: "iframe",
				href: href,
				width: parseInt(w),
				height: parseInt(h),
				padding: 15
			});
			return false;
		});
	} else {
		$(".apply .description a").attr("target", "_blank");
	}
	
	
	/*
	$(".apply .description a").fancybox({
		centerOnScroll: true,
		overlayOpacity: 0.8,
		overlayColor: "#000000",
		type: "iframe",
		width: ,
		height: $(this).attr("class").split("-")[1],
		padding: 15
	});
	*/
	
	

	$(".visas-button-eea").live("click", function(e) {
		$.fancybox({
			centerOnScroll: true,
			overlayOpacity: 0.8,
			overlayColor: "#000000",
			content: "<div class=\"eea\"><p><strong>European Economic Area countries are:</strong> Austria, Belgium, Bulgaria, Cyprus, Czech Republic, Denmark, Estonia, Finland, France, Germany, Greece, Hungary, Iceland, Ireland, Italy, Latvia, Liechtenstein, Lithuania, Luxembourg, Malta, Netherlands, Norway, Poland, Portugal, Romania, Slovak Republic, Slovenia, Spain, Sweden and the UK.</p><p class=\"last\"><strong>Switzerland</strong> is not a member but has agreements with the EEA.</p></div>",
			width: 400,
			height: 125,
			autoDimensions: false,
			padding: 15
		});
		return false;
	});
	$(".visas-button-visa").live("click", function(e) {
		$.fancybox({
			centerOnScroll: true,
			overlayOpacity: 0.8,
			overlayColor: "#000000",
			type: "iframe",
			href: "http://www.ukba.homeoffice.gov.uk/policyandlaw/immigrationlaw/immigrationrules/appendix1/",
			width: 960,
			height: 700,
			padding: 15
		});
		return false;
	});
	
	
	// lessons
	$("body:not(.placement) form.lesson").submit(function() {
		form = $(this);
		$.post("/ajax/lesson/", $(this).serialize(), function(data) {
			data = $.parseJSON(data);
			form.find("td.correct span").remove();
			score = 0;
			for(var question in data) {
				if(data[question].result == "true") {
					form.find("tbody tr:eq(" + question + ") td.response").html('<img src="/media/web/img/layout/icon-tick.png" alt="Correct" />');
					score++;
				}
				else {
					response = form.find("tbody tr:eq(" + question + ") td.response");
					if(response.hasClass("response-column")) {
						response.html('<img src="/media/web/img/layout/icon-cross.png" alt="Incorrect" />');	
					} else {
						response.html('<img src="/media/web/img/layout/icon-cross.png" alt="Incorrect" />');
						response.parent().find(".correct").append('<span><span>' + data[question].correct + '</span></span>')
					}
				}
			}
			form.find(".submit-row span").html("Your score: <strong>" + score + "/" + form.find("input[name='questions']").val() + "</strong>").show();
			form.addClass("lesson-marked");
		});
		//console.log($(this).serialize)
		return false;
	});
	
	$("body:not(.enrol-index) #courses li, .home .box-brochure").click(function() {
		window.location.href = $(this).find("a:first").attr("href");
	});
	



	
	// center images on our students
	$(".our-students #courses > li").each(function() {
		i = $(this).children("img");
		o = Math.floor(($(this).height() + 32 - 163) / 2);
		i.css({"top": o + "px"});
	});
	
	
	
	
	// add captions to first period
	/*
	$("#] li:first img").each(function() {
		$(this).after("<span>" + $(this).attr("alt") + "</span>");
	});
	// init cycle for all periods
	$("#history li:first .images").cycle({
		speed: 1500,
		timeout: 4000,
		slideExpr: "div"
	});
	// pause all but first
	$("#history li:gt(0) .images").cycle("pause");
	*/
	// switches
	$("#history-switch a").click(function() {
		$(this).blur();
		if(!$(this).parent().hasClass("on")) {
			// pause all initd cycles
			$("#history li .images").cycle("pause");
			// swap periods
			clicked = $(this).parent().attr("class");
			slide = $("#history li." + clicked);
			$("#history li.on").removeClass("on");
			slide.addClass("on");
			$("#history-switch li.on").removeClass("on");
			$(this).parent().addClass("on");
			// slide arrow
			bgpos = "";
			switch(clicked) {
				case "roman": bgpos = "-907px 0"; break;
				case "middle": bgpos = "-751px 0"; break;
				case "sixteen": bgpos = "-595px 0"; break;
				case "georgian": bgpos = "-439px 0"; break;
				case "victorian": bgpos = "-283px 0"; break;
				case "modern": bgpos = "-127px 0"; break;
			}
			$("#history-switch-container").animate({
				backgroundPosition: bgpos
			}, 500);
			// load images if needed
			if(!slide.hasClass("loaded")) {
				toLoad = $.map(slide.find(".images div"), function(i) {
					return "/media/web/img/history/" + clicked + "-" + (($(i).prevAll().length)+1) + ".jpg";
				});
				$.preLoadImages(toLoad, function() {
					// when images are loaded, add them
					slide.find(".images div").each(function(i) {
						alt = $(this).text();
						$(this).html('<img src="' + toLoad[i] + '" alt="' + alt + '" /><span>' + alt + '</span>');
					});
					// init cycle
					slide.find(".images").cycle({
						speed: 3000,
						timeout: 5000,
						slideExpr: "div"
					});
					// record as loaded
					slide.addClass("loaded");
				});				
			} else {
				// cycle will already be initd from loading, so resume it
				slide.find(".images").cycle("resume");
			}
			// init cycle, or resume it if already initd
			
			// pause other cycles, start this one
			//$("#history li .images").cycle("pause");
			//$("#history li." + clicked + " .images").cycle("resume");
		}
		return false;
	});
	
	$("#history-switch a:first").trigger("click");
	
	

/*
	$(".rolling input[type='image']").click(function() {
		console.log("hi");
		$(this).blur();
		form = $(this).parents(".rolling");
		$(".ajax").remove();
		form.after('<p class="ajax">Checking availability...</p>');
		// validate fields are completed
		
		course = form.find("input[name='course']").val();
		variant = $(this).closest("tr").find("input[name='variant']").val();
		index = $(this).closest("tr").find("input[name='index']").val();
		start = $(this).closest("tr").find("select[name='start']").val();
		weeks = $(this).closest("tr").find("select[name='weeks']").val();
		if(index == undefined) { index = 0; }
		if(start == 0 || weeks == 0) {
			$(".ajax").remove();
			form.after('<p class="ajax">Please select a start date and number of weeks.</p>');
		} else {
			// everything is OK, do ajax validation
			$.post("/ajax/rolling/", { "course": course, "variant": variant, "start": start, "weeks": weeks }, function(data) {
				if(data == "OK") {
					// image inputs are not sent by jquery, so put it in a hidden field (variant and index are needed on some courses)
					form.append('<input type="hidden" name="variant" value="' + variant + '" />');
					form.append('<input type="hidden" name="index" value="' + index + '" />');
					form.submit();
				} else {
					$(".ajax").remove();
					form.after('<p class="ajax">' + data + '</p>');
				}
			});
		}
		return false;
	});
*/




});



/*
window.onerror = function (err, file, line) {
alert('The following error occured: ' + err + '\n' +
'In file: ' + file + '\n' +
'At line: ' + line);
return true;
}
*/
