//Common Javascript function for the header
 function genericDialog(link,title,height,width)
	{
		$("#genericDialog").dialog({
						title: title,
						modal: true,
						autoOpen: false,
						height: height,
						width: width,
						open: function() {
							$("#genericDialog").load(link);
						}
		});
		window.scrollTo(100,100);
		$("#genericDialog").dialog('open');
		$(".ui-widget-overlay").live("click", function() { $("#genericDialog").dialog('close'); } );
}
var destination;
$(document).ready(function() {
	

	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 0.9).show();
		
		//Calculate width of all ul's
			$.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});
			//Make sure the menu does not go outside the #spread DIV
			var swidth = $('#spread').width();
			var tn = $(this).position();
			var subWidth = $(this).find(".sub").outerWidth();
			if((swidth - tn.left) < subWidth){
				var leftPos = (swidth - subWidth) - tn.left;
				$(this).find(".sub").css({'marginLeft' : leftPos});
			}
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		 $(this).hide();
	  });
	}


	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 500, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	$("ul#topnav li .sub").css({'opacity':'0'});
	$("ul#topnav li").hoverIntent(config);
	
	//So I wanted a way to call attention to a graphic element, thank-you Mac OSX!
	function bounceMe(){
		if($("img.bounceme").length > 0){
		$("img.bounceme").effect("bounce",{times:3});
		}
	}
	setInterval(bounceMe, 15000);
	
});
	
	function clearSearch(){
		var sBox = $('#txtSearch').val();
		if(sBox == "search"){
			$('#txtSearch').val("");
		}
	}
	function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
	}
	var shown = false;
	function showSignIn(toggle){
		showSearch(1);
		if(shown == true){
			$('#login').slideUp();
			shown = false;
		}else{
			if(toggle == 1){
				$('#login').slideDown();
				scroll(0,0);
				shown = true;
			}else{
				$('#login').slideUp();
				shown = false;
			}
		}
	}
	var formCache;
	function signIn(){
		formCache = $('#loginAccount').html();
		var url = "/ajax/login.ajax.php?t="+Math.floor(Math.random()*10000000);
		$.post(url,$('#formLogin').serialize(), function(data){
			if(data.error == 0){
				$('#loginStat').html(data.message);
				$('#loginStatus').html(data.util);
				if(destination != undefined){
					location.href=destination;
				}else{
					$('#loginAccount').html("<p class='green'>You are now signed in.</p><p>Take me to:</p><ul><li><a href='/myusac/index.php?pagename=mypage'>My USA Cycling</a></li><li><a href='javascript:void(0);' onclick='showSignIn(0)'>Stay Here</a></li></ul>");
					updateOverlay();
					$('#leftButton').html("<a href='/events/index.php'><img border='0' src='images/find_button.png' width='225' height='57' alt='Register' /></a><br/>");
				}
			}else{
				$('#laFormStat').html("<span class='error'>Sign In failed. Please try again</span>");
				$('#laFormStat').show();
				//showSignIn(0);
			}
		},'json');
	}
	function signOut(){
		var url = "/ajax/login.ajax.php?t="+Math.floor(Math.random()*10000000);
		$.post(url,'logout=1',function(data){
			if(data.error == 1){
				alert("An error occurred while trying to end your session!");
			}else{
				$('#loginStat').html(data.message);
				$('#loginStatus').html(data.util);
				$('#loginAccount').html(formCache);
				if($("#leftButton").length > 0){
					$('#leftButton').html("<a href='javascript:void(0)' onclick='showSignIn(1);'><img border='0' src='images/my_usac_button.png' width='225' height='57' alt='Register' /></a><br/>");
				}
				if(updateOverlay() == false){
					location.href = "/index.php";
				}
			}
		},"json");
	}
	function checkInput(field,form){
		$(field).keypress(function(e){
			c = e.which ? e.which : e.keyCode;
			if(c == 13){
				signIn();
			}
		});
	}
	var searching = false;
	function showSearch(s){
		if(shown == true && s != 1){
			showSignIn(false);
		}
		if(searching == false && s != 1){
			if(s != 1){
				$('#search').slideDown();
				$('#txtSearch').focus();
				searching = true;
			}
		}else{
			$('#search').slideUp();
			searching = false;
		}
	}
	function updateOverlay(){
		if($("#hpOverlayText").length > 0){
			var url = "/ajax/hpoverlay.ajax.php?t="+Math.floor(Math.random()*10000000);
			$('#hpOverlayText').load(url, function(){
				$(function() {
					$( "#tabs" ).tabs();
				});
			});
		}else{
			return false;
		}
	}

$('#txtSearch').keypress(function(e){
	c = e.which ? e.which : e.keyCode;
	if(c == 13){
		$('#formSearch').submit();
	}
});

function sessionCheck(url){
	$.get("/ajax/sessionCheck.ajax.php",function(data){
		if(data.message == "valid"){
			location.href=url;
		}else{
			destination = url;
			showSignIn(1);
		}
	},"json");
}
//Used by the register script to update the header after an account has been created
function updateHeader(){
	url = "/ajax/getSession.ajax.php";
	$.getJSON(url,function(data){
		if(data.session == 1){
			//Update the Header
			$('#loginStat').html(data.message);
			$('#loginStatus').html(data.util);
		}
	});
}
function copyToClipboard(s) {
	//Load the string into a pop-up dialog
	$("#genericDialog").html("<i>Copy the following text:</i><br/>" + s);
	$("#genericDialog").dialog({
			title: "Copy Link to USA Cycling Article",
			modal: true,
			height: 100,
			width:600
	});
}
