$(document).ready(function() {
	// Handle site search
	$('#but-search').click(function(event) {
		event.preventDefault();
		
		if ($('#keywords').val() != '') {
			$('#search-form').submit();
		} else {
			alert('Please enter a search term before clicking "Search"');
		}
	});
	
	// Handle Popup links
	$("a.pops").click(function(event) {
		var dims = this.rel.split('x');
		window.open(this.href, "pop", "width="+dims[0]+",height="+dims[1]+",menubar=no,status=no,toolbar=no");
		return false;
	});
	
	//	Handle Popup close links
	$("a.close").click(function(event) {
		window.close();
		return false;
	});
	
	// Handle show/hides
	$('a[@rel=showhide]').click(function(event) {
		$('div#' + this.href).slideToggle('slow');
		return false;
	});
	
	// Handle external links
	$("a[@rel=external]").click(function(event) {
		window.open(this.href);
		return false;
	});
	
	// Handle select all checkbox behavior
	$('input.select_all').click(function(event) {
		var id = $(this).attr('id').split('-')[0];
		$('input[@id^=' + id +']').each(function(i) {
			$(this).attr('checked','checked');
		});
	});
	
	//	Form field focus
	swapDefault();
	
	// Handle fake IE CSS :after
	if ( $.browser.msie && $('.bluebox a') ) {
		$('.bluebox a').append('&nbsp;<img src="/images/layout/bluearrow.gif" alt="" />');
	}
});

function showpage(el, dir) {
	var id 	= el.href.slice(-2, -1);
	var old = (dir == 'next') ? parseInt(id) - 1 : parseInt(id) + 1;
	$('#page'+old).hide();
	$('#page'+id).show();
}

// cookie functions http://www.quirksmode.org/js/cookies.html

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) { createCookie(name,"",-1); }

// Create Text Size control bar and build interaction

function textSize() {
	var textSize	= '<span class="textsize right">Text Size:<a href="" id="sm">A</a><a href="" id="md">A</a><a href="" id="lg">A</a></span>';
	$("div.content h2").before(textSize);
	$("span.textsize a").click(function() {
		var clss	= this.id;
		$(this).parents('span').children('a').removeClass("selected");
		$(this).addClass("selected");
		swapSheet(this.id);
		return false;
	});
}

// Append inline alternate stylesheets to DOM

function swapSheet(id) {
	 $("link[@rel*=alternate style]").each(function(i) {
		this.disabled = true;
		if (this.getAttribute('title') == id) this.disabled = false;
	});
	createCookie('style', id, 365);
}

// Find cookie and envoke correct stylesheet if set

function cookieExists() {
	var c = readCookie('style');
	if (c) { swapSheet(c); $("a#" + c).addClass("selected");
	} else { $("a#sm").addClass("selected"); }
}

// Remove useless whitespace from all unordered lists in a page
function cleanLists() {
	$("ul").each(function() {
		var node	= this.firstChild;
		while(node) {
			var nextNode	= node.nextSibling;
			if(node.nodeType == 3 && !(/\S/).test(node.nodeValue))
			this.removeChild(node);
			node	= nextNode;
		}
		return this;
	});
}

function swapDefault() {
	$("input.blankout").each(function() {
		$(this).focus(function() {
			if(this.defaultValue && this.value == this.defaultValue) this.value = "";
			$(this).addClass("focus");
		}).blur(function() {
			if(this.defaultValue && !this.value.length) this.value = this.defaultValue;
			$(this).removeClass("focus");
		});
	});
}

//	--------------------------------------
//	Validate
//	--------------------------------------

function validate ( form, error )
{
	var fields		= new Array( 'first', 'last', 'email' );
	var phones		= new Array();
	var radios		= new Array();
	var tbl_radios	= new Array();

	//	-------------------------------------
	//	Volunteer fields
	//	-------------------------------------
	
	if ( form == "volunteer" || form == "endorse" )
	{
		fields.push( 'street1' );
		fields.push( 'city' );
	}

	//	-------------------------------------
	//	Viral fields fields
	//	-------------------------------------
	
	if ( form == "raise-money" || form == "letter-to-editor" || form == "invite-friends" || "a-law" )
	{
		//	fields.push( 'subject' );
	}

	//	-------------------------------------
	//	Validate reg form
	//	-------------------------------------
	
	$("form#" + form).submit( function(event)
	{
		//	-------------------------------------
		//	Reset
		//	-------------------------------------
		
		var msg	= "";
		
		$("form#" + form + " input").parents("div").parents("li").removeClass("error");
		$("form#" + form + " select").parents("div").parents("li").removeClass("error");
		
		//	-------------------------------------
		//	Validate email
		//	-------------------------------------
		
		var email	= $("form#" + form + " input[@name='email']").val();
		
		if ( /^[^\s,;]+@([^\s.,;]+\.)+[\w-]{2,}$/i.test(email) == false )
		{
			$("form#" + form + " input[@name='email']").parents("div").parents("li").addClass("error");
			
			msg	+=	"<li>Please provide a valid email address.</li>"; 
		}
		
		//	-------------------------------------
		//	Validate phone
		//	-------------------------------------
		//	Disabling this as we assume some
		//	international people will submit forms
		//	-------------------------------------
		
		/*
		
		var phone			= '';
		
		var invalid_phone	= false;
		
		$.each( phones, function(i,n)
		{
			if ( $("form#" + form + " input[@name='" + n + "']").val() != '' )
			{
				phone	= $("form#" + form + " input[@name='" + n + "']").val();
		
				if ( /^[1-9]\d{2}\-?\d{3}\-\d{4}$/.test(phone) == false )
				{
					$("form#" + form + " input[@name='" + n + "']").parent("p").addClass("error");
					
					invalid_phone	= true;
				}
			}		
		});
		
		if ( invalid_phone )
		{
			msg	+=	"<li>Please format phone numbers as xxx-xxx-xxxx.</li>"; 
		}
		
		*/
		
		//	-------------------------------------
		//	Check password match
		//	-------------------------------------
		
		if ( $("form#" + form + " input[@name='password']").val() != $("form#" + form + " input[@name='password_confirm']").val() )
		{
			$("form#" + form + " input[@name='password']").parents("div").parents("li").addClass("error");
			
			$("form#" + form + " input[@name='password_confirm']").parents("div").parents("li").addClass("error");
			
			msg	+= "<li>Please make sure that your password confirmation matches your password.</li>";
		}
		
		//	-------------------------------------
		//	Check empties
		//	-------------------------------------
	
		var empty	= false;
		
		$.each( fields, function(i,n)
		{
			var val		= $("form#" + form + " input[@name='" + n + "']").parents("div").parents("li").children("label").attr("title");
			var current	=  $("form#" + form + " input[@name='" + n + "']").val();
			
			if ( current == val || current == "" )
			{
				empty	= true;
				
				$("form#" + form + " input[@name='" + n + "']").parents("div").parents("li").addClass("error");
			}		
		});
		
		if ( empty === true )
		{
			msg	+= "<li>Please complete the required fields.</li>";
		}
		
		//	-------------------------------------
		//	Show message
		//	-------------------------------------
		
		if ( msg != '' )
		{
			$("div#" + error).show();
			$("div#" + error).empty();
			$("div#" + error).append( "<ul>" + msg + "</ul>" );
		
			return false;
		}
	});
}