$(document).ready(function() {

	$("#headerSearchField, .searchAgain, .newsletterEmail").each(function() {
		var tempVal = this.value;
		var el = $(this);
		el.focus(function() {
			if(this.value==tempVal)
				this.value="";
		});
		el.blur(function() {
			if(this.value=="")
				this.value=tempVal;
		});
	});
	
	$(".featuredTournHeader h5").each(function(i)
	{
		var parent = $(this).parent(".featuredTournHeader");
	
		
		var el = $(this);
		if(!this.id) {
			this.id = "tournTitleReplace"+i;
		}
		
		swfobject.embedSWF('http://www.ussoccer.com/Media/flash/textReplaceWhite.swf', $(this).attr("id"), '100%', '23', '9.0.124', '', {t:$(this).text(), l:$("a:first", this).attr("href"), lt:$("a:first", this).attr("target"), d:$(this).attr("id")}, {menu:'false', quality:'best', scale:'noscale', wmode:'transparent'});
	});
	
/*
	$(".genericModuleHeader h4").each(function(i)
					  {
					      var parent = $(this).parent(".genericModuleHeader");
					      if($(".moduleAd", parent).length>0) {
						  $(parent).addClass("hasModuleAd");
					      }
					      var el = $(this);
					      if(!this.id) {
						  this.id = "moduleTitleReplace"+i;
					      }
					      swfobject.embedSWF('http://www.ussoccer.com/Media/flash/textReplace.swf', $(this).attr("id"), '100%', '23', '9.0.124', '', {t:$(this).text(), d:$(this).attr("id")}, {menu:'false', quality:'best', scale:'noscale', wmode:'transparent'});

					      					      swfobject.embedSWF('http://www.ussoccer.com/Media/flash/textReplace.swf', $(this).attr("id"), '100%', '23', '9.0.124', '', {t:$(this).text(), l:$("a:first", this).attr("href"), lt:$("a:first", this).attr("target"), d:$(this).attr("id")}, {menu:'false', quality:'best', scale:'noscale', wmode:'transparent'});
					       			  });*/	
	
	








	/*
	$(".genericModuleHeader h4").each(function(i)
	{
		var parent = $(this).parent(".genericModuleHeader");
		if($(".moduleAd", parent).length>0) {
			$(parent).addClass("hasModuleAd");
		}
		
		var el = $(this);
		if(!this.id) {
			this.id = "moduleTitleReplace"+i;
		}
		
		swfobject.embedSWF('http://www.ussoccer.com/Media/flash/textReplace.swf', $(this).attr("id"), '100%', '23', '9.0.124', '', {t:$(this).text(), l:$("a:first", this).attr("href"), lt:$("a:first", this).attr("target"), d:$(this).attr("id")}, {menu:'false', quality:'best', scale:'noscale', wmode:'transparent'});
	});
	*/

	// For each anchor in an li in #playerBioTabs
	// Find the matching _content for the _tab
	// Show that bio content
	$("#playerBioTabs li a").click(function() {
		var showDiv = $(this).attr("id");
		showDiv = showDiv.replace("_tab", "_content");
		showBioContent(this.id, showDiv);
		return false;
	});
	
	//if(curWinRef.width() < 1260) {
		initImageReplace();
		layoutWrapper.addClass("altSize1024");
		//}
	//	if(curWinRef.width() < 1260) {
	//	initImageReplace();
	//	layoutWrapper.addClass("altSize1024");
	//}
		/*

	curWinRef.bind("resize", function() {
		var scope = $(this);
		if(scope.width() < 1260 && !layoutWrapper.hasClass("altSize1024")) {
			layoutWrapper.addClass("altSize1024");
			initImageReplace();
		} else if(scope.width() >= 1260 && layoutWrapper.hasClass("altSize1024"))
			layoutWrapper.removeClass("altSize1024");
	});
	
		*/

	$(".footerNav").each(function(i) {
		 $(".footerNav:eq("+i+")>li:first").addClass("first");
	});
	$(".footerNav>li>ul").each(function(i) {
		$("li:even", this).addClass("oddRow");
	});
	
	$(".imageTextCarousel").each(function (i){
		var newScroller = new scrollObj(i);
	});
	
	$(".homeResultsModule tr:odd").addClass("oddRow");
	
	$(".teamLandScores tr:odd").addClass("oddRow");
	
	$(".genericTable tr:odd").addClass("oddRow");
	
	$("#bioMainData li:odd").addClass("oddRow");
	
	$(".listModule li:odd").addClass("oddRow");
	
	$(".newsArticleList li:odd").addClass("oddRow");
	
	$(".genericDropDown ul.dropContent li a:odd").addClass("oddRow");
	
	var dropdownTimeout = new Array();
	// add click functionality for generic dropdowns
	$(".genericDropDown").each(function(i) {
        var scope = $(this);
        $(".dropTrigger>a:first", scope).bind("click", function() {
            var thisDropStyle = $(".dropContent", scope).css("display");
            if (thisDropStyle == "none") {
                $(".dropContent").hide();
                $(".dropContent", scope).show();
            } else {
				if(clearTimeout(dropdownTimeout[i]))
					clearTimeout(dropdownTimeout[i]);
                $(".dropContent").hide();
            }
            return false;
        });
		
		scope.bind("mouseout", function() {
			dropdownTimeout[i] = setTimeout("hideDropDown("+i+");",1000);
		}).bind("mouseover",function() {
			
			if(clearTimeout(dropdownTimeout[i])) {
				clearTimeout(dropdownTimeout[i]);
				scope.unbind("mouseout");
				scope.bind("mouseout", function() {
					dropdownTimeout[i] = setTimeout("hideDropDown("+i+");",1000);
				});
			}
		});
		
		$(window).bind('resize', function() {
			$(".dropContent", scope).hide();
		});
    });
	
	$(".shareBarSocial>a").bind("click", function() {
        var thisPos = findPos(this);
        toggleShareBar(thisPos);
        return false;
    }).bind("mouseout", function() {
		shareTimeout = setTimeout("hideShareBox();",1000);
	});
    $(".shareBarSocial>a").bind("blur", function() {
        $("#shareBox").removeClass("showBox");
    });
    $(window).bind('resize', function() {
        $("#shareBox").removeClass("showBox");
    });
	$("#shareBox").mouseover(function() {
		var el = $(this);
		el.unbind("mouseout");
		if(clearTimeout(shareTimeout))
			clearTimeout(shareTimeout);

		el.bind("mouseout", function() {
			shareTimeout = setTimeout("hideShareBox();",1000);
		});
	});
	
	
	$(".genericForm").bind("submit", function(i) {
		var form = $(this);
		return validateForm(form);			
	});
	
	
	$(".quizModule").each(function() {
		var quizId = $("form", this).attr("id");
		quizObj.initQuiz(quizId);
	});
	
	// Bind the #checkUserName to check to see if the username is available
	$("#checkUserName").click(function() {
		var button = $(this);
		checkUsernameAvail(button);
		return false;
	});
});
/*************************************************
END OF DOC READY
*************************************************/
var imageReplaced = false;
var curWinRef = $(window);
var layoutWrapper = $("#allWrap");
	
function toggleShareBar(coords) {
	newCoord = coords[1] + 22;
	newCoordLeft = coords[0] + 1;
	$("#shareBox").css("left",newCoordLeft);
	$("#shareBox").css("top",newCoord);
	$("#shareBox").toggleClass("showShare");
}
function hideShareBox(el) {
	$("#shareBox").removeClass("showShare");
}


function hideDropDown(i) {
	$(".dropContent:eq("+i+")").hide();	
}

function initImageReplace() {
	if(!imageReplaced) {
		$(".imageReplace").each(function(i)
		{
			var scope = $(this);
			var parentLink = (scope.parent("a").length >0) ?scope.parent("a").attr("href") : "";
			
			if(!this.id) {
				this.id = "imageReplace"+i;
			}
			
			swfobject.embedSWF('http://www.ussoccer.com/Media/flash/imageReplace.swf',scope.attr("id"), '100%', '50', '9.0.124', '', {t:scope.attr("src"), d:scope.attr("id"), l:parentLink}, {menu:'false', quality:'best', scale:'noscale', wmode:'transparent'});
		});
		imageReplaced = true;
	}
}
function addClickEvent(id) {
	$("#"+id).click(function() {
		var parentLink = $(this).parent("a");
		$(parentLink).triggerHandler("click");
	});
}
function resizeDiv(d,h)
{
	var el = $("#"+d);
	/*var parent = el.parent().parent(".genericModuleHeader");
	if($(".moduleAd", parent).length>0) {
		var theH4 = el.parent("h4");
		var newWid = parent.width() - 98;
		theH4.width(newWid);
	}*/
	el.css("height", h+"px");
	return false;
}
footerHover = function() {
	$(".footerNav>li").mouseover(function() {
		$(this).css("position", "relative");
		$(this).addClass("footerHover");
	}).mouseout(function() {
		$(this).css("position", "static");
		$(this).removeClass("footerHover");
	});
}
mainHover = function() {
	$("#siteNavMain>li").mouseover(function() {
		$(this).css("position", "relative");
		$(this).addClass("mainHover");
	}).mouseout(function() {
		$(this).css("position", "static");
		$(this).removeClass("mainHover");
	});
}

if (window.attachEvent) window.attachEvent("onload", footerHover);
if (window.attachEvent) window.attachEvent("onload", mainHover);


/*function toggleShareBar(coords) {
	newCoord = coords[1] + 16;
	newCoordLeft = coords[0] - 16;
	var shareBoxEl = $("#shareBox");
	shareBoxEl.css("left",newCoordLeft);
	shareBoxEl.css("top",newCoord);
	shareBoxEl.toggleClass("showShare");
}
function hideShareBox(el) {
	$("#shareBox").removeClass("showShare");
}*/
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	return [curleft,curtop];
	}
}
/**
 * Tab system for showBioContent - makes the tab active, animates the content in.
 * <p>
 * Hides the .playerBioTabContent
 * Removes the active class from anything within #playerBioTabs that is active.
 * Adds the active class back to the parent of the id passed.
 * Slowly animates in the div referenced in showDiv.
 * </p>
 * @returns {void}
 * @param {string} id DOM Node ID for the tab we wish to make active.
 * @param {string} showDiv DOM Node ID for the content div we wish to show.
 * @see $(document).ready (called by) (related to playerBioTabs)
 * @author Richard Rudzinski
 */
showBioContent = function(id, showDiv) {
	$(".playerBioTabContent").hide();
	$("#playerBioTabs .active").removeClass("active");
	$("#"+id).parent().addClass("active");
	$("#"+showDiv).animate({opacity: 'show'}, "fast");
	return false;
}

function scrollObj(i) {
	this.scrollWidth = $(".imageTextCarouselHide:eq("+i+")").width();
	this.currentPane = 1;
	this.totalScrollPanes = $(".imageTextCarouselHide:eq("+i+") .carouselItem").length;
	this.paneWidth = $(".imageTextCarouselHide:eq("+i+") .carouselItem:first").width() + parseInt($(".imageTextCarouselHide:eq("+i+") .carouselItem:first").css("margin-left")) + parseInt($(".imageTextCarouselHide:eq("+i+") .carouselItem:first").css("margin-right"));
	this.totalScrollPanes = parseInt(this.totalScrollPanes) * this.paneWidth;
	
	this.paneCount = Math.ceil(this.totalScrollPanes / this.scrollWidth);
	
	this.scrollHide = $(".imageTextCarouselHide:eq("+i+")");
	this.scrollWrap = $(".imageTextCarouselHide:eq("+i+") .imageTextCarouselWrap");
	$(this.scrollWrap).width(this.totalScrollPanes+"px");
	
	this.okToScroll = true;
	this.scrollLeftButton = $(".imageTextCarousel:eq("+i+")>.scrollCarouselLeft:first");
	this.scrollRightButton = $(".imageTextCarousel:eq("+i+")>.scrollCarouselRight:first");
	var self= this;
	$(this.scrollLeftButton).click(function() {
		self.scrollCarousel(1);
		return false;
	});
	$(this.scrollRightButton).click(function() {
		self.scrollCarousel(-1);
		return false;
	});
	
	if(this.paneCount > 1)
		$(this.scrollRightButton).show();
		
	$(window).bind("resize", function() {
		self.redefineCarousel(i);						  
	});
}


scrollObj.prototype = {
	redefineCarousel: function(i) {
		tempWidth  = $(".imageTextCarouselHide:eq("+i+")").width();
		tempTotalPanes = $(".imageTextCarouselHide:eq("+i+") .carouselItem").length;
		tempPaneWidth = $(".imageTextCarouselHide:eq("+i+") .carouselItem:first").width() + parseInt($(".imageTextCarouselHide:eq("+i+") .carouselItem:first").css("margin-left")) + parseInt($(".imageTextCarouselHide:eq("+i+") .carouselItem:first").css("margin-right"));
		tempTotalPanes = parseInt(tempTotalPanes) * tempPaneWidth;
		
		tempPaneCount = Math.ceil(tempTotalPanes / tempWidth);
		
		if(tempPaneCount != this.paneCount) {
			this.scrollLeftButton.hide();
			this.scrollRightButton.hide();
			this.scrollWrap.animate({left: 0}, "fast");
			//this.scrollWrap.css("left", 0);
			
			
			this.scrollWidth = tempWidth;
			this.currentPane = 1;
			this.paneWidth = tempPaneWidth;
			this.totalScrollPanes = parseInt(tempTotalPanes) * tempPaneWidth;
			
			this.paneCount = tempPaneCount;
			
			if(this.paneCount > 1)
				this.scrollRightButton.show();
		}
		
	},
	scrollCarousel: function(dir) {
		var cssDir= (dir==-1) ? 'right':'left';
		var scrollWidth = this.scrollWidth;
		var scrollSpeed = this.scrollWidth;
		var scrollWrapLeft = $(this.scrollWrap).css("left");

		if(this.okToScroll == false) {
			return;
		}
		var newScrollWrapLeft = (parseInt(scrollWrapLeft) + (dir * scrollWidth));
		if(cssDir == "left") {
			if(this.currentPane <= 1) {
				return;
			} else {
				$(this.scrollRightButton).show();
				var self = this;
				this.okToScroll = false;
				$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
					self.okToScroll = true;
				});
				this.currentPane--;
			}
		}
		if(cssDir == "right") {
			if(this.currentPane >= this.paneCount) {
				return;
			} else {
				$(this.scrollLeftButton).show();
				this.okToScroll = false;
				var self = this;
				$(this.scrollWrap).animate({left: newScrollWrapLeft+"px"}, "slow", function() {
					self.okToScroll = true;
				});
				this.currentPane++;
			}
		}
		
		this.checkCurrentPane(this.currentPane, this.paneCount);
	},
	checkCurrentPane: function(currentPane, paneCount) {
		if(currentPane == 1) {
			$(this.scrollLeftButton).hide();
		} else if(currentPane == paneCount) {
			$(this.scrollRightButton).hide();
		}
	}
}

function validateForm(form) {
	var showError = false;
	// starting with text fields
	$(".required > input:text", form).each(function() {
		if(this.value == "") {
			showFormError($(this).parent(".required"));
			showError = true;
		} else {
			if(this.id=="displayName") {
				console.log("checking");
				checkUsernameAvail($("#checkUserName"));
				if($("#userNameAvailMessage").html() != "This user name is available.")
					showError = true;
				
			} else {
				hideFormError($(this).parent(".required"));
			}
		}
	});
	$(".required > input:password", form).each(function() {
		if(this.value == "") {
			showFormError($(this).parent(".required"));
			showError = true;
		} else {
			hideFormError($(this).parent(".required"));
		}
	});
	// next is textareas
	$(".required > textarea", form).each(function() {
		if(this.value == "") {
			showFormError($(this).parent(".required"));
			showError = true;
		} else {
			hideFormError($(this).parent(".required"));
		}
	});
	// textareas
	$(".required > select", form).each(function() {
		if(this.value == "") {
			showFormError($(this).parent(".required"));
			showError = true;
		} else {
			hideFormError($(this).parent(".required"));
		}
	});
	// checkboxes are done individually
	$(".required:checkbox", form).each(function() {
		
		if(!this.checked) {
			$(this).parent("label").css("color", "red");
			showError = true;
		} else {
			$(this).parent("label").css("color", "inherit");
		}
	});
	
	if(showError) {
		$(".formErrorMessageWrap", form).show();
		return false;
	} else {
		$(".formErrorMessageWrap", form).hide();
	}
	
}
function showFormError(rowEl) {
	rowEl.css("color", "red");	
	if($(".errorIcon", rowEl).length > 0) {
		$(".errorIcon", rowEl).show();	
	} else {
		$(rowEl).append("<div class='errorIcon'></div>");
	}
}
function hideFormError(rowEl) {
	rowEl.css("color", "inherit");	
	$(".errorIcon", rowEl).hide();
}


function showCheckLink(el, button) {
	el.next("span").attr("class","")
	button.show();
	button.next("span").html("");
	el.unbind("focus");
}

function checkUsernameAvail(button) {
	var el = document.getElementById("displayName");
	if(el.value == "")
		return false;
	var el = $(el);
	$.ajax({
		type: "GET",url: "/Handlers/CheckUser.aspx",dataType:"json",cache:false,async:false,data:"username="+el.val(),
		success: function(unameResult){
			if(!unameResult.processed) {
				var errorSpan = el.next("span");
				errorSpan.attr("class","errorIcon");
				button.hide();
				button.next("span").html("Unavailable. Please try again.");
				el.bind("focus", function() {
					showCheckLink(el, button);
				});
				console.log("failed");
				return false;
			} else {
				var errorSpan = el.next("span");
				errorSpan.addClass("checkIcon");
				button.hide();
				button.next("span").html("This user name is available.");
				var curVal = el.val();			
				el.bind("blur", function() {
					if(el.val() != curVal)
						showCheckLink(el, button);
				});
				console.log("passed");
				return true;
			}
		}
	});
}

var quizObj = {
	initQuiz: function (quizId) {
		//this goes through the itemQuizs array and initializes all quizs on a page
	
		var quizForm = $("#"+quizId);
		var quizContainer = $("#"+quizId+"Container");
		var quizurl = quizForm.attr("action");
		
		
		var self = this;
		$.ajax({
			type: "GET",url: "/Handlers/Quiz.aspx",dataType: "json",cache:false,data:"id="+quizId+"&userID="+readCookie("userID"),
			success: function(quizJSON){
				if(quizJSON.userClicked) {
					var quizAnswerTexts = self.getQuizAnswerTexts(quizForm, quizId);
					quizResults = self.buildQuizResults(quizJSON, quizAnswerTexts, quizId, false);
					quizMessage = self.buildExplanationSource(quizJSON.message);
				
					$(".quizModule:has(#"+quizId+")").after(quizMessage);
					
					swfobject.embedSWF('/Media/flash/textReplace.swf', "explanationTItle", '100%', '23', '9.0.124', '', {t:"Explanation", d:"explanationTItle"}, {menu:'false', quality:'best', scale:'noscale', wmode:'transparent'});
					
					
					quizContainer.animate({opacity: 'hide'}, "fast", function() {
						quizContainer.html(quizResults).animate({opacity: 'show'}, "slow");
						
					});
				} else {
					quizForm.submit(function() {
						self.submitQuiz(quizId,quizForm,quizContainer,quizurl);
						return false;
					});
				}
			}
		});
		
	},
	submitQuiz: function (quizId,quizForm,quizContainer,quizurl) {
		var quizValue;
		$("input:radio").each( function(f) {
			if($("input:radio:eq("+f+")", "#"+quizId).attr("checked"))
				quizValue = $(this).attr("value");
		});
		
		if(!quizValue)
			alert("Please select an answer.");
		else {
			var self = this;
			$.ajax({
				type: "GET",
				url: "/Handlers/QuizClick.aspx",
				data: "id="+quizId+"&choiceId="+quizValue+"&userid="+userId,
				cache:false,
				success: function(quizResults){
					if(quizResults.processed = true)
						self.getQuizResults(userId,quizId,quizForm,quizContainer,quizurl, quizValue);
				}
			});
		}
		return false;
	},
	getQuizResults: function (userid,quizId,quizForm,quizContainer,quizurl,quizValue) {
		var self = this;
		$.ajax({
			type: "GET",url: "/Handlers/Quiz.aspx",dataType:"json",cache:false,data:"id="+quizId+"&userid="+userid,
			success: function(quizresults){
				quizAnswerTexts = self.getQuizAnswerTexts(quizForm, quizId);
				quizResults = self.buildQuizResults(quizresults, quizAnswerTexts, quizId, quizValue);
				quizMessage = self.buildExplanationSource(quizresults.message);
				$(quizContainer).animate({opacity: 'hide'}, "fast", function() {
					$(quizContainer).html(quizResults);
					$(quizContainer).animate({opacity: 'show'}, "slow");
				});
				$(".quizModule:has(#"+quizId+")").after(quizMessage);
				swfobject.embedSWF('http://www.ussoccer.com/Media/flash/textReplace.swf', "explanationTItle", '100%', '23', '9.0.124', '', {t:"Explanation", d:"explanationTItle"}, {menu:'false', quality:'best', scale:'noscale', wmode:'transparent'});
			}
		});
	},
	buildExplanationSource: function(message) {
		return '<div class="moduleWrap quizModuleExplanation clear"><div class="moduleContentOuter"><div class="genericModuleHeader"><h4 id="explanationTItle"></h4></div><div class="moduleContentInner">'+message+'</div></div></div>';
	},
	// function to build quiz result
	buildQuizResults: function (quizJSON, quizAnswerTexts, quizId, firstTime) {
		var quizResultsSource = new Array;
		var quizAnswersCount = 0;
		var correctAnswer = quizJSON.correctId;
		
		
		for(i=0;i<quizJSON.poll.length;i++) {
			quizPercentage = quizJSON.poll[i].percentage;
			if(quizPercentage < 2)
				quizPercentage = 1;
			var idRef = quizJSON.poll[i].itemId;
			
			var correctClass = (idRef == correctAnswer)?" correctAnswer":"";
			var correctIcon = (idRef == correctAnswer)?"<img src='/Media/quiz_correct_mark.gif' alt='Correct Answer' />":"";
				
			quizResultsSource[quizAnswerTexts[idRef]] = "<div class='quizResultRow clear"+correctClass+"'><p class='quizResultRowPercentage'>"+correctIcon+""+quizJSON.poll[i].percentage+"% </p><p>&nbsp;"+quizAnswerTexts[idRef]+"</p></div>";
			
			
			quizAnswersCount++;
		}
		var quizResultsSourceOrdered = new Array();
		if(firstTime !== false) {
			if(correctAnswer == firstTime) {
				quizResultsSourceOrdered.push("<p class='quizCorrectMessage'><span>CORRECT!</span></p>");
			} else {
				quizResultsSourceOrdered.push("<p class='quizIncorrectMessage'><span>INCORRECT</span> View correct answer below.</p>");
			}
		}
		//quizResultsSourceOrdered.push("<p class='quizTotalClicks'>Total: "+quizJSON.totalClicks+"</p>");
		// re-order to match initial state
		
		for(i=0;i<=quizJSON.poll.length;i++) {
			var sourceKey = quizAnswerTexts[quizId+i];
			var addSource = quizResultsSource[sourceKey];
			quizResultsSourceOrdered.push(addSource);
		}
		return quizResultsSourceOrdered.join("");
	},
	// this gets the answer text from each quiz question to use in results source
	getQuizAnswerTexts: function (quizForm, quizId) {
		var labels = $("label", quizForm);
		var labelTexts =new Object;
		for(i=0; i<labels.length;i++) {
			
			var answerId = $("label:eq("+i+") input", quizForm).attr("value");
			var answerText = $("label:eq("+i+") span", quizForm).html();
			labelTexts[answerId] = answerText;
			labelTexts[quizId+i] = answerText;
	
		}
		$(quizForm).html("<div class='quizError'>Loading</div>");
		return labelTexts;
	}
}
