$(document).ready(function() {
	
	siteRoot = "http://www.freshawards.co.uk/";
	
	if($(".list dl").exists()) {
		initListDL();
	}
	if($("#masthead .tabs").exists()) {
		initTabLabels();
	}
	if($("#slideshow").exists()) {
		initSlideshow();
		$("#slideshow li:first img").load(checkSlideshowHeightOnImageLoad);
	}
	if($("#mediaPlayer").exists()) {
		initMediaPlayer();
	}
	if($("input:text, input:password").exists()) {
		initFields();
	}
	if($(".validation-summary-errors").exists()) {
		initValidationSummary();
	}
	/*if($(".form input:submit, .col-303 input:submit").exists()) {
		initForm();
	}*/
	if($(".confirmation").exists()) {
		initConfSummary();
	}

	if ($(".unpaid-summary").exists()) {
		initUnpaidSummary();
	}
	if ($(".paid-summary").exists()) {
		initPaidSummary();
	}
	if($("#cart").exists()) {
		initCart();
	}
	/*if($("#ticker").exists()) {
		initTicker();
	}*/
	if($(".panel-sd").exists()) {
		initPanelSD();
	}
	prepOverlay();
	initLinks();
	initOverlayLinks();
	initGAEvents();
	initSiteContainer();
	
});

//////////----- CORE ------------------------------------------//////////
//---------------------------------------------------------------------//
jQuery.fn.exists = function() {
	return jQuery(this).length > 0;
}

//////////----- SITE CONTAINER --------------------------------//////////
//---------------------------------------------------------------------//
function initSiteContainer() {
	var windowHeight = $(window).height();
	var containerHeight = $("#container").height();
	if(windowHeight > containerHeight) {
		$("#container").css({ "height": "100%" });
	}
}

//////////----- LIST (DEFINITION LIST) ------------------------//////////
//---------------------------------------------------------------------//
function initListDL() {

	$(".list dt").each(
		function() {
			if ($(this).next("dd").exists()) {

				$(this).hover(function() {
					$(this).css({
						"color": "#ffde00",
						"cursor": "pointer"
					});
				}, function() {
					$(this).css({ "color": "#666" });
				});
				
				$(this).click(function() {
					if($(this).next("dd").is(":hidden")) {
						$(this).parent("dl").children("dd").each(
							function() {
								if($(this).is(":visible")) {
									$(this).slideUp(400);
									$(this).prev("dt").find(".state").html("+");
									//$(this).prev("dt").toggle();
								}
							}
						);
						$(this).next("dd").slideDown(400);
						$(this).find(".state").html("&minus;");
					} else if($(this).next("dd").is(":visible")) {
						$(this).next("dd").slideUp(400);
						$(this).find(".state").html("+");
					}
					return false;
				});
			}
		}
	);
	
}

//////////----- TAB LABELS ------------------------------------//////////
//---------------------------------------------------------------------//
function initTabLabels() {
	
	if($("#masthead .tabs .current").exists()) {
		$("#masthead .tabs .current").animate({
			"margin-top": 0
		}, 400);
	}
	
}

//////////----- SLIDESHOW -------------------------------------//////////
//---------------------------------------------------------------------//
function initSlideshow() {
	
	var ssLength = $("#slideshow li").length;
	var ssImgWidth = 630;
	var ssHeight = 0;
	$("#slideshow ul li").css({ "width": ssImgWidth + "px" });
	$("#slideshow ul").css({ "width": ssLength*ssImgWidth + "px" });
	var ssCount = 1;
	
	var ssImgHeight = $("#slideshow li:first").height();
	if(ssImgHeight > ssHeight) {
		ssHeight = ssImgHeight;
	}
	
	$("#slideshow li").each(
		function() {
			
			if(ssCount == 1) {
				var current = " current";
			} else {
				var current = "";
			}
			$("#slideshow-nav").append("<li class=\"slideshow" + ssCount + "\"><a class=\"" + current + "\" href=\"#\">" + ssCount + "</a></li>");
			$(this).attr("id", "slideshowImg" + ssCount);
			
			$("#slideshow-nav .slideshow" + ssCount + " a").bind("click", function() {
				var ssImage = $(this).parent("li").attr("class");
				ssImage = ssImage.substr(9);
				$("#slideshow ul").animate({
					left: "-" + ssImgWidth*(ssImage-1)
				}, 400);
				$("#slideshow-nav li a").removeClass("current");
				$(this).addClass("current");
				
				//Adjust height
				ssHeight = $("#slideshowImg" + ssImage).height();
				$("#slideshow").animate({
					height: ssHeight
				}, 400);
				
				return false;
			});
			
			ssCount++;
		}
	);
	
	$("#slideshow").css({ "height": ssHeight + "px" });
	$("#slideshow ul").css({ "height": ssHeight + "px" });
	
}


function checkSlideshowHeightOnImageLoad() {

	var ssHeight = $(this).height();

	$("#slideshow").css({ "height": ssHeight + "px" });
	$("#slideshow ul").css({ "height": ssHeight + "px" });	
}

//////////----- MEDIA PLAYER ----------------------------------//////////
//---------------------------------------------------------------------//
function initMediaPlayer() {
	
	$("#slideshow-nav li a").each(
		function() {
			if($(this).hasClass("media")) {
				$(this).bind("click", function() {
					var mediaPath = $(this).attr("href");
					if($(this).hasClass("video")) {
						var mediaHeight = "400";
						var mediaControlBar = "true";
						var mediaType = "Audio";
					} else if($(this).hasClass("audio")) {
						var mediaHeight = "35";
						var mediaControlBar = "false";
						var mediaType = "Video";
					}					
					$("#mediaPlayerFrame").show();
					launchMediaPlayer(mediaPath, mediaHeight, mediaControlBar);
					GATrackEvent("Media", "View " + mediaType, document.URL);
					return false;
				});
			}
		}
	);
	
	$("#mediaPlayerFrame p a").bind("click", function() {
		$("#mediaPlayerFrame").hide();
		$("#mediaPlayer").empty();
		return false;
	});
	
}
function launchMediaPlayer(mediaPath, mediaHeight, mediaControlBar) {
	
	$("#mediaPlayer").empty();
	$("#mediaPlayer").html("<embed src=\""+mediaPath+"\" width=\"630\" height=\""+mediaHeight+"\" scale=\"aspect\"></embed>");
	
	/*
	var mediaPlayerParameters = {
		id: "1",
		src: mediaPath,
		autoPlay: "true",
		width: "630",
		height: mediaHeight,
		backgroundColor: "#000000",
		autoHideControlBar: mediaControlBar,
		controlBarPosition: "bottom"
	};
	
	// Embed the player SWF:							
	swfobject.embedSWF(
		siteRoot+"SWF/StrobeMediaPlayback.swf",
		"mediaPlayer",
		mediaPlayerParameters["width"],
		mediaPlayerParameters["height"],
		"10.0.0",
		{},
		mediaPlayerParameters,
		{ allowFullScreen: "true" },
		{ name: "StrobeMediaPlayback" }
	);
	*/
	
	/*
	flowplayer("mediaPlayer", siteRoot+"SWF/flowplayer-3.2.2-0.swf", {
		// player configuration goes here
		clip: {
			url: mediaPath,
			autoPlay: true,
			autoBuffering: true,
			image: siteRoot+"images/posterframe.gif"
		}
	});
	*/
	
}

//////////----- VERTICAL CENTRE -------------------------------//////////
//---------------------------------------------------------------------//
function verticalCentre(object) {
	
	var objectHeight = $(object).height();
	var viewportHeight = $(window).height();
	
	if(viewportHeight > objectHeight) {
		var yOffset = Math.floor((viewportHeight - objectHeight) / 2) - 24;
		$(object).css({ "margin-top": yOffset + "px" });
	}
	
}

//////////----- LINKS -----------------------------------------//////////
//---------------------------------------------------------------------//
function initLinks() {
	
	$("a").each(
		function() {
			if(!$(this).hasClass("ovl") && !$(this).hasClass("media")) {
				$(this).bind("click", function() {
					var destinationURL = $(this).attr("href").toLowerCase();
					if(!destinationURL.match("freshawards.co.uk") && !destinationURL.match("dev.fusedevelopment.com/freshawards") && (destinationURL.match("http://") || destinationURL.match("https://"))) {
						window.open(destinationURL);
						return false;
					} else {
						return true;
					}
				});
			}
		}
	);
	
}

//////////----- OVERLAY LINKS ---------------------------------//////////
//---------------------------------------------------------------------//
function initOverlayLinks() {
		
	$("a.ovl").each(
		function() {
			var ovlHref = $(this).attr("href");
			var ovlTarget = $(this).attr("class");
			ovlTarget = ovlTarget.substr(4);
			$(this).bind("click", function() {
				initOverlay(ovlHref, ovlTarget);
				if($.browser.msie) {
					var browserVersion = $.browser.version;
					browserVersion = browserVersion.substr(0,1);
					if(browserVersion == 6) {
						return true; //IE6 doesn't support fixed positioning so jump to top of page for overlay
					} else {
						return false;
					}
				} else {
					return false;
				}
				
			});
		}
	);

}

//////////----- OVERLAY ---------------------------------------//////////
//---------------------------------------------------------------------//
function prepOverlay() {	
	$("body").prepend("<div id=\"overlay\"><div class=\"frame\"><div class=\"panel\"><div class=\"loader\"></div></div></div></div>");
	$("body").prepend("<div id=\"overlay-idle\"><div class=\"frame\"><div class=\"panel\"><div class=\"loader\"></div></div></div></div>");
}
function initOverlay(ovlHref, ovlTarget) {
	
	$("#overlay").addClass("active");
	verticalCentre("#overlay .panel");
	$("#overlay .panel").css({ "height": $("#overlay .panel").height() + "px" });
	
	//$("#overlay .panel").load("overlay.html #ovl" + ovlTarget, function() {
	//$("#overlay .panel").load(ovlHref + " #ovl" + ovlTarget, function() {
	$("#overlay .panel").load(ovlHref + "/Overlay", function() {
		
		var maxHeight = 380;
		var targetHeight = $("#ovl" + ovlTarget).height();
		if(targetHeight > maxHeight) {
			targetHeight = maxHeight + 48;
			$("#overlay .panel .content").css({ "height": maxHeight + "px" });
			$("#overlay .panel .content").addClass("scroll");
		}
		var viewportHeight = $(window).height();
		var targetMargin = Math.floor((viewportHeight - targetHeight) / 2) - 24;
		$("#ovl" + ovlTarget).hide();
		
		$("#overlay .panel").animate({
			"height": targetHeight + "px",
			"margin-top": targetMargin + "px"
		}, 400, function() {
			$("#ovl" + ovlTarget).fadeIn(200);
		});
		
		$(window).bind("resize", function() {
			verticalCentre("#overlay .panel");
		});
		
		$("#overlay .close a").bind("click", function() {
			$("#overlay .panel").empty();
			$("#overlay .panel .content").removeClass("scroll");
			$("#overlay .panel").css({ "height": "auto" });
			$("#overlay").removeClass("active");
			$(window).unbind();
			return false;
		});
		
		GATrackPageView("/Overlay/" + ovlTarget);
		
	});
	
}
function initOverlayIdle() {
	$("#overlay-idle").addClass("active");
	$("#overlay-idle .loader").after("<p>I'm just going outside<br />I may be a while</p>");
	verticalCentre("#overlay-idle .panel");
}
function closeOverlayIdle() {
	$("#overlay-idle").removeClass("active");
}

//////////----- FIELDS ----------------------------------------//////////
//---------------------------------------------------------------------//
function initFields() {
	
	$("input:text, input:password").each(
		function() {
			$(this).bind("focus", function() {
				$(this).siblings("label").hide();
			});
			$(this).bind("blur", function() {
				if($(this).val() == "") {
					$(this).siblings("label").show();
				}
			});
		}
	);
	
	$("input:text").each(
		function() {
			if(!$(this).val() == "") {
				$(this).siblings("label").hide();
			}
		}
	);
	
}

//////////----- FORM SUBMISSION -------------------------------//////////
//---------------------------------------------------------------------//
function initForm() {	
	var targetForm = $(".form input:submit, .col-303 input:submit").parents("form").attr("id");	
	$("#" + targetForm).validate();
}

function initValidationSummary() {
	$(".validation-summary-errors").animate({
		backgroundColor: "#ffeaea"
	}, 1000);
}

function initConfSummary() {
	$(".confirmation").animate({
		backgroundColor: "#f2fff2"
	}, 1000);
}


function initUnpaidSummary() {
	$(".unpaid-summary").animate({
		backgroundColor: "#ffeaea"
	}, 1000);
}

function initPaidSummary() {
	$(".paid-summary").animate({
		backgroundColor: "#f2fff2"
	}, 1000);
}


//////////----- FEES CART -------------------------------------//////////
//---------------------------------------------------------------------//
function initCart() {
	
	$("#cart").mouseover(function() {
		$("#cart table").animate({
			"margin-top": 0
		}, 400);
	});
	
	$("#cart").mouseleave(function() {
		$("#cart table").stop(true);
		$("#cart table").animate({
			"margin-top": "-112px"
		}, 400);
	});
	
}

//////////----- GA TRACKING -----------------------------------//////////
//---------------------------------------------------------------------//
function GATrackEvent(category, action, label) {
	_gaq.push(["_trackEvent", category, action, label]);
	//alert(category + " " + action + " " + label);
}

function GATrackPageView(page) {
	_gaq.push(["_trackPageview", page]);
	//alert(page);
}

function initGAEvents() {
	
	$("a").each(
		function() {
			var destinationURL = $(this).attr("href");
			if(destinationURL.indexOf(".pdf") > -1) {
				var category = "Link";
				var action = "Download";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			} else if(destinationURL.indexOf("mailto") > -1) {
				var category = "Link";
				var action = "Mailto";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			} else if(destinationURL.indexOf("http") > -1 && destinationURL.indexOf("freshawards.co.uk") == -1) {
				var category = "Link";
				var action = "Exit";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			}
		}
	);

}

//////////----- NEWS TICKER -----------------------------------//////////
//---------------------------------------------------------------------//
function initTicker() {
	
	tickerItems = new Array();
	tickerIndex = 0;
	//var tickerMaxChars = 116;
	var tickerMaxChars = 112;
	
	//$("#ticker li a").each(
	$("#ticker li").each(
		function() {
			var tickerItemText = $(this).text();
			if(tickerItemText.length > tickerMaxChars) {
				tickerItemText = tickerItemText.substr(0, tickerMaxChars);
				tickerItemText += "...";
			}/* else {
				tickerItemText += "...";
			}*/
			$(this).text(tickerItemText);
			tickerItems[tickerIndex] = $(this).text();
			tickerIndex++;
			$(this).text("");
			$(this).hover(
				function() {
					stopTicker();
				}, function() {
					tickerInterval = setInterval(runTicker, 6000);
				}
			);
			//$(this).prepend("<a href=\"http://twitter.com/freshawards\">").append("</a>");
		}
	);
	
	$("#ticker li").hide();
	tickerIndex = 0;
	tickerLength = $("#ticker li").length;
	tickerInterval = setInterval(runTicker, 6000);
	runTicker();
	$("#ticker").show();
	
}

function runTicker() {
	
	$("#ticker li").hide();
	$("#ticker li:eq(" + tickerIndex + ")").show();
	
	var tickerText = "";
	var tickerTextLength = tickerItems[tickerIndex].length;
	var tickerCharIndex = 0;
	tickerCharInterval = setInterval(runTickerChar, 10);
	
	function runTickerChar() {
		tickerText += tickerItems[tickerIndex].charAt(tickerCharIndex);
		//$("#ticker li:eq(" + tickerIndex + ") a").text(tickerText);
		$("#ticker li:eq(" + tickerIndex + ")").text(tickerText);
		tickerCharIndex++;
		if(tickerCharIndex == tickerTextLength) {
			clearInterval(tickerCharInterval);
			tickerIndex++;
			if(tickerIndex == tickerLength) {
				tickerIndex = 0;
			}
		}
	}
	
}

function stopTicker() {
	clearInterval(tickerInterval);
}

//////////----- SLIDE DOWN PANEL (GENERIC) --------------------//////////
//---------------------------------------------------------------------//
function initPanelSD() {
	
	$(".panel-sd").each(
		function() {
			panelSDLink = $(this).prev("p").children("a");
			panelSDLinkText1 = $(panelSDLink).text();
			if(panelSDLinkText1.match("More")) {
				panelSDLinkText2 = panelSDLinkText1.substr(5);
				panelSDLinkText2 = "Hide " + panelSDLinkText2;
			} else {
				panelSDLinkText2 = "Hide information";
			}
			
			$(panelSDLink).toggle(
				function() {
					$(this).parent("p").next(".panel-sd").slideDown(400);
					$(this).text(panelSDLinkText2);
				}, function() {
					$(this).parent("p").next(".panel-sd").slideUp(400);
					$(this).text(panelSDLinkText1);
				}
			);
		}
	);

	}

//
// jQuery select extensions
//
(function($) {
	jQuery.fn.selectOptions = function(settings) {
		var sb = [];
		for (var key in settings) {
			var item = settings[key];
			if (typeof item === "object") {
				// <optgroup>
				sb.push('<optgroup label="' + key + '">');
				for (var optkey in item)
					sb.push('<option value="' + item[optkey] + '">' + optkey + '</option>');
				sb.push('</optgroup>');
			}
			else {
				// <option>
				sb.push('<option value="' + item + '">' + key + '</option>');
			}
		}
		var str = sb.join('');

		this.each(function() {
			$(this).html(str);
		});

		return this;
	}
})(jQuery);



//////////----- AWARD ENTRIES ---------------------------------//////////
//---------------------------------------------------------------------//


//
// EditMultipleFiles support
//

function initMultipleFileUploadEditor(inputId, inputName, addAnchorId, tableId, trTmplId, trCssClass, maxFiles) {

	$(addAnchorId).click(function() {
		var tbody = $(tableId + " tbody");

		var fileCount = tbody.find("tr." + trCssClass + ":visible").length;
		if (fileCount < maxFiles) {

			var newIndex = fileCount + 1;
			var tr = tbody.find("tr:not(:visible):first").css("display", "");
			
			if ((fileCount + 1) >= maxFiles)
				tbody.find("tr:last a").css("display", "none");
		}
		return false;
	});

	$(tableId + " tr a.remove").click(function() {

		var tr = $(this).parents("tr");

		if (!confirm("Are you sure you want to remove this file?"))
			return false;

		tr.find("input:file").css("display", "");
		tr.find("span.downloadLink").css("display", "none");
		var inputHidden = tr.find("input:hidden");
		inputHidden.val(inputHidden.val().replace("NoChange", "Delete"));

		var tbody = $(tableId + " tbody");
		var fileCount = tbody.find("tr." + trCssClass + ":visible").length;
		if ((fileCount + 1) >= maxFiles)
			tbody.find("tr:last a").css("display", "");

		return false;
	});
}

function initSingleFileUploadEditor(tr) {

	function bindRemoveAnchor(tr) {
		var a = tr.find("a.remove");
		a.click(function() {
			if (!confirm("Are you sure you want to remove this file?"))
				return false;
			tr.find("input:file").css("display", "");
			tr.find("span.downloadLink").css("display", "none");
			var inputHidden = tr.find("input:hidden");
			inputHidden.val(inputHidden.val().replace("NoChange", "Delete"));
			a.unbind("click");
			return false;
		});
	}

	bindRemoveAnchor(tr);
}


function initKeyPeopleEditor(personTmpl, positionTmpl, addAnchorId, tableId, trTmplId, trCssClass, maxPeople) {

	$(tableId + " tr." + trCssClass).each(function() {
		keyPeople_bindRemoveAnchor($(this));
	});

	$(addAnchorId).click(function() {

		var tbody = $(tableId + " tbody");

		var peopleCount = keyPeople_count(tbody);
		if (peopleCount < maxPeople) {

			var tr = tbody.find(trTmplId).clone();
			tr.attr("id", "").attr("class", trCssClass).css("display", "");

			var id = peopleCount;
			tr.find("input#" + personTmpl.id).each(function() {
				$(this).attr("name", personTmpl.name.replace("$id", id));
			});
			tr.find("input#" + positionTmpl.id).each(function() {
				$(this).attr("name", positionTmpl.name.replace("$id", id));
			});
			tr.insertBefore(tbody.find("tr:last"));
			keyPeople_bindRemoveAnchor(tr);

			if ((peopleCount + 1) >= maxPeople)
				tbody.find("tr:last").css("display", "none");
		}
		return false;
	});

	function keyPeople_count(tbody) {
		return tbody.find("tr." + trCssClass).length;
	}

	function keyPeople_bindRemoveAnchor(element) {
		element.find("p.remove a").click(function() {
			$(this).unbind("click").parents("tr").remove();

			var tbody = $(tableId + " tbody");
			var count = keyPeople_count(tbody);
			if (count <= (maxPeople - 1))
				tbody.find("tr:last").css("display", "");

			return false;
		});
	}
}




//
// MVC Validation
//

//function getWordCount(text) {
//	return text.split(/\w+/).length;
//}

$(document).ready(function() {
	//
	// arrayLength
	//
	jQuery.validator.addMethod("arrayLength", function(value, element, params) {
		var count, fields = $("input#" + element.id);
		if (!params.excludeNullElements) {
			count = fields.length;
		}
		else {
			count = 0;
			fields.each(function(index) {
				if ($.trim($(this).val()) != "")
					count++;
			});
		}
		return (count >= params.minLength && count <= params.maxLength);
	});

	//
	// passwordLength
	//
	jQuery.validator.addMethod("passwordLength", function(value, element, params) {
		if (value == null || value == "")
			return true;
		else if (value.length < params.minChars)
			return false;
		else
			return true;
	});

	//
	// regexi - case insensitive regular expression
	//
	jQuery.validator.addMethod("regexi", function(value, element, params) {
		var rx = params.ignoreCase ? new RegExp(params.pattern, "i") : new RegExp(params.pattern);
		return this.optional(element) || rx.test(value);
	});

	// fileType
	jQuery.validator.addMethod("fileType", function(value, element, params) {
		var rx = new RegExp(params.pattern, "i");
		return this.optional(element) || rx.test(value);
	});

	//
	// freshFileType
	//
	jQuery.validator.addMethod("freshFileType", function(value, element, params) {
		if (value == null || value == "") {
			return true;
		}
		else {
			var rx = params.ignoreCase ? new RegExp(params.pattern, "i") : new RegExp(params.pattern);
			return this.optional(element) || rx.test(value);
		}
	});

	//
	// freshFileRequired
	//
	jQuery.validator.addMethod("freshFileRequired", function(value, element, params) {
		if (value && value != "")
			return true;
		else {
			var statusVal = $("#" + element.id + "Status").val() || "";
			var index = statusVal.indexOf(':');
			var status = statusVal.substring(0, index);
			if (status == "" || status.toLowerCase() == "delete")
				return false;
			else
				return true;
		}
	});

	//
	// wordCount
	//
	//jQuery.validator.addMethod("wordCount", function(value, element, params) {
	//	var count = getWordCount(value);
	//	return (count >= params.minWords && count <= params.maxWords);
	//});
});
