﻿$(document).ready(function() {
	
	overlayButtonInit();
	
	$("body").load(function() {
		if(top != self)
			top.location = self.location;
	});
	
	navInit();
	
	$("body").animate({
		marginLeft: 0
	}, 500, function() {
		checkScreenSize();
	});
	
});

//CHECK SCREEN SIZE
function checkScreenSize() {
	
	var viewportMinHeight = 620;
	var viewportHeight = $(window).height();
	var siteHeight = 620;
	
	if(viewportHeight < viewportMinHeight) {
		//$("#miniAdventures").css("height", siteHeight + "px");
		$("#flashContainer").attr("height", siteHeight);
		$(".footer").css("position", "relative");
		$(".footer").css("margin-top", "-20px");
	}
	
}



//BIND NAVIGATION FUNCTIONS
function navInit() {
	
	var currentURL = document.URL;
	
	if(currentURL.indexOf("/Enter/") > 1) {
		
		$(".top_line_nav a").each(
			function() {
				
				var thisSection = $(this).attr("class");
				
				if(thisSection == "Adventures" || thisSection == "Winners" || thisSection == "FlavoursFAQs") {
					$(this).bind("click", function() {
						return true;
					});
				}
				
			}
		);
		
	}
	
	
	isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	
	if (isIE6) {
	
		
		$(".top_line_nav a").each(
			function() {
	
				var thisSection = $(this).attr("class");
	
				if(thisSection == "Adventures") {
					$(this).bind("click", function(ev) {
						var adventuresFlash = document.getElementById("flashContainer");
						adventuresFlash.navigateToAdventures();
						ev.preventDefault();
						ev.stopPropagation();
						return false;
					});
				} else if(thisSection == "Winners") {
					$(this).bind("click", function(ev) {
					var adventuresFlash = document.getElementById("flashContainer");
						adventuresFlash.navigateToWinner();
						ev.preventDefault();
						ev.stopPropagation();
						return false;
					});
				} else if(thisSection == "FlavoursFAQs") {
					$(this).bind("click", function(ev) {
					var adventuresFlash = document.getElementById("flashContainer");
						adventuresFlash.navigateToFlavoursFAQs();
						ev.preventDefault();
						ev.stopPropagation();
						return false;
					});
				}
	
			}
		);
		
	}
	
	//var myFlashMovie = document.getElementById("flashId");
	//myFlashMovie.myFunctionId();
	
}

//BIND OVERLAY LAUNCH FUNCTIONS
function overlayButtonInit() {
	$("a.ovl").unbind("click");
	$("a.ovl").each(
    	function() {
			var thisOverlay = $(this).attr("class");
			thisOverlay = thisOverlay.substr(4);
			$(this).click(
				function() {
					launchOverlay(thisOverlay);
					return false;
				}
			);
		}
	);
}

//OVERLAYS
function launchOverlay(thisOverlay) {
	
	$("#overlay").remove();
	$("body").prepend("<div id=\"overlay\"></div>");
	try	{
		stopRenderingFlashJava();
	}
	catch(e){
	}
    /* overlaysPath = "overlays/overlays.aspx" */
	$("#overlay").load(oGlobal.overlaysPath + " #ovl-" + thisOverlay, null, function() {
		centerPopup();
	    closeOverlay();
		
		switch(thisOverlay) {
			case "contact":
				overlayInitContact();
				break;
			
			case "share":
				overlayInitShare();
				break;

			case "profile":
				overlayInitProfile();
				break;
				
			default:
				return false;
		}
	});
}

function centerPopup() {
	if ($.browser.msie && $.browser.version == "6.0"){
		var yOffset; 
		if (document.documentElement && document.documentElement.scrollTop) {// Explorer 6 Strict 
			yOffset = document.documentElement.scrollTop; 
		} 
		else if (document.body){ // all other Explorers 
			yOffset = document.body.scrollTop; 
		} 

		//request data for centering
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var popupWidth = 520;
		var popupHeight = 488;

		$(".overlay").css({
			"position": "absolute",
			"top":  yOffset,
			"left": windowWidth / 2 - popupWidth / 2
		});

		//only need force for IE6
		$("#overlay").css({
			"height": windowHeight + yOffset
		});
	}
}

function launchSecondOverlay(thisOverlay) {
	$("#overlay").before("<div id=\"overlay-2\"></div>");
	$("#overlay-2").load(oGlobal.overlaysPath + " #ovl-" + thisOverlay, null, function() {
		closeSecondOverlay();
	});
}

function secondOverlayLaunch(thisContainer) {
	$(thisContainer + " a.ovl").unbind("click");
	$(thisContainer + " a.ovl").each(
		function() {
			var thisOverlay = $(this).attr("class");
			thisOverlay = thisOverlay.substr(4);
			$(this).click(
				function() {
					launchSecondOverlay(thisOverlay);
					return false;
				}
			);
		}
	);
}

function closeOverlay() {
	$("#overlay .close a, #overlay .cancel a").unbind("click");
	$("#overlay .close a, #overlay .cancel a").click(
		function() {
			$("#overlay").fadeOut(400, function() {
				$("#overlay").remove();
				window.setTimeout(function() {
					startRenderingFlashJava();
			   }, 0);
			});
			return false;
		}
	);
}

function closeSecondOverlay() {
	$("#overlay-2 .close a, #overlay-2 .cancel a").unbind("click");
	$("#overlay-2 .close a, #overlay-2 .cancel a").click(
		function() {
			$("#overlay-2").fadeOut(400, function() {
				$("#overlay-2").remove();
			});
			return false;
		}
	);
}

/*
function startRenderingFlashJava() {
	var alertPlusMovie = document.getElementById("site");
	try {
	    if(alertPlusMovie["startRenderingFlash"]){
		    alertPlusMovie["startRenderingFlash"]();
	    }
	} catch(e){}
}

function stopRenderingFlashJava() {
	var alertPlusMovie = document.getElementById("site");
	try {
	    if(alertPlusMovie["stopRenderingFlash"]){
		    alertPlusMovie["stopRenderingFlash"]();
	    }
	} catch (e){}
}
*/

function overlayInitContact() {
	registerField("#cnt-firstname");
	registerField("#cnt-lastname");
	registerField("#cnt-email", "email");
	registerField("#cnt-message");
	registerField("#cnt-terms", "terms");
	initFields("#ovl-contact table");
	contactButtonInit();
	secondOverlayLaunch("#ovl-contact");
}

function overlayInitShare() {

	$("#ovl-share ul.share .delicious").attr("href", "http://del.icio.us/post?url=" + encodeURIComponent(document.URL) + "&title=" + encodeURIComponent(document.title));
	$("#ovl-share ul.share .digg").attr("href", "http://digg.com/submit?url=" + encodeURIComponent(document.URL) + "&title=" + encodeURIComponent(document.title));
	$("#ovl-share ul.share .facebook").attr("href", "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(document.URL));
	$("#ovl-share ul.share .stumbleupon").attr("href", "http://www.stumbleupon.com/submit?url=" + encodeURIComponent(document.URL) + "&title=" + encodeURIComponent(document.title));
	$("#ovl-share ul.share .twitter").attr("href", "http://twitter.com/home?status=Currently reading " + encodeURIComponent(document.URL));

	$("#ovl-share ul.share .delicious").attr("onclick", "return trackAction('exit', document.URL, 'share: delicious');");
	$("#ovl-share ul.share .digg").attr("onclick", "return trackAction('exit', document.URL, 'share: digg');");
	$("#ovl-share ul.share .facebook").attr("onclick", "return trackAction('exit', document.URL, 'share: facebook');");
	$("#ovl-share ul.share .stumbleupon").attr("onclick", "return trackAction('exit', document.URL, 'share: stumbleupon');");
	$("#ovl-share ul.share .twitter").attr("onclick", "return trackAction('exit', document.URL, 'share: twitter');");

	contactButtonInit();
}

function overlayInitProfile() {
	$("a.contact-us").unbind("click");
	$("a.contact-us").click(
		function() {
			launchOverlay("contact");
			return false;
		}
	);
}

//REGISTER REQUIRED FIELDS
function registerField(thisField, additionalClass) {
	if(!additionalClass) {
		additionalClass = "";
	}
	$(thisField).addClass("req " + additionalClass);
}

function deRegisterField(thisField, additionalClass) {
	$(thisField).removeClass("req");
	if(additionalClass) {
		$(thisField).removeClass(additionalClass);
	}
}

//FIELD FOCUS
function initFields(thisContainer) {	
	$(thisContainer + " :input").unbind("focus");
	$(thisContainer + " :input").unbind("blur");
	$(thisContainer + " :input").focus(
		function() {
		    if (typeof (leaveFieldDefaults) == "undefined") {
		        //Clear default content
		        if ($(this).attr("value") == $(this)[0].defaultValue) {
		            $(this).attr("value", "");
		        }
		    }
		    $(thisContainer + " :input").css("color", "#fff");
		    //Show hint
		    showHint(this);
		}
	);
	
	//FIELD BLUR
	$(thisContainer + " :input").blur(
		function() {			
			//Hide hint
			hideHint(this);			
			//Validate content
			if($(this).hasClass("req")) {
				validateField(this);
			}			
		}
	);	
}

//HINT FUNCTIONS
function showHint(thisField) {
	if($(thisField).siblings(".hint").is(":hidden")) {
		$(thisField).siblings(".hint").fadeIn(300);
	}
}

function hideHint(thisField) {
	if($(thisField).siblings(".hint").is(":visible")) {
		$(thisField).siblings(".hint").hide();
	}
}

//FIELD VALIDATION
function validateForm(thisForm) {
	$(thisForm + " :input").each(
		function() {
			if($(this).hasClass("req")) {
				validateField(this);
			}
		}
	);
}

function validateField(thisField) {
	var additionalClass = $(thisField).attr("class").substr(4);
	var fieldValue = $(thisField).attr("value");
	switch(additionalClass) {
		case "email":
			var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
			if(!emailFilter.test(fieldValue)) {
				addError(thisField);
			} else {
				removeError(thisField);
			}
			
			break;
			
		case "terms":
			if($(thisField).parent().children("input.terms:checked").length < 1) { //IE has problems with thisField :checked
				addError(thisField, $(thisField).next("label"));
			} else {
				removeError(thisField, $(thisField).next("label"));
			}
			
			break;
			
		case "select":
			if($(thisField).attr("value") == "default") {
				addError(thisField);
			} else {
				removeError(thisField);
			}
			
			break;
			
		case "radio":
			var radioGroup = $(thisField).attr("name");
			
			if($("input[name='" + radioGroup + "']:checked").length < 1) { //IE has problems with thisField :checked
				addError(thisField, $(thisField).parents("ul").prev("h3"));
			} else {
				removeError(thisField, $(thisField).parents("ul").prevAll("h3"));
			}
			
			break;
			
		case "postcode":
			if($(thisField).attr("value").length > 8 || $(thisField).attr("value") == "") {
				addError(thisField);
			} else {
				removeError(thisField);
			}
			
			break;
			
		case "password":
			checkPasswordMatch();
			
			break;
			
		default:
			if(!fieldValue) {
				addError(thisField);
			} else {
				removeError(thisField);
			}
		
	}
}

//ERROR FEEDBACK
function addError(thisField, thisObject) {
	if(thisObject) {
		if($(thisObject).next(".error").length < 1) {
			$(thisObject).after("<span class=\"error\"></span>");
		}
	} else {
		if($(thisField).next(".error").length < 1) {
			$(thisField).after("<span class=\"error\"></span>");
		}
	}
	validationResult = 0;
}

function removeError(thisField, thisObject) {
	if(thisObject) {
		$(thisObject).next(".error").remove();
	} else if(thisField) {
		$(thisField).next(".error").remove();
	} else {
		$(".error").remove();
	}
}

//CONTACT FORM BUTTON INIT
function contactButtonInit() {
	$("#ovl-contact .send").unbind("click");
	$("#ovl-contact table :input").unbind("keypress");
	//SIGN IN CLICK
	$("#ovl-contact .send").click(
		function() {
			contactButtonSubmit();
			return false;
		}
	);
	
	//ENTER PRESS
	$("#ovl-contact table :input").keypress(
		function(e) {
			if(e.which == 13) {
				//contactButtonSubmit();
			}
		}
	);
}

function contactButtonSubmit() {
	thisObject = "#ovl-contact .send";
	if(!$(thisObject).hasClass("disabled")) {
		//Validate content
		submitInit(thisObject);
		$("ul.links").after("<span class=\"loader-alt\"></span>");
		var targetForm = "#ovl-contact .form"; //Set target form if button resides outside form container
		if(!targetForm) {
			var targetForm = $(thisObject).parent().siblings(".form");
		}
		validateForm(targetForm);
		//Response okay
		if(validationResult != 0) {
			completeContact();
		} else {
			submitReset();
		}
	}
	return false;
}

function completeContact() {
    if(validationResult != 0) {
        var messageType;
        var messageType_checked = $("#cnt-query-1").is(":checked");
        if (messageType_checked) {
            messageType = "Customer Service";
        }
        else { 
            messageType = "Technical";
        }            
		$.post(oGlobal.site_root + "ajax/ContactUs.ashx",
			{
				title: $("#cnt-title").val(),
				firstName: $("#cnt-firstname").val(),
				lastName: $("#cnt-lastname").val(),
				email: $("#cnt-email").val(),
				message: $("#cnt-message").val(), 
				messageType : messageType
			},
			function(data) {
			    if (data == "OK")
			    {
			        $("#ovl-contact .intro, #ovl-contact .form-items, #ovl-contact table, #ovl-contact .links").hide();
                    $("#ovl-contact .content").append("<p class=\"success\">Thank you. Your message has been sent</p><h2 class=\"rem\">What happens next?</h2><p class=\"rem\">Our customer service team will deal with your enquiry as soon as possible.</p><h2 class=\"rem\">What do you want to do now?</h2><ul class=\"rem\"><li class=\"cancel\"><a href=\"#content\">Go back to the Lucozade Energy website</a></li><li class=\"send-another\"><a href=\"#content\" onclick=\"launchOverlay('contact'); return false;\">Send another message</a></li></ul>");
                    
                    closeOverlay();
			    	$(".loader-alt").remove();
//                  sendanotherButtonInit();
			    }
			}
		);
	}
}

//SUBMIT INIT
function submitInit(thisButton) {
	$(thisButton).addClass("disabled");
	if($(thisButton).next(".loader").length < 1) {
		$(thisButton).after("<span class=\"loader\"></span>");
	}
	// can't disable these - they are NOT submitted if disabled
	// set readonly and change CSS instead
	//$(":input").attr("disabled", "disabled");
	$(":input").css("color", "#777");
	$(".server-error").remove();
	validationResult = 1;
}

//SUBMIT RESET
function submitReset(thisButton, flush) {
	if(thisButton) {
		$(thisButton).removeClass("disabled");
		$(thisButton).next(".loader").remove();
	} else {
		$("a.pill").removeClass("disabled");
		$(".loader").remove();
	}
	//$(":input").attr("disabled", "");
	$(":input").css("color", "#fff");
	if(flush) {
		$(":input").each(
			function() {
				$(this).attr("value", $(this)[0].defaultValue);
			}
		);
	}
}

//ACTION TRACKING
function trackAction(action, page, title, media, type) {
	
	page = page.substr(page.indexOf("sport/"));
	
	var track_path = "/" + action + "/" + page + "/" + title;
	
	if(media) track_path += "/" + media;
	if(type) track_path += "/" + type;
	
	track_path = unescape(track_path);
	pageTracker._trackPageview(track_path);
	
}

//GET URL FOR SHARETHIS
	url = (document.location.href);
    
