if (typeof readCookie=="undefined") {
	readCookie=jCore.readCookie;
}

$(document).ready(function() {	
	$(".countdownClock").each(function(i) {
		countdown($(this), i);
	});
	
	var userName = checkUserCookie();
	
	initComments();
	
	checkForNewsFilters();
	
	initAjaxTabs();
	
	initHomepageFeatureWidget();
	
	initStaticCarousels();
	
	stripe();
	
	initInputs();
	
	initTabModules();
	
	initRotators();
	
	initTwitter();
	
	initSchedule();
	
	initFin();
	
	initLogin();

	initShareBar();
	
	prepRatingSystem();
	
	flashReplace();
	
	initCheckAvailability();
	
	forceFormHeights();
	
	initFormValidation();
	
	removeEmptyPollSubText();
	
	paginatorWidthFix();
	
	if (document.location.toString().indexOf("imaprettyprincess")!=-1) {
		showFlashOverlay('/Html/modules/home_flash_overlay.html');
	}
	
	initToggleShareBarKey();
	
	$('#newPasswordClose').click(function(e) {
		e.preventDefault();
		$('#newPasswordWarning').hide();
	});
});
/*************************************************
END OF DOC READY
*************************************************/

/** IE8 in IE7 compatibility mode was still showing these elements even when they were empty, blowing out the layout. */
function removeEmptyPollSubText() {
	$('.pollTextSub').each(function() {
		if ($(this).html()=="") { 
			$(this).hide(); 
		}
	});
}

/**
 * In FF2, the width of the .genericPagination doesn't correctly shrink to that of the UL within it.
 * This should fix that.
 */
function paginatorWidthFix() {
	$('.genericPagination').each(function() {
		if ($(this).width()>200) {
			$(this).css('width', $(this).find('ul').width()+8);
		}
	});
}

function forceFormHeights() {
	var wrapperHeight=$('#wrapper_content_main').height();
	var fm=$('.formModule');
	var formHeight=fm.height();
	if (formHeight<wrapperHeight) {
		fm.css('min-height', wrapperHeight);
	}
}

function initFlashOverlay(url) {
	if ($('#homeFlashOverlay').length==0) {
		$('#homeFlash').append('<div id="homeFlashOverlay"><iframe id="homeFlashOverlay" scrolling="no" frameborder="0" src="'+ url + '"></iframe></div>');
		$('#homeFlashOverlay').hide();
	}
}

function showFlashOverlay(url) {
	if (document.getElementById("homeFlash")) {
		if (url && url.length > 0) {
			initFlashOverlay(url);
			document.getElementById("homeFlashOverlay").src = url;
			$('#homeFlashOverlay').show();
		}
	}
}

function hideFlashOverlay() {
	$('#homeFlashOverlay').hide();
}

function prepRatingSystem() {
	$(".shareBarRatings").each(function(e) {
		var scope = this;
		var rateInfo = $(".shareBarRatings:eq("+e+") li a:first");
			
		$(".shareBarRatings:eq("+e+") ul").mouseover(function() {
			$(".shareBarRatings:eq("+e+") ul").addClass("ratingHover");				   
		});
		
		$(".shareBarRatings:eq("+e+") ul").mouseout(function() {
			$(".shareBarRatings:eq("+e+") ul").removeClass("ratingHover");		
			$(".ratingDescription").html("");
			$(".currentRating", scope).show();
		});
		
		$(".shareBarRatings:eq("+e+")>ul>li a").mouseover(function() {
			$(".currentRating", scope).hide();
			var thisDesc = $(this).attr("title");
			thisDesc = "&raquo; "+thisDesc;
			$(".ratingDescription").html(thisDesc);
		});

		$(".shareBarRatings:eq(" + e + ")>ul>li a").click(function() {
		    pageTracker._trackEvent('Social', 'Rate', location.href, $(this).attr("title"))
			rateContent(this);
			return false;
		});
	});
}
// function to submit rating
function rateContent(el) {
	var rateResultPage = $(el).attr("href");	
	$.ajax({
		type: "GET",url: rateResultPage+"&id="+jCore.itemId+"&userid="+jCore.itemStats.userId,dataType: "json",cache:false,
		success: function(rateJSON){
			if(rateJSON.processed == true) {
				updateRating();
			} else {
				updateRating();
				//$(".shareBarRatings").html("Error. Please try again later.");
			}
		}
	});
}
function updateRating() {
	$.ajax({type: "GET", url: "/Handlers/ItemStats.ajax", data:"id="+jCore.itemId+"&userid="+jCore.itemStats.userId,dataType:"json",cache:false,
	   success: function(updatedItemStatistics){
			updateRatingStats(updatedItemStatistics);
			if (updatedItemStatistics.userVoted) {
				disableRatings();
			}
		}
	});
}

var addthis_config={services_exclude: "email", ui_offset_top: -20, ui_offset_left: 0};

function ensureFlashAddThis() {
	if (!document.getElementById('flashAddThis')) {
		if ($('#mainContentCol0').length>0) {
			$('#mainContentCol0').prepend('<a id="flashAddThis" href="#"></a>');
		} else {
			$('#mainContentCol1').prepend('<a id="flashAddThis" href="#"></a>');
		}
	}
}

// Handler for Flash to call to fire addThis share
// Expects a#flashAddThis in the code wherever we want it to appear.
function showAddThisShare() {
	ensureFlashAddThis();
	var linkEl=document.getElementById('flashAddThis');
	if (linkEl) {
		addthis_open(linkEl, 'share', '[url]', '[title]');
	}
}

// Handler for Flash to call to fire addThis email
// Expects a#flashAddThis in the code wherever we want it to appear.
function showAddThisEmail() {
	ensureFlashAddThis();
	var linkEl=document.getElementById('flashAddThis');
	if (linkEl) {
		addthis_open(linkEl, 'email', '[url]', '[title]');
	}
}

// Listen to the handler Flash expects.
function toggleShareBar() {
	ensureFlashAddThis();
	showAddThisShare();
}

function initToggleShareBarKey() {
	$(document).keyup(function(e) {
		if (e.keyCode==192) {
			toggleShareBar();
		}
	});
}

function initShareBar() {
    $('.shareBarLinksShare a').each(function() {
        this.onclick = function(e) {
            pageTracker._trackEvent('Social', 'Share', location.href)
            addthis_open(this, 'share', '[url]', '[title]');
            return false;
        }
    });
	
	$('.shareBarLinksEmail a').each(function() {
		this.onclick=function(e) {
		    pageTracker._trackEvent('Social', 'Email', location.href)
			addthis_open(this, 'email', '[url]', '[title]');
			return false;
		}
	});

	$('.shareBarLinksPrint a').click(function(e) {
	    pageTracker._trackEvent('Social', 'Print', location.href)
		e.preventDefault();
		window.print();
	});
}

var mouseLoc={x:0,y:800};
var halfH=56;
var halfW=53;
var keyBuffer="";

function initFin() {
	if ((document.location.toString().indexOf("stayoutofthewater")!=-1)) {
		if (navigator.appName=="Netscape") {
			$("body").prepend('<div id="fin" style="background: url(/Media/placeholder/fin.png) top left no-repeat; width: 107px; height: 112px; position: absolute; top: 800px; left: 0; z-index: 1;"></div>');
			$("#body2").css('z-index', 2);
			
			$(document).mousemove(function(e) {
				mouseLoc.x=e.pageX;
				mouseLoc.y=e.pageY;
				if (mouseLoc.y<800) mouseLoc.y=800;
				
			});
			
			$(document).keyup(function(e) {
				keyBuffer+=e.keyCode;
				if (keyBuffer.length>20) {
					keyBuffer=keyBuffer.substring(keyBuffer.length-20,20);
				}
				if (keyBuffer.indexOf("3838404037393739")!=-1) {
					keyBuffer="";
					$('#fin').css('background-image', 'url(/Media/placeholder/fin2.png)');
					$('#fin').css('width', 300);
					$('#fin').css('height', 143);
					halfH=72;
					halfW=150;
					setTimeout(function() {
						$('#fin').css('background-image', 'url(/Media/placeholder/fin.png)');
						$('#fin').css('width', 107);
						$('#fin').css('height', 112);
						halfH=56;
						halfW=53;
					}, 10000);
				}
			});
			
			setInterval(function() {	
				var f=$('#fin');
				var pos=f.offset();
				var x=pos.left+halfW;
				var y=pos.top-halfH;
				var dX=mouseLoc.x-x;
				var dY=mouseLoc.y-y;
				var newX=x+(dX/2)-halfW;
				var newY=y+(dY/2)+halfH;
				f.css('left', newX);
				f.css('top', newY);
				if (dX<0) {
					f.css('background-position', 'top left');
				} else {
					f.css('background-position', 'top right');
				}
			}, 500);
		}
	}
}

function checkUserCookie() {
	if(jCore.readCookie("userName"))
		return jCore.readCookie("userName");
	//else
		//jCore.writeCookie("userName","testUser");
}
var viewAllClicked = false;
function submitNewComment(form) {
	if($("#comment").val() != "") {
		var submitURL = $(form).attr("action");
		var commentString = $("#comment").val();
		commentStringEncoded = escape(commentString);
		$.ajax({type: "POST", url: submitURL, data:"id="+jCore.itemId+"&userid="+jCore.itemStats.userId+"&comment="+commentStringEncoded,dataType:"json",cache:false,
			success: function(commentResponse){
				if(commentResponse.processed == true) {
					addNewComment();
					updateRating();
				}
			}
		});
	}
	return false;
}
function addNewComment(userNameComment, commentContent) {
	$("#comment").val("");
	$(".commentFormHidden").hide();
	if(viewAllClicked == true)
		getAllComments();
	else
		getComments(jCore.itemId, 1, 4);
}

function getAllComments() {
	getComments(jCore.itemId, 1, "");
}
function getComments(id, from, count) {
	jCore.itemId = id;
	$.ajax({type: "GET", url: "/Handlers/Comments.ajax", data:"id="+id+"&from="+from+"&count="+count,dataType:"json",cache:false,
		success: function(requestedComments){
			if (typeof console != "undefined") {
				if (typeof console.log != "undefined") {
					console.log(jCore);
				}
			}
			outputComments(requestedComments);
		}
	});
}
function outputComments(requestedCommentsObj) {
	var commentsSource = new Array;
	
	if($("#comments").hasClass("commentBubbleLarge")){
		inner = "commentItemInnerLarge";
		outer =  "commentItemOuterLarge";
	}else{
		inner = "commentItemInner";
		outer =  "commentItemOuter";
	}
		
	for(i=0;i<requestedCommentsObj.comments.length;i++) {
		if (i%2 == 0)
			striper = "even"
		else
			striper = "odd"

        commentsSource.push('<li class="' + striper + '"><div class="' + outer + '"><div class="' + inner + '"><p>' + requestedCommentsObj.comments[i].comment + '</p><div class="commentContent"><span class="commentDate">' + requestedCommentsObj.comments[i].date + '</span><a href="'+$('#addCommentLink').attr('rel')+encodeURI(requestedCommentsObj.comments[i].username)+'" class="commentUser">' + requestedCommentsObj.comments[i].username + '</a></div></div></div></li>');
	}
	/*	Sample source:
		<li>
			<div class="commentItemOuter">
				<div class="commentItemInner">
					<p>Donec congue suscipit sem, id imperdiet ligula dapibus non. Pellentesque congue justo id eros volutpat ut sodales mauris lacinia. Ut pretium, metus sed hendrerit tempus, quam lectus fringilla dolor, vel congue diam orci vitae arcu. Sed eget velit volutpat felis laoreet mollis. Vivamus ac tellus ligula, a vestibulum risus.</p>
					<span class="commentDate">April 16 2009</span><a href="" class="commentUser">Usernamehere</a>
				</div>
			</div>
		</li>
	*/
	$("ul.commentContainer").html(commentsSource.join(""));
	if(jCore.itemStats.comments && parseFloat(jCore.itemStats.comments) < 5)
		$(".commentViewAll").hide();
	else
		$(".commentViewAll").show();
	
	// IE 7 and below fix
	// For some stupid reason, IE 7 loses the height of the #comments area when it's dynamically populated.
	// Hiding and then redisplaying the page forces IE to recalculate.
	var appString=navigator.appVersion.toString();
	if (appString.indexOf('MSIE')!=-1) {
		var appVer=parseInt(appString.substring(appString.indexOf("MSIE")+5), 10);
		if (appVer<8) {
			$('#body2').hide();
			$('#body2').show();
		}
	}
}
/* end comment functionality */
function initComments() {
	if(document.getElementById("comments"))
		getComments(jCore.itemId,1,4);
	$("#commentFormSignup").hide();
	$("#addCommentLink").click(function() {
		$("#commentFormSignup").toggle();
		return false;
	});
	$("#commentsViewAllButton").click(function() {
		viewAllClicked = true;
		getAllComments();
		return false;
	});
	// this will check if there is a username. if there is, we assume they are logged in and show the comment form
	$("#commentFormSignup").each(function() {
		if(jCore.readCookie("userName")) {
			$("#commentFormSignup").html('<form action="/Handlers/Comment.ajax" method="post" id="commentFormInput" onsubmit="return submitNewComment(this);"><p>Please add your comment in the text field below.</p><textarea name="comment" id="comment"></textarea><button type="submit" class="submit">Submit</button><button type="reset" class="clearButton">Clear</button><div class="clear"></div></form>');
		}
	});
}
/**
	Stripe all lis and tbody trs.
	Additionally add first and last classes.
	Will clean up any prior versions so can be repeatedly applied.
	Takes an optional root element. If no root element is specified, will run from body.
*/
function stripe(el) {
	if (typeof el=="undefined") {
		el="body";
	}
	el=jQuery(el);
	el.find('li:nth-child(2n+1), tbody tr:nth-child(2n+1)').addClass('odd').removeClass('even').removeClass('first').removeClass('last');
	el.find('li:nth-child(2n), tbody tr:nth-child(2n)').addClass('even').removeClass('odd').removeClass('first').removeClass('last');
	el.find('li:nth-child(3n+2)').addClass('oneOfThree').removeClass('twoOfThree').removeClass('threeOfThree');
	el.find('li:nth-child(3n+1)').addClass('twoOfThree').removeClass('oneOfThree').removeClass('threeOfThree');
	el.find('li:nth-child(3n)').addClass('threeOfThree').removeClass('oneOfThree').removeClass('twoOfThree');
	el.find('li:first-child, tbody tr:first-child').addClass('first');
	el.find('li:last-child, tbody tr:last-child').addClass('last');
}

function initInputs() {
	$('input[type!=radio]').focus(function() {
		if ((typeof this.defaultValue != "undefined") && (typeof this.defaultValue != "null")) {
			if (this.value==this.defaultValue) {
				this.value="";
			}
		}
	}).blur(function() {
		if ((typeof this.defaultValue != "undefined") && (typeof this.defaultValue != "null")) {
			if (this.value=="") {
				this.value=this.defaultValue;
			}
		}
	});
}

function initStaticCarousels() {
	jQuery('.carouselModule .moduleContentInner').show(); // Unhide the content (kept hidden until the carousel is right about ready to initialize)
	jQuery('.carouselModule .moduleContentInner ul').jcarousel(); // Init the carousel.
}

var carouselHomepageObj=null;

function loadHomepageFeatureWidgetCarousel(url) {
	jQuery.ajax({
		url: url,
		success: function(data) {
			if (carouselHomepageObj!=null) {
				// If there's an existing carousel, lock it as we're about to build a new one.
				carouselHomepageObj.lock();
			}
			jQuery('.homepageFeatureWidgetContent').html(data);
			var carouselEl=jQuery('.homepageFeatureWidgetContent ul.homepageCarousel');
			
			// Swap the background to either the carousel or non carousel version
			if (carouselEl.length==0) {
				jQuery('.homepageFeatureWidget').css('background-position', 'bottom left');
			} else {
				jQuery('.homepageFeatureWidget').css('background-position', 'top left');
			}
			
			// Initialize the carousel so it callsback with its reference that way we can disable it later
			carouselEl.jcarousel({
				initCallback: function(carousel) {
					carouselHomepageObj=carousel;
				}
			});
		},
		error: function(data) {
			alert("Unable to load content in to the carousel.");
		}
	});
}

function initHomepageFeatureWidget() {
	if (jQuery('.homepageNavButtonsBody').length==0) return;
	
	if (jQuery('.homepageNavButtonsBody li.activeNav').length==0) {
		jQuery('.homepageNavButtonsBody li:first').addClass('activeNav');
	}
	var url=jQuery('.homepageNavButtonsBody li.activeNav a').attr('href');
	loadHomepageFeatureWidgetCarousel(url);
	
	jQuery('.homepageNavButtonsBody li a').click(function(e) {
		e.preventDefault();
		jQuery('.homepageNavButtonsBody li.activeNav').removeClass('activeNav');
		$(this.parentNode).addClass('activeNav');
		var url=$(this).attr('href');
		loadHomepageFeatureWidgetCarousel(url);
	});
}


function initAjaxTabs() {
	$(".ajaxTabModule").each(function() {
        var scope = this;
        var tabContent = $(".ajaxTabContent:first", scope);
        $(".ajaxTabsList li a", scope).click(function() {
            $(".ajaxTabsList li.active", scope).removeClass("active");
            $(this, scope).parent("li").addClass("active");
            $(tabContent).html("Loading");
            var newTabContent = this.href;
            $.ajax({ type: "GET", url: newTabContent,
                success: function(data) {
                    $(tabContent).html(data);
                }
            });
            return false;
        });
    });
}
function checkForNewsFilters() {
	var filter = new Array();
	$(".newsFilterArchive #newsArchiveFilter").each(function(i) {
		filter[i] = new Filter("newsArchiveFilter","newsArchiveFilterItem","newsArchiveList",20);
	});
}

function setTabModule(el, isInitializing) {
	el=$(el);
	parentModule=el.parents('.tabModule');
	tabsHolder=parentModule.find('.tabModuleTabs');
	
	// Change the active state
	tabsHolder.find('li.activeNav').removeClass('activeNav');
	el.parent().addClass('activeNav');
	
	// Hide all unwanted panes
	parentModule.find('.tabModulePane').hide();
	
	// If we have a rel, turn on the matching id
	if ( (el.is('.traditionalLink')) && (isInitializing==false) ) { 
		var newURL=el.attr('href').toString();
		if (document.location.toString().indexOf(newURL) != -1) {
			if (typeof console!="undefined") {
				if (typeof console.debug != "undefined") { 
					console.debug(newURL);
				}
			}
			document.location=newURL;
		}
	} else if (el.attr('rel')!="") {
		$('#'+el.attr('rel')).show();
	} else { // Otherwise, load the href in to the pane via AJAX
		parentModule.find('.tabModulePane').show().load(el.attr('href'));
	}
}

/**
 * Initialize the tab module system.
 * Find all of the links, bind them to call setTabModule when clicked.
 * If any have a parent li with .activeNav set, set them.
 */
function initTabModules() {
	$('.tabModuleTabs a').each(function() {
		$(this).click(function(e) {
			if ($(this).is('.traditionalLink')==false) {
				e.preventDefault();
			}
			setTabModule(this, false)
		});
		
		// Set the tab to active if either the .activeNav class is applied or it's a traditionalLink with the same href as the document.location
		if (   ($(this).parent().is('.activeNav'))   ||   (  ($(this).is('.traditionalLink')) && (document.location.toString().indexOf($(this).attr('href'))!=-1)  )   ) { 
			setTabModule(this, true);
		}
	});
}

/**
 * Handle rotatable images.
 * <p>
 * Pass a parent object in that contains images, links, whatever you want with class rotatable applied to them.
 * All but the first one will be hidden.
 * Periodically, the current one will be hidden and the next one displayed.
 * </p>
 * <p>
 * Additionally, a div with class rotatableControls will be prepended to the parent object.
 * It will contain links for each of the images. Clicking on any of them will stop the interval timer.
 * They will gain class "active" as the rotator moves to their corresponding image.
 */
function rotatorClass(parentEl) {
	// Store a local reference for all kinds of cool scope trickery
	var _this=this;
	
	// Store the parent set
	this.$_parentSet=$(parentEl);
	
	// Find all of the rotatable elements within
	this.$_rotatables=this.$_parentSet.find('.rotatable');
	this.$_rotatables.hide(); // Hide them
	$(this.$_rotatables[0]).show(); // Show the first one
	
	// Create the control bar
	this.$_parentSet.prepend('<div class="rotatableControls"></div>');
	this.$_rotatableControls=this.$_parentSet.find('.rotatableControls');
	for (var i=0; i<this.$_rotatables.length; i++) {
		this.$_rotatableControls.append('<a href="#" rel="'+i+'"><span>'+(i+1)+'</span></a>');
	}
	this.$_rotatableControlLinks=this.$_rotatableControls.find('a'); // Store the links separately
	this.$_rotatableControlLinks.click(function(e) { // Bind them all to the rotate method
		e.preventDefault();
		_this.rotate($(this).attr('rel'));
	});
	$(this.$_rotatableControlLinks[0]).addClass('active');
	
	
	// Set the counter for which image to show to 0
	this.currentPos=0;
	
	// Set up the interval
	this.interval=setInterval(function() {
		_this.rotate();
	}, 5000);
	
}

/**
 * Handle rotating the images within a rotator.
 * Takes a position. 
 * If the position is set, it'll stop the interval timer and auto rotation.
 * If no position is given, it'll just continue rotating as normal.
 * If the position goes off the end of the array, it'll move back to the start.
 */
rotatorClass.prototype.rotate=function(pos) {
	// If no pos was passed, get the current pos
	if ((typeof pos=="undefined") || (typeof pos=="null")) {
		pos=this.currentPos+1;
	} else { // Otherwise, just make sure the interval's no longer running
		clearInterval(this.interval);
	}
	
	// Loop back around if needed
	if (pos>=this.$_rotatables.length) pos=0;
	
	this.currentPos=pos;
	
	// Show/hide the correct images
	this.$_rotatables.hide();
	$(this.$_rotatables[pos]).show();
	
	// Set the active states for the control links
	this.$_rotatableControlLinks.removeClass('active');
	$(this.$_rotatableControlLinks[pos]).addClass('active');
}

/**
 * Set up all of the rotators on the page (if there are any)
 */
function initRotators() {
	$('.rotatableImages').each(function() {
		new rotatorClass(this);
	});
}

/**
 * Perform a twitter update via AJAX.
 * Reads the rel for the url to open
 * Loads it in.
 * Then stripes it.
 * @author Nick Davison
 */
function updateTwitter() {
	$('.twitterModule').each(function() {
		url=$(this).attr('rel');
		var contentEl=$(this).find('.moduleContentInner')
		contentEl.load(url, function() {
			stripe(contentEl);
		});
	});
}

/**
 * Set up the twitter module to update every 2 minutes (120,000 miliseconds)
 * @author Nick Davison
 */
function initTwitter() {
	// Make sure there is a twitter module on the page
	if ($('.twitterModule').length!=0) {
		// Set up the timer
		var twitterInterval=setInterval(updateTwitter, 120000);
		// And run an update now
		updateTwitter();
	}
}

/**
 * Set up the schedule accordian
 * @author Nick Davison
 */
function initSchedule() {
	if ($('.scheduleModule').length>0) { // Only run any of this code if there is a schedule module
		$('.scheduleDayOpen .scheduleEvents').show(); // Display any events lists that should be open by default
		
		$('a.scheduleDay').click(function(e){ // Bind all of the title links
			e.preventDefault();
			
			// Get the parent li and the sibling ul.scheduleEvents
			var $_parent=$(this).parent();
			var $_events=$_parent.find('ul.scheduleEvents');
			
			if ($_parent.is('.scheduleDayOpen')) { // If it's already open, close it
				$_parent.removeClass('scheduleDayOpen');
				$_events.slideUp();
			} else { // Otherwise open it
				$_parent.addClass('scheduleDayOpen');
				$_events.slideDown();
			}
		});
	}
}
var initLoginButtons = true;
/**
 * Set up header login
 * @author Micki Taylor
 */
function initLogin() {
	//if user is logged in
	if(jCore.readCookie("userName")){
		loggedInUser();
	}else{
		// Hide Login copy DIVs
		hideAllLoginCopy();
		// Hide Login buttons DIVs
		hideAllLoginButtons();
		// Show default DIVs
		$('#headerLoginDefault').show();	
		$('#headerLoginSignUpDefault').show();
	}

	if (initLoginButtons) {
	    initLoginButtons = false;
	    
	    // Default login button
	    $('#headerLoginLogin').click(function(e) {
	        e.preventDefault();

	        hideAllLoginCopy();
	        hideAllLoginButtons();
	        $('#headerLoginRequest').show();
	        $('#headerLoginInput').show();
	        $('#headerForgot').show();
	        return;
	    });
	    // Submit Username / Password
	    $('#theLoginForm').submit(function(e) {
	        e.preventDefault();

	        authenticate();
	        return;
	    });
	    // Setup forgot password request
	    $('#headerForgot').click(function(e) {
	        e.preventDefault();

	        hideAllLoginCopy();
	        hideAllLoginButtons();
	        $('#headerForgotRequest').show();
	        $('#headerForgotSubmitInput').show();
	        return;
	    });
	    // Submit username for forgot email process
	    $("#headerForgotSubmit").removeAttr("disabled");
	    $('#theForgotForm').submit(function(e) {
	        e.preventDefault();
	        $("#headerForgotSubmit").attr("disabled", "disabled");
	        forgotEmail();
	        return;
	    });
	    // Close login
	    $('.headerLoginClose').click(function(e) {
	        e.preventDefault();

	        initLogin();
	        return;
	    });
	    // Logout
	    $('#headerLoginLogout').click(function(e) {
	        e.preventDefault();

	        logout();
	        return;
	    });
	}
}
function loggedInUser(){
	hideAllLoginCopy();
	hideAllLoginButtons();
	$('#headerLoginWelcome').show();
	$('#headerLoginSignOut').show();
	$('#headerUsername').html(jCore.readCookie("userName") + "!");
}
function hideAllLoginCopy() {
	$('#headerLoginDefault,#headerLoginWelcome,#headerLoginRequest,#headerForgotRequest,#headerForgotSuccess').hide();
}
function hideAllLoginButtons() {
	$('#headerLoginSignUpDefault,#headerLoginSignOut,#headerLoginInput,#headerForgotSubmitInput,#headerTryAgain,#headerForgot,#headerMsgText,#headerForgotSuccessInput').hide();
}
// Check to see if user is in system
function authenticate() {
    var user = $('#username').val();
    var pass = $('#password').val();

	if(user == "" || pass == "") {
		$('#headerTryAgain').show();
        return false;
    }
    var dataStr = 'username=' + user + '&password=' + pass;
    $.ajax({
        type: 'POST',
        url: '/Handlers/Login.ajax',
        data: dataStr,
        cache: false,
        dataType: 'json',
        success: function(data) {
            if(data.processed == false) { 
				$('#headerTryAgain').show();
				$('#newPasswordWarning').show();
            } else {
                jCore.writeCookie("userID", data.userId);
                //jCore.writeCookie("userId", data.userId);
                jCore.writeCookie("userName",data.userName);
				loggedInUser();
				document.location.reload();
            }
        }
    });
    return false;
}
function forgotEmail() {
    var user = $('#usernameForgot').val();
	
	if(user == "" || user == "Username") {
		$('#headerMsgText').show();
		$("#headerForgotSubmit").removeAttr("disabled");
		$('#headerMsgText').html("Please enter a username.");
        return false;
    }
	$('#headerMsgText').show();
	$('#headerMsgText').html("One moment please...");
    var dataStr = 'username=' + user;
    $.ajax({
        type: 'POST',
        url: '/Handlers/ForgotPassword.aspx',
        data: dataStr,
        cache: false,
        dataType: 'json',
        success: function(data) {			
            if(data.processed == false) { 
				$("#headerForgotSubmit").removeAttr("disabled");
				$('#headerMsgText').show();
				$('#headerMsgText').html("That username does not exist in our system.");
            } else {
				hideAllLoginCopy();
				hideAllLoginButtons();
                $('#headerForgotSuccess,#headerForgotSuccessInput').show();
            }
        }
    });
    return false;
}
function logout(){		
	//initLogin();
	$.ajax({
	    type: 'POST',
	    url: '/Handlers/Logout.ajax',
	    cache: false,
	    dataType: 'json',
	    success: function(data) {
	        if (data.processed == false) {
	        } else {
	            jCore.deleteCookie("userID");
	            jCore.deleteCookie("userName");
	            document.location.reload();
	        }
	    }
	});
}

/**
 * Push out the graphics bars of the Poll results
 * @author Micki Taylor
 */
var theLrResult = 0;
var thePollPerc = 0;
//for each result bar displays 80% percent of the displayed number to fit within the box
$(".pollResultBar").each(function(){
	thePollPerc  = parseInt($(this).siblings("span").html().slice(0,$(".pollResultBar").siblings("span").html().indexOf("%")));
	//$(this).css({'width' : (thePollPerc * .8) + "%"}); //changes DIV width to % of SPAN
	//collect the highest % for highlighting
	if(thePollPerc > theLrResult){
		theLrResult = thePollPerc;
	}
});
//check each bar displayed for the largest % and change its bar to the highlight
$(".pollResultBar").each(function(){
	//if the largest % change result bar
	if($(this).siblings("span").html().slice(0,$(".pollResultBar").siblings("span").html().indexOf("%")) == theLrResult){
		$(this).css('background-image','url(/Media/backgrounds/poll_winning_result.gif)');
	} 
});


/**
 * Check to see if a username is available.
 * <p>
 * Gets the value from #username.
 * Checks /Handlers/CheckUser.aspx to see if it's available.<br/>
 * If it IS NOT available: Adds the class "error" and displays an error message.
 * If it IS available: Adds the class "success" and displays a success message.
 * </p>
 * @returns {void}
 * @see initCheckAvailability (called by)
 */
function checkUsernameAvail() {
	var el = document.getElementById("signupUsername");
	if(el.value == "")
		return false;
	var _passedUsername=el.value
	$.ajax({
			type: "GET",url: "/Handlers/CheckUser.aspx",dataType:"json",cache:false,data:"username="+_passedUsername,
			success: function(unameResult){
					$('#checkUserName').attr('rel', _passedUsername);
					if(!unameResult.processed) {
						$("#checkUserName").html("Unavailable. Please try again.");
						$("#checkUserName").addClass('error');
						$("#checkUserName").removeClass('success');
					} else {
						$("#checkUserName").html("This user name is available.");
						$("#checkUserName").addClass('success');
						$("#checkUserName").removeClass('error');
					}
			}
	});
}

function clearUsernameCheck() {
	if ($("#checkUserName").length>0) {
		if ($('#signupUsername').val()!=$("#checkUserName").attr('rel')) {
			$("#checkUserName").removeClass('success');
			$("#checkUserName").removeClass('error');
			$("#checkUserName").html('');
		}
	}
}

/**
 * Bind the check availability button and call checkUsernameAvail to perform those checks.
 */
function initCheckAvailability() {
	$('a#checkAvailability').click(function(e) {
		e.preventDefault();
		checkUsernameAvail();
	});

	$('#signupUsername').blur(function() {
	    checkUsernameAvail();
	});
	
	// Give IE a moment to catch up, then check to see if the username's changed from the checked username
	$('#signupUsername').keyup(function() {
		setTimeout(clearUsernameCheck, 100);
	});
}

function validateField(field, validateType) {
	field=$(field);
	if (field.length==0) {
		return true;
	}
	val=field.val();
	var isValid=true;
	
	// Check for fields that are not allowed to be empty
	if (validateType.indexOf("notempty")!=-1) {
		if (val=="") {
			isValid=false;
		}
	}
	
	// Check for fields that have to be a valid email address
	if (validateType.indexOf("email")!=-1) {
		var re=/^.+@.+\..{2,3}$/
		if (!re.test(val)) {
			isValid=false;
		}
	}
	
	// If a matchpassword is given, look immediately after it for the id of the field it has to match
	if (validateType.indexOf("matchpassword")!=-1) {
		var pwId=validateType.substring(14);
		if (val!=$('#'+pwId).val()) {
			isValid=false;
		}
	}
	
	// If a field requires #checkUserName to have class success, check for that
	if (validateType.indexOf("available")!=-1) {
		if (!$('#checkUserName').is('.success')) {
			isValid=false;
		}
	}
	
	// Find the parent .formRow
	var row=field.parents('.formRow');
	if (!isValid) { // If there was an error, add the error claass
		row.addClass('requiredError');
	} else { // Otherwise, remove the error class
		row.removeClass('requiredError');
	}
	
	// Return whether it was successful or unsuccessful
	return isValid;
}

function validateForm() {
	// Perform all of the different types of validation the site requires
	validateField('#signupUsername', 'notempty available');
	validateField('#signupEmail', 'email');
	validateField('#signupPassword', 'notempty');
	validateField('#signupConfirm', 'matchpassword signupPassword');

	validateField('#forgotUsername', 'notempty');

	validateField('#regPassword', 'notempty');
	validateField('#regRePassword', 'matchpassword regPassword');

	validateField('#loginUsername', 'notempty');
	validateField('#loginPassword', 'notempty');
	
	validateField('#personalFirstname', 'notempty');
	validateField('#personalLastname', 'notempty');
	validateField('#personalEmail', 'email');

	if ($('.requiredError').length == 0) {
	    // No errors
	    $('.formErrorMessageWrap').hide();
	    return true;
	} else {
	    $('.formErrorMessageWrap').show();
	    return false;
	}
}

function initFormValidation() {
	// Grab hold of the .genericForm and don't allow it to submit unless it validates
	$('.genericForm').each(function() {
		this.onsubmit=function() {
			return validateForm();
		}
	});
	
	// Do the same with the submit button
	$('.genericForm button.submit').each(function() {
		this.onclick=function() {
			return validateForm();
		}
	});
}