$.expr[':'].external = function(o) {
	return !o.href.match(/^mailto\:/) && (o.hostname !== location.hostname);
};



$(function() {



	// Maintain Nav State
	var currentURI = location.pathname;
	//var uriSegments = currentURI.replace('/^\//','').replace('/\/$/','').split('/');
	//console.log(uriSegments);



	// IE7
	if ( $.browser.msie && parseInt(jQuery.browser.version) <= 7 ) { $('#header-logo').after('<div style="width:1px;height:1px;margin-top:-1px"></div>'); }
	
	
	
	// Toggle Callout Icons
	if ($('#callout-nav').length) {
		$('#callout-nav a').hover(
			function() {
				$('.icon',this).css('backgroundImage',$('.icon',this).css('backgroundImage').replace('\-r\.','\-w\.'));
			},
			function() {
				if ( ! $(this).hasClass('active')) $('.icon',this).css('backgroundImage',$('.icon',this).css('backgroundImage').replace('\-w\.','\-r\.'));
			}
		)
	}



	// External Links in New Windows
	$('a:external').attr('target','_blank').addClass('external');



	// Feature Rotator
	if ($('#slides').length) {
		$('#slides').cycle({
			pager:'#slide-ctrl',
			pagerAnchorBuilder:function(i,e){
				return '<li><a href="#"></a></li>';
				}
		});
	}



	// Article Select
	if ($('#news,#events,#issues').length) {
		$('#news article:not(.single),#events article:not(.single),#issues article:not(.single)').hover(
			function(){ $(this).addClass('article-selected'); },
			function(){ $(this).removeClass('article-selected'); }
		);
	}



	// Put that red on the screen
	if ($('body.home').length && $('#events article').length) {
		$('#events').css('display','block');
		$('<div id="event-content-back" />').appendTo('body');
	}



	// Tweetify Tweets
	if ($('#twitter li').length) {
		$('#twitter li').each(function() {
			$(this).html(ify.clean($(this).text()));
		});
	}
	
	
	
	
	
	
	/* /// FORM SUBMISSIONS /// */
	
	// Track Form Loads on GA
	if ($('form').length) {
		$('form').each(function() {
			var id = $(this).attr('id');
			if (id !== '') {
				id = (id == 'petition')? id + ' - ' + $('#petition-id').val(): id;
				_gaq.push(['_trackEvent','Forms','Form Loaded',id]);
			}
		});
	}
	
	// Create Em-sub Form
	var emSubForm = '\
		<h3>Email Updates</h3>\
		<p>Sign up and stay informed.</p>\
		<form method="post" action="/cr/processor/em-sub/" id="em-sub">\
			<label>\
				<span class="title">First Name</span>\
				<input type="text" name="fname" id="em-sub-fname">\
			</label>\
			<label>\
				<span class="title">Last Name</span>\
				<input type="text" name="lname" id="em-sub-lname">\
			</label>\
			<label>\
				<span class="title">Email Address</span>\
				<input type="email" name="email" id="em-sub-email">\
			</label>\
			<label>\
				<span class="title">Zip Code</span>\
				<input type="text" name="zip" id="em-sub-zip">\
			</label>\
			<label class="sms">\
				<span class="title">Mobile Phone</span>\
				<input type="text" name="mobile" id="em-sub-mobile">\
			</label>\
			<label class="check">\
				<input type="checkbox" name="sms" id="em-sub-sms-sub"> Send me text updates\
			</label>\
			<button>Sign Up</button>\
		</form>\
		<a href="/em-sub/" class="close"><img src="/cr/images/em-sub-close.png"></a>';
	$('<section />',{ id:'em-sub-holder',style:'display:none' }).html(emSubForm).appendTo('#callout-nav');
	$('#callout-nav .em-sub a,#em-sub-holder a.close').click(function() {
		$('#em-sub-holder').slideToggle(200,function() {
			//console.log($('#em-sub-holder:visible').length);
			if ($('#em-sub-holder:visible').length) {
				$('#callout-nav .em-sub a').addClass('active');
				$('#em-sub-fname').focus();
			} else {
				$('#callout-nav .em-sub a').removeClass('active');
				$('#callout-nav .em-sub a .icon').css('backgroundImage',$('#callout-nav .em-sub a .icon').css('backgroundImage').replace('\-w\.','\-r\.'));
			}
		});
		return false;
	});
	
	// Validate & Handle Email Subscription Form
	if ($('#em-sub').length) {
		
		// Toggle SMS Subscription
		$('#em-sub input#em-sub-sms-sub').click(function() {
			if ($(this).is(':checked')) {
				$('#em-sub label.sms').slideDown(400,function() {
					$(this).css({display:'block'});
					$('#em-sub label.sms input').focus();
				});
			} else {
				$('#em-sub label.sms').slideUp(200,function() {
					$('#em-sub label.sms input').val('');
				});
			}
		});
		
		// Validate Email Subscription Form
		var emSubVal = {
			debug:true,
			rules: {
				fname:'required',
				lname:'required',
				email: {
					required:true,
					email:true
				},
				zip:'required',
				mobile: {
					required: {
						depends: function(e) {
							return $('#em-sub-sms-sub:checked').length;
						}
					}
				}
			},
			errorClass:'invalid',
			highlight:function(e,ec) {
				$(e).addClass(ec);
			},
			unhighlight:function(e,ec) {
				$(e).removeClass(ec);
				$(e).siblings('span.error').remove();
			},
			submitHandler:function(f) {
				formHide(f);
				$.ajax({
					type:'POST',
					url:$(f).attr('action'),
					dataType:'json',
					data:{
						action:'em-sub',
						jssub:'1',
						fname:$('input#em-sub-fname',f).val(),
						lname:$('input#em-sub-lname',f).val(),
						email:$('input#em-sub-email',f).val(),
						zip:$('input#em-sub-zip',f).val(),
						mobile:$('input#em-sub-mobile',f).val(),
						'em-sub':'1',
						'sms-sub':$('input#em-sub-sms-sub:checked').length
					},
					success:function(json) {
						var m = '';
						if (json.success) {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Submitted','em-sub']);
						} else {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Error','em-sub, json error']);
						}
						formShow(f,m,false,100);
					},
					error:function(x,t,e) {
						var m = '<p>There was a problem subscribing.</p>';
						formShow(f,m,true);
						_gaq.push(['_trackEvent','Forms','Form Error','em-sub']);
					}
				});
			},
			invalidHandler: function(f,v) {
			},
			errorPlacement: function(err,el) {
				var fn = $(el).siblings('span.title').text();
				$(el).siblings('span.error').remove();
				if(!$(el).siblings('span.error').length) {
					$(el).after('<span class="error">Please provide your <strong>'+fn+'</strong>.</span>');
				}
			}
		};
		$('#em-sub').validate(emSubVal);
		// Mask Phone & Zip Input
		$('form#em-sub input#em-sub-mobile').mask("999 999-9999",{placeholder:" "});
		$('form#em-sub input#em-sub-zip').mask("99999",{placeholder:" "});
	}
	
	
	
	// Validate & Handle Petition Form
	if ($('#petition').length) {
		
		// Toggle SMS Subscription
		$('#petition input#petition-sms-sub').click(function() {
			if ($(this).is(':checked')) {
				$('#petition label.sms').slideDown(400,function() {
					$(this).css({display:'block'});
					$('#petition label.sms input').focus();
				});
			} else {
				$('#petition label.sms').slideUp(200,function() {
					$('#petition label.sms input').val('');
				});
			}
		});
		
		// Validate Email Subscription Form
		var emSubVal = {
			debug:true,
			rules: {
				fname:'required',
				lname:'required',
				email: {
					required:true,
					email:true
				},
				zip:'required',
				mobile: {
					required: {
						depends: function(e) {
							return $('#petition-sms-sub:checked').length;
						}
					}
				}
			},
			errorClass:'invalid',
			highlight:function(e,ec) {
				$(e).addClass(ec);
			},
			unhighlight:function(e,ec) {
				$(e).removeClass(ec);
				$(e).siblings('span.error').remove();
			},
			submitHandler:function(f) {
				formHide(f);
				$.ajax({
					type:'POST',
					url:$(f).attr('action'),
					dataType:'json',
					data:{
						action:'petition',
						jssub:'1',
						c:$('input#petition-c',f).val(),
						ptype:$('input#petition-id',f).val(),
						fname:$('input#petition-fname',f).val(),
						lname:$('input#petition-lname',f).val(),
						email:$('input#petition-email',f).val(),
						zip:$('input#petition-zip',f).val(),
						mobile:$('input#petition-mobile',f).val(),
						'em-sub':'1',
						'sms-sub':$('input#petition-sms-sub:checked').length
					},
					success:function(json) {
						var m = '';
						if (json.success) {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Submitted','petition - ' + $('input#petition-id',f).val()]);
						} else {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Error','petition - ' + $('input#petition-id',f).val() + ', json error']);
						}
						formShow(f,m,false,100);
					},
					error:function(x,t,e) {
						var m = '<p>There was a problem signing the petition. Please try again later.</p>';
						formShow(f,m,true);
						_gaq.push(['_trackEvent','Forms','Form Error','petition - ' + $('input#petition-id',f).val()]);
					}
				});
			},
			invalidHandler: function(f,v) {
			},
			errorPlacement: function(err,el) {
				var fn = $(el).siblings('span.title').text();
				$(el).siblings('span.error').remove();
				if(!$(el).siblings('span.error').length) {
					$(el).after('<span class="error">Please provide your <strong>'+fn+'</strong>.</span>');
				}
			}
		};
		$('#petition').validate(emSubVal);
		// Mask Phone & Zip Input
		$('form#petition input#petition-mobile').mask("999 999-9999",{placeholder:" "});
		$('form#petition input#petition-zip').mask("99999",{placeholder:" "});
	}
	
	
	
	// Validate & Handle Contact Form
	if ($('form#contact').length) {
		
		// Define Validation
		var contactVal = {
			debug:true,
			rules: {
				fname:'required',
				lname:'required',
				zip:'required',
				email: {
					required:true,
					email:true
				},
				phone: {
					required: {
						depends: function(e) {
							return $('form#contact input#contact-sms-sub:checked').length;
						}
					}
				},
				message:'required'
			},
			errorClass:'invalid',
			highlight:function(e,ec) {
				$(e).addClass(ec);
			},
			unhighlight:function(e,ec) {
				$(e).removeClass(ec);
				$(e).siblings('span.error').remove();
			},
			submitHandler:function(f) {
				formHide(f);
				$.ajax({
					type:'POST',
					url:$(f).attr('action'),
					dataType:'json',
					data:{
						action:'contact',
						jssub:'1',
						fname:$('input#contact-fname',f).val(),
						lname:$('input#contact-lname',f).val(),
						addr1:$('input#contact-addr1',f).val(),
						addr2:$('input#contact-addr2',f).val(),
						city:$('input#contact-city',f).val(),
						state:$('select#contact-state',f).val(),
						zip:$('input#contact-zip',f).val(),
						email:$('input#contact-email',f).val(),
						'em-sub':$('input#contact-em-sub:checked',f).length,
						mobile:$('input#contact-phone',f).val(),
						'sms-sub':$('input#contact-sms-sub:checked',f).length,
						message:$('textarea#contact-message',f).val()
					},
					success:function(json) {
						var m = '';
						if (json.success) {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Submitted','contact']);
						} else {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Error','contact, json error']);
						}
						formShow(f,m);
					},
					error:function(x,t,e) {
						formShow(f,'<p>Your message could not be sent. Please try again.</p>');
						_gaq.push(['_trackEvent','Forms','Form Error','contact']);
					}
				});
			},
			invalidHandler: function(f,v) {
			},
			errorPlacement: function(err,el) {
				var fn = $(el).siblings('span.title').text();
				$(el).siblings('span.error').remove();
				if(!$(el).siblings('span.error').length) {
					$(el).after('<span class="error">Please provide your <strong>'+fn+'</strong>.</span>');
				}
			}
		};
		$('form#contact').validate(contactVal);
		
		// Mask Phone & Zip Input
		$('form#contact input#contact-phone').mask("999 999-9999",{placeholder:" "});
		$('form#contact input#contact-zip').mask("99999",{placeholder:" "});
		
	}
	
	
	
	// Validate & Handle Contact Form
	if ($('form#volunteer').length) {
		
		// Define Validation
		var volunteerVal = {
			debug:true,
			rules: {
				fname:'required',
				lname:'required',
				zip:'required',
				email: {
					required:true,
					email:true
				},
				phone: {
					required: {
						depends: function(e) {
							return $('form#volunteer input#volunteer-sms-sub:checked').length;
						}
					}
				}
			},
			errorClass:'invalid',
			highlight:function(e,ec) {
				$(e).addClass(ec);
			},
			unhighlight:function(e,ec) {
				$(e).removeClass(ec);
				$(e).siblings('span.error').remove();
			},
			submitHandler:function(f) {
				
				// Grabbing the tasks
				var t = [];
				$('input.task:checked',f).each(function() {
					t.push($(this).val());
				});
				
				formHide(f);
				$.ajax({
					type:'POST',
					url:$(f).attr('action'),
					dataType:'json',
					data:{
						action:'volunteer',
						jssub:'1',
						fname:$('input#volunteer-fname',f).val(),
						lname:$('input#volunteer-lname',f).val(),
						addr1:$('input#volunteer-addr1',f).val(),
						addr2:$('input#volunteer-addr2',f).val(),
						city:$('input#volunteer-city',f).val(),
						state:$('select#volunteer-state',f).val(),
						zip:$('input#volunteer-zip',f).val(),
						email:$('input#volunteer-email',f).val(),
						'em-sub':$('input#volunteer-em-sub:checked',f).length,
						mobile_phone:$('input#volunteer-phone',f).val(),
						'sms-sub':$('input#volunteer-sms-sub:checked',f).length,
						tasks:t
					},
					success:function(json) {
						var m = '';
						if (json.success) {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Submitted','volunteer']);
						} else {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Error','volunteer, json error']);
						}
						formShow(f,m,false,100);
					},
					error:function(x,t,e) {
						formShow(f,'<p>Your message could not be sent. Please try again.</p>');
						_gaq.push(['_trackEvent','Forms','Form Error','volunteer']);
					}
				});
			},
			invalidHandler: function(f,v) {
			},
			errorPlacement: function(err,el) {
				var fn = $(el).siblings('span.title').text();
				$(el).siblings('span.error').remove();
				if(!$(el).siblings('span.error').length) {
					$(el).after('<span class="error">Please provide your <strong>'+fn+'</strong>.</span>');
				}
			}
		};
		$('form#volunteer').validate(volunteerVal);
		
		// Mask Phone & Zip Input
		$('form#volunteer input#volunteer-phone').mask("999 999-9999",{placeholder:" "});
		$('form#volunteer input#volunteer-zip').mask("99999",{placeholder:" "});
		
	}
	
	
	
	// To Make Buttons Submit Forms (IE <= 7 Only)
	// And I'm putting this at the bottom because IE doesn't even know the form exists yet.
	if ($.browser.msie && parseFloat($.browser.version) <= 7) {
		$('form button').click(function() {
			$(this).parents('form').submit();
		});
	}



});






function formHide(f) {
	var fw = $(f).innerWidth();
	var fh = $(f).innerHeight();
	var fid = $(f).attr('id');
	$(f).parent('.fwrap').remove();
	$(f).wrap(function() {
		return '<div class="fwrap '+ fid +'" style="width:'+ fw +'px;height:'+ fh +'px" />';
	});
	$(f).fadeOut(400,function() {
		if ( ! $('div.fwrap.finished').length) $('div.fwrap.'+ fid).css('background','transparent url(/cr/images/spinner.gif) no-repeat center center');
	});
}
function formShow(f,m,r,h) {
	$(f).parent('.fwrap').prepend(m).addClass('finished').css('background','none');
	r = typeof(r) != 'undefined' ? r : false;
	if (r) $(f).show();
	h = typeof(h) != 'undefined' ? h : false;
	if (h && !r) $(f).parent('.fwrap').animate({height:h+'px'},200);
}



var ify = function() {
	return {
		"link": function(t) {
			return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\+#\/.=]+[^:\.,\)\s*$]/ig, function(m) {
				return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
			});
		},
		"at": function(t) {
			return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15}(\/[a-zA-Z0-9-_]+)*)/g, function(m, m1, m2) {
				return m1 + '@<a href="http://twitter.com/' + m2 + '">' + m2 + '</a>';
			});
		},
		"hash": function(t) {
			return t.replace(/(^|[^&\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
				return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>';
			});
		},
		"clean": function(tweet) {
			return this.hash(this.at(this.link(tweet)));
		}
	};
}();
