function jsonCallback(data)
{
    return data;
}

function openJanrainModal() {

    /* JANRAIN CODE UPDATES */
    $("#janrainModal").dialog({
        height: 480,
        width: 860,
        modal: true
    });

    /* IE7 Hack for Forgot Password Peek a Boo Issue */
    $('#janrainModal').css('zoom', 1.1);
    $('#janrainModal').css('zoom', 1);

    $('.janrainContent').width('386px');
    $('.janrainContent').css('borderRadius', '0');
    $('.janrainContent').css('background-color', '#f1f1f1');
    $('.janrainHeader').css('margin-top', '5px');
    $('.janrainHeader').css('margin-bottom', '5px');
    $('.janrainHeader').css('background-color', '#f1f1f1');
    $('.janrainHeader').css('font-size', '14px').css('color', '#333').css('font-weight', 'bold');
    $('.janrainContent').css('padding-left', '13px');
    $('#janrainProviderPages').css('left', '13px');
    $('#janrainProviderPages').next().hide();
    $('#janrainView').next().width('386px').css('borderRadius', '0').css('background-color', '#f1f1f1');
    return false;
}

$(document).ready(function () {

    /* USERNAME BUTTON */
    $('#userNameBtn > ul').width($('#userNameBtn > ul').width() + 50);

    /* FAN ZONE */
    $('#headerTopBarButtons li.topNavLink > ul').width($('#headerTopBarButtons li.topNavLink > ul').width() + 21);

    /* JANRAIN CODE */

    if (typeof window.janrain !== 'object') window.janrain = {};
    window.janrain.settings = {};

    var regex = new RegExp('[?&]url(?:=([^&]*))?', 'i');
    var match = regex.exec(window.location.href);
    var retUrl = window.location.href;

    if (match) {
        retUrl = match[1];
    }

    janrain.settings.tokenUrl = location.protocol + '//' + ((window.hostname === "undefined") ? location.hostname : hostname) + '/handlers/AuthHandler.aspx?url=' + escape(retUrl);

    function isReady() { janrain.ready = true; };
    if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", isReady, false);
    } else {
        window.attachEvent('onload', isReady);
    }

    var e = document.createElement('script');
    e.type = 'text/javascript';
    e.id = 'janrainAuthWidget';

    if (document.location.protocol === 'https:') {
        e.src = 'https://rpxnow.com/js/lib/signin.ussoccer.com/engage.js';
    } else {
        e.src = 'http://widget-cdn.rpxnow.com/js/lib/signin.ussoccer.com/engage.js';
    }

    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(e, s);

    $('#signInRegister').bind('click', function () { openJanrainModal() });

    $('#janrainModal form').submit(function () {
        $('#janrainModal #signInForm .error').remove();
        var form = $(this);
        if (validateForm(form) !== false) {
            $.ajax({
                url: $(this).attr('action') + '?callback=jsonCallback&username=' + $('#username')[0].value + '&password=' + $('#password')[0].value,
                dataType: "jsonp",
                jsonpCallback: "jsonCallback",
                context: document.body,
                success: function (data) {
                    if (data.processed !== false) {
                        // Successful Login
                        location.reload();
                    }
                    else {
                        $('<span class="error">Login Failed</span>').insertAfter('#janrainModal form input[type=submit]');
                    }
                },
                error: function () {
                    $('<span class="error">Error. Please try again later.</span>').insertAfter('#janrainModal form input[type=submit]');
                }
            });
        }

        return false;
    });

    $('.benefits').each(function () {
        if ($(this).data('url')) {
            var myUrl = $(this).data('url');
            $.ajax({
                url: myUrl,
                dataType: "jsonp",
                jsonpCallback: "jsonCallback",
                success: function (data) {
                    $.each(data, function (key, val) {
                        $('.benefits').html(val);
                    });
                }
            });
        }
    });

    /* MEDIA LANDING CODE UPDATES */

    $(".toggleTagList").click(function () {

        if ($(this).next().css('display') == 'none') {
            $(this).next().css("display", "block");
            $(this).parent("li").addClass("subNavOpened");
        }
        else {
            $(this).next().css("display", "none");
            $(this).parent("li").removeClass("subNavOpened");
        }

        return false;
    });

    /* ---------------------------- */


    var tempNewHeightMatches = 0;
    var allHomeMatches = $(".matchesModule .homeUpcomingMatches");
    allHomeMatches.each(function () {
        if ($(this).height() > tempNewHeightMatches)
            tempNewHeightMatches = $(this).height();
    });
    allHomeMatches.height(tempNewHeightMatches);

    $(".searchField, .searchAgain, .newsletterEmail, #pass_pluck, #user_pluck").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;
        });
    });

    $(".pageDropDown").each(function () {
        if ($(this).prev(".dropDownNav").length > 0) {
            $(this).css("right", "0");
        }
    });

    $(".featuredTournHeader h5").each(function (i) {
        var parent = $(this).parent(".featuredTournHeader");
        var el = $(this);
        if (!this.id) {
            this.id = "tournTitleReplace" + i;
        }

        swfobject.embedSWF('/Media/flash/textReplaceWhite.swf', $(this).attr("id"), '100%', '23', '9.0.124', '', { t: escape($(this).text()), l: $("a:first", this).attr("href"), linktar: $("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 = "moduelTitleReplace" + i;
        }
        swfobject.embedSWF('/Media/flash/textReplace.swf', $(this).attr("id"), '100%', '23', '9.0.124', '', { t: escape($(this).text()), l: $("a:first", this).attr("href"), linktar: $("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() < 1255) {
        initImageReplace();
        layoutWrapper.addClass("altSize1024");
        $("#ooyalaPlayer848").hide();
        $("#ooyalaPlayer640").show();
    }
    else {
        $("#ooyalaPlayer848").show();
        $("#ooyalaPlayer640").hide();
    }

    curWinRef.bind("resize", function () {
        var scope = $(this);
        if (scope.width() < 1255 && !layoutWrapper.hasClass("altSize1024")) {
            layoutWrapper.addClass("altSize1024");
            initImageReplace();
        } else if (scope.width() >= 1255 && layoutWrapper.hasClass("altSize1024"))
            layoutWrapper.removeClass("altSize1024");
    });

    $(".footerNav").each(function (i) {
        $(".footerNav:eq(" + i + ")>li:first").addClass("first");
        $(".footerNav:eq(" + i + ")>li:last").addClass("last");
    });
    $(".footerNav>li>ul").each(function (i) {
        $("li:even", this).addClass("oddRow");
    });

    $(".imageTextCarousel").each(function (i) {
        var newScroller = new scrollObj(i);
    });

    $(".matchCarousel").each(function (i) {
        var newScroller = new matchScrollObj(i);
    });

    //track ad impressions
    var adCount = $(".adModule").length;
    trackEvent('ads', 'impressions', toString(window.location), adCount);
    // track ad click throughs
    $(".adModule a:first").bind("click", function () {
        tempUrl = $(this).attr("href");
        trackEvent('outbound', 'click', tempUrl);
    });

    $(".homeResultsModule table tbody tr:odd").addClass("oddRow");

    $(".teamLandScores tr:odd").addClass("oddRow");

    $(".genericTable tr:odd").addClass("oddRow");

    $("#bioMainData li:odd").addClass("oddRow");

    $(".matchFactsList 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();
        });
    });


    $("#registration form").attr("action", "/Registration/Register.aspx");

    $(".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 (typeof shareTimeout != "undefined")
            clearTimeout(shareTimeout);

        el.bind("mouseout", function () {
            shareTimeout = setTimeout("hideShareBox();", 1000);
        });
    });


    $(".genericForm").bind("submit", function (i) {
        var form = $(this);
        return validateForm(form);
    });

    // For each element of class shareBarRatings, prep the rating system for it
    $(".shareBarRatings").each(function (e) {
        prepRatingSystem(e);
    });


    $(".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 hideShareFlash() {
	shareTimeout = setTimeout("hideShareBox();",1000);
}

function getHtml(id) {
	tempHtml = $("#"+id).html();
	return tempHtml;
}

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('/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 openMatchTracker(mid, optUrl) {
	if(optUrl)
		openWin(""+optUrl+"/?id="+mid,'Match_Tracker',{width:990,height:675,scrollbars:0});
	else
		openWin("http://matchtracker.ussoccer.com/?id="+mid,'Match_Tracker',{width:990,height:675,scrollbars:0});
	return false;
}
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() {
		// Store a private reference to self
		_this=this;
		
		// Go through all of the the nav items
		$("#siteNavMain>li").each(function() {
			// If they're not the current one
			if (this!=_this) {
				// Make sure they're hidden
				$(this).removeClass("mainHover");
			}
		});
		
		$(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 cleanXHTML(source) {
	var pattern = /<img/g;
	source = source.split(">");
	for(i=0;i<=source.length;i++) {
		if(pattern.test(source[i])) {
			source[i] = source[i]+"/";
		}
	}
	return source.join(">");
}

/*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];
	}
}
function findFlashPos(str, x, y) {
	var offset = findPos(document.getElementById(str))
	offset[0] += x;
	offset[1] += y;
	return offset;
}
/**
 * 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();
		}
	}
}

// Date Validation
function isValidDate(day, mn, yr) {
    var result = true;

    if (day != '' || mn != '' || yr != '') {
        var dateVal = mn + "/" + day + "/" + yr;
        var dt = new Date(dateVal);

        if (dt.getDate() != day) {
            result = false;
        }
        else if (dt.getMonth() != mn - 1) {
            //this is for the purpose JavaScript starts the month from 0
            result = false;
        }
        else if (dt.getFullYear() != yr) {
            result = false;
        }
    }

    return result;
}

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 if($("#userNameAvailMessage").html() == "This user name is available.") {
					hideFormError($(this).parent(".required"));
				}
		    } else if(this.id == "email") {
		        var validateEmail = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
		        if(!validateEmail.test(this.value)) {
		            showFormError($(this).parent(".required"));
			        showError = true;
		        } else {
		            hideFormError($(this).parent(".required"));
		        }
			} 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"));
		}
	});
	// dropdowns
	$(".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", "");
		}
    });
    // dates
    $(".validDate", form).each(function () {
        var day = -1, mn = -1, yr = -1, counter = 0;

        $(this).children("select").each(function () {
            if (counter == 0) {
                mn = $(this)[0].value;
            }
            else if (counter == 1) {
                day = $(this)[0].value;
            }
            else if (counter == 2) {
                yr = $(this)[0].value;
            }
            else {
                return false;
            }
            counter++;
        });

        if (!isValidDate(day, mn, yr)) {
            showFormError($(this));
            showError = true;
        } else {
            hideFormError($(this));
        }
    });	

	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", "");	
	$(".errorIcon", rowEl).hide();
}


function showCheckLink(el, button) {
	el.next("span").attr("class","")
	button.show();
	button.next("span").html("");
	el.unbind("focus");
}
var deniedUsernameFragments = [/ussoccer/];
function usernameNotAllowed(inputValue) {
	for(i=0;i<deniedUsernameFragments.length;i++) {
		if(deniedUsernameFragments[i].test(inputValue) == true)
			return false;
	}
	return true;
}
function checkUsernameAvail(button) {
	var el = document.getElementById("displayName");
	var ifUsernameAllowed = usernameNotAllowed(el.value);

	if(el.value == "")
		return false;
	
	var el = $(el);
	if(ifUsernameAllowed == false) {
		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);
		});
		return false;
	} else {
		$.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('/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;
	}
}

function queryStr(parameter) 
{
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i=0;i<gy.length;i++) 
    {
        ft = gy[i].split("=");
        if (ft[0] == parameter)
        {return ft[1];}
    }
}

function matchScrollObj(i) {
	this.scrollWidth = $(".matchCarouselHide:eq("+i+")").width();
	this.currentPane = 1;
	this.totalScrollPanes = $(".matchCarouselHide:eq("+i+") .carouselItem").length;
	this.paneWidth = $(".matchCarouselHide:eq("+i+") .carouselItem:first").width() + parseInt($(".matchCarouselHide:eq("+i+") .carouselItem:first").css("margin-left")) + parseInt($(".matchCarouselHide:eq("+i+") .carouselItem:first").css("margin-right"));
	this.totalScrollPanes = parseInt(this.totalScrollPanes) * this.paneWidth;
	
	this.paneCount = Math.ceil(this.totalScrollPanes / this.scrollWidth);
	
	this.scrollHide = $(".matchCarouselHide:eq("+i+")");
	this.scrollWrap = $(".matchCarouselHide:eq("+i+") .matchCarouselWrap");
	$(this.scrollWrap).width(this.totalScrollPanes+"px");
	
	this.okToScroll = true;
	this.scrollLeftButton = $(".matchCarousel:eq("+i+")>.scrollCarouselLeft:first");
	this.scrollRightButton = $(".matchCarousel: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();
		
	if($(".matchCarousel a.current").length > 0) {
		$(".matchCarousel a.carouselItem").each(function(i) {
			if($(this).hasClass("current")) {
				count = ((i +1) * self.paneWidth) - self.paneWidth;
				scrollToNew = Math.floor((count / self.scrollWidth)) * -1;
				self.scrollCarousel(scrollToNew);
			}
		});
	}	
	
	$(window).bind("resize", function() {
		self.redefineCarousel(i);					  
	});
}

matchScrollObj.prototype = {
	redefineCarousel: function(i) {
		tempWidth  = $(".matchCarouselHide:eq("+i+")").width();
		tempTotalPanes = $(".matchCarouselHide:eq("+i+") .carouselItem").length;
		tempPaneWidth = $(".matchCarouselHide:eq("+i+") .carouselItem:first").width() + parseInt($(".matchCarouselHide:eq("+i+") .carouselItem:first").css("margin-left")) + parseInt($(".matchCarouselHide:eq("+i+") .carouselItem:first").css("margin-right"));
		tempTotalPanes = parseInt(tempTotalPanes) * tempPaneWidth;
		
		tempPaneCount = Math.ceil(tempTotalPanes / tempWidth);
		
		if(tempPaneWidth != this.paneWidth) {
			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.scrollWrap).width(this.totalScrollPanes+"px");
			
			this.paneCount = tempPaneCount;
			
			if(this.paneCount > 1)
				this.scrollRightButton.show();
			
			
		}
		var self = this;
		if($(".matchCarousel a.current").length > 0) {
			$(".matchCarousel a.carouselItem").each(function(i) {
				if($(this).hasClass("current")) {
					count = ((i +1) * self.paneWidth) - self.paneWidth;
					scrollToNew = Math.floor((count / self.scrollWidth)) * -1;
					self.scrollCarousel(scrollToNew);
					
					
					/*count = (i +1) * tempPaneWidth;
					scrollToNew = (count / parseInt(tempTotalPanes)) * -1;
					scrollToNew = (scrollToNew<1)? 0:Math.round(scrollToNew);
					self.scrollCarousel(scrollToNew);*/
				}
			});
		}
		
	},
	scrollCarousel: function(dir) {
		//console.log(dir);
		var cssDir= (dir<0) ? '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();
		}
	}
}

/**
* Prep Rating System.
* <p>
* When the mouse moves out of the ul, remove the ratingHover class
* Clear the .ratingDescription inner html
* Show .ratingTotalVotes
* </p>
* <p>
* When the mouse moves over one of the links
* Add the ratingHover class to the parent UL.
* Hide the total votes.
* Get the description from the element's title.
* Display the description in .ratingDescription
* </p>
* <p>
* When a rating is clicked,
* rate content accordingly.
* </p>
* @returns {void}
* @param {number} eq The index of the shareBarRatings we're lookign for.
* @see rateContent (calls)
* @see $(document).ready (called by) (related to shareBarRatings)
* @author Richard Rudzinski
*/
function prepRatingSystem(e) {
    //var rateInfo = $(".shareBarRatings:eq("+e+") li a:first");
    $(".shareBarRatings:eq(" + e + ") ul").mouseover(function () {

    });

    // When the mouse moves out of the ul, remove the ratingHover class
    // Clear the .ratingDescription inner html
    // Show .ratingTotalVotes
    $(".shareBarRatings:eq(" + e + ") ul").mouseout(function () {
        $(".shareBarRatings:eq(" + e + ") ul").removeClass("ratingHover");
        $(".ratingDescription").html("");
        $(".ratingTotalVotes").show();
    });

    // When the mouse moves over one of the links
    // Add the ratingHover class to the parent UL.
    // Hide the total votes.
    // Get the description from the element's title.
    // Display the description in .ratingDescription
    $(".shareBarRatings:eq(" + e + ")>ul>li a").mouseover(function () {
        $(".shareBarRatings:eq(" + e + ") ul").addClass("ratingHover");
        $(".ratingTotalVotes").hide();
        var thisDesc = $(this).attr("title");
        $(".ratingDescription").html(thisDesc);
    });

    // When a rating is clicked,
    // rate content accordingly.
    $(".shareBarRatings:eq(" + e + ")>ul>li a").click(function () {
        rateContent(this);
        return false;
    });
}

/**
* Function to submit a rating.
* <p>
* Get the url to send to from the passed element's href.
* Get the user id from the userId cookie.
* Tack the page id from jCore.itemID and the userID from the cookie on to the url to be called.
* Display a "Calculating..." message in .shareBarRatings
* Make an ajax request, passing the call over.
* If it's successful, call updateRating(),
* if it's not display an error.
* </p>
* @returns {void}
* @param {element} el The element that was clicked to submit the rating.
* @see prepRatingSystem (called by)
* @see readCookie (calls)
* @see updateRating (calls)
* @author Richard Rudzinski
*/
function rateContent(el) {

    var rateResultPage = $(el).attr("href");
    var userId = readCookie("userID");
    rateResultPage = rateResultPage + "&id=" + jCore.itemId + "&userID=" + userId;
    $(".shareBarRatings").html("<p>...</p>");
    $.ajax({
        type: "GET", url: rateResultPage, dataType: "json", cache: false,
        success: function (rateJSON) {
            if (rateJSON.processed == true) {
                updateRating();
            } else if (rateJSON.processed == false) {
                $(".shareBarRatings").html("Error. Please try again later.");
            }
        }
    });
}
