$(function() {
	
	$('ul.navigation li a').hover(
		function() {
			$(this).addClass('hov');
		},
		function() {
			$(this).removeClass('hov');
		});

	if ($('ul.service-labels').length) {
		$('ul.service-labels').cycle({
			timeout:3000,
			speed:500,
			fx:'fade',
			cleartype:($.browser.msie && $.browser.version == '6.0')?true:false,
			after:function() {
				$('ul.services li').removeClass('sel');
				$('ul.services li.'+this.id).addClass('sel');
			}
		});
	}
	
	if ($('div.features ul').length) {
		if ($('div.features ul li').length > 1) {
			$('div.features ul').cycle({
				timeout:6000,
				speed:500,
				fx:'fade',
				cleartype:!$.support.opacity,
				pager:'.ctrl',
				pagerAnchorBuilder:function() {
					return '<a href="#"><img src="/cr/images/spc.gif" width="24" height="14" alt="" /></a>';
				},
				pagerClick: function() {
					$('div.features ul').cycle('pause').addClass('paused');
					$('div.features div.ctrl div.toggle').addClass('paused');
				},
				after: function() {
					if ($('div.ooyala',this).length) {
						$('div.ooyala div.embed',this).hide();
						$('div.ooyala img.vid-mask',this).show();
					}
				}
			});
			$('div.features ul li').click(function() {
				$('div.features ul').cycle('pause').addClass('paused');
				$('div.features div.ctrl div.toggle').addClass('paused');
			})
			$('div.features div.ctrl div.toggle').click(function() {
				if ($('div.features ul.paused').length) {
					$(this).removeClass('paused');
					$('div.features ul').cycle('resume').removeClass('paused');
				} else {
					$(this).addClass('paused');
					$('div.features ul').cycle('pause').addClass('paused');
				}
			});
			$('div.features ul li div.ooyala img.vid-mask').click(function() {
				var p = $(this).parents('div.ooyala');
				$(this).hide();
				$('div.embed',p).show()
			});
		} else {
			$('div.features ul li').show();
			$('div.features div.ctrl').hide();
		}
	}
	
	if ($('td.sidebar div.feature').length) {
		$('td.sidebar div.feature').each(function() {
			if ($('p.link',this).length) {
				var re = /^http:\/\/www.johnthune.com\/|^#|^\/|^$/;
				var lnk = $('p.link a',this).attr('href');
				$(this).click(function() {
					if (!re.exec(lnk)) {
						window.open(lnk);
					} else {
						location.href=lnk;
					}
				}).css({cursor:'pointer'});
				$('p.link',this).remove();
			}
		});
	}
	

	$('ul.updates li').each(function() {
		var url = $('a',this).attr('href');
		var title = $('a',this).text();
		if (/^(http:\/\/www.twitter.com|http:\/\/twitter.com)/.test(url)) {
			$(this).addClass('twitter');
		} else if (/^(http:\/\/www.youtube.com|http:\/\/youtube.com)/.test(url)) {
			$(this).addClass('youtube');
		} else if (/^(http:\/\/picasaweb.google.com)/.test(url)) {
			$(this).addClass('picasa');
		} else if (/^(http:\/\/www.flickr.com|http:\/\/flickr.com)/.test(url)) {
			$(this).addClass('flickr');
		} else if (/^(http:\/\/www.facebook.com|http:\/\/facebook.com)/.test(url)) {
			$(this).addClass('facebook');
		} else if (/\(via Digg\)$/.test(title)) {
			$(this).addClass('digg');
		} else if (/^http:\/\/friendfeed.com/.test(url)) {
			$(this).remove();
		} else {
			$(this).addClass('digg');
		}
	});
	
	$('form.right').validate({
		rules: {
			email: {
				required:true,
				email:true
			},
			zip: {
				required:true,
				digits:true,
				maxlength:5,
				minlength:5
			}
		},
		messages: {
			email: {
				required: "Please provide your email address.",
				email: "Please provide a valid email address."
			},
			zip: {
				required: "Please provide your zip code.",
				digits: "Please provide a valid zip code.",
				maxlength: "Please provide a valid zip code.",
				minlength: "Please provide a valid zip code."
			}
		},
		errorClass: 'invalid',
		errorLabelContainer: 'div#form-right-errors div.holder',
		invalidHandler: function(f,v) {
			var err = [];
			$(v.errorList).each(function(ik,iv) {
				err.push(iv.message);
			});
			if (err.length>0) {
				if (err.length==2) err = ['Please provide a valid email address and zip code.'];
				var errStr = err.join('</li><li>');
				$('div#form-right-errors').html('<ul><li>'+errStr+'</li></ul><div class="holder"></div>').fadeIn(400);
			}
		},
		highlight: function(e,errorClass) {
			$(e).addClass(errorClass);
			$(e).parents('label').addClass(errorClass);
		},
		unhighlight: function(e,errorClass) {
			$(e).removeClass(errorClass);
			$(e).parents('label').removeClass(errorClass);
		},
		submitHandler: function(form) {
			$('div#form-right-errors').html('').fadeOut(800);
			formShade($(form));
			$.ajax({
				type:'POST',
				url:'/cr/php/process_ac.php',
				dataType:'json',
				data:{
					'email':$('input#email',form).val(),
					'zip':$('input#zip',form).val(),
					'a_sub':'1',
					'form_id':$('input.form-id',form).val()},
				success:function(json) {
					if (json.Success) {
						formReveal($(form),'<p><strong>Thank you!</strong> You will now receive John Thune updates.</p>');
						$('div#body-foot div.bottom-bar').append('<iframe src="https://pixel.fetchback.com/serve/fb/pdc?cat=&name=success&sid=1436" scrolling="no" width="1" height="1" marginheight="0" marginwidth="0" frameborder="0"></iframe>');
					} else {
						formReveal($(form),'<p><strong>An error has occurred.</strong> Please try again later.</p>');
					}
				},
				error:function() {
					formReveal($(form),'<p><strong>An error has occurred.</strong> Please try again later.</p>');
				}
			});
		}
	});
	
	$('ul.action-center form#ac-act input#phone_cell').mask("(999) 999-9999",{placeholder:" "});
	$('ul.action-center form#ac-act').submit(function() {
		$('.invalid',this).removeClass('invalid');
		var err = [];
		var req = {
			fname:{
				preload:'first name',
				message:'Please provide your first name.'
				},
			lname:{
				preload:'last name',
				message:'Please provide your last name.'
				},
			phone_cell:{
				preload:'cell phone',
				message:'Please provide your cell phone.'
				},
			email:{
				preload:'email',
				message:'Please provide your email address.'
				},
			zip:{
				preload:'zip',
				message:'Please provide your zip code.'
				}
		};
		$.each(req,function(k,v) {
			var el = $('ul.action-center form#ac-act input#'+k);
			var iv = $(el).val();
			if (k == 'phone_cell') {
				if ($('ul.action-center form#ac-act input#ac-sms-updates:checked').length) {
					if (iv == v.preload || iv == '') {
						// console.log(iv);
						$(el).addClass('invalid');
						$(el).parents('label').addClass('invalid');
						err.push(v.message);
					}
				}
			} else if (k == 'email') {
				var regex = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
				if (iv == v.preload || iv == '' || !regex.test(iv)) {
					$(el).addClass('invalid');
					$(el).parents('label').addClass('invalid');
					err.push(v.message);
				}
			} else if (k == 'zip') {
				var regexa = new RegExp(/^\d{5}$/);
				var regexb = new RegExp(/^\d{10}$/);
				if (iv == v.preload || iv == '' || (!regexa.test(iv) && !regexb.test(iv))) {
					$(el).addClass('invalid');
					$(el).parents('label').addClass('invalid');
					err.push(v.message);
				}
			} else {
				var regex = new RegExp(/^[a-z \-\']{1,}$/i);
				if (iv == v.preload || iv == '' || !regex.test(iv)) {
					$(el).addClass('invalid');
					$(el).parents('label').addClass('invalid');
					err.push(v.message);
				}
			}
		});
		if (err.length) {
			var errors = err.join('</li><li>');
			$('div#ac-form-errors').html('<ul><li>'+errors+'</li></ul>').fadeIn(400);
		} else {
			$('div#ac-form-errors').html('').hide();
			formShade($('ul.action-center form'));
			var chx = [];
			$.each($('input:checkbox',this),function() {
				if ($(this).is(':checked')) chx.push($(this).val());
			});
			$.ajax({
				type:'POST',
				url:'/cr/php/process_ac.php',
				dataType:'json',
				data:{
					'fname':$('input#fname',this).val(),
					'lname':$('input#lname',this).val(),
					'phone_cell':$('input#phone_cell',this).val(),
					'email':$('input#email',this).val(),
					'zip':$('input#zip',this).val(),
					'chx':chx.join(','),
					'a_sub':'1',
					'form_id':$('input.form-id',this).val()
					},
				success:function(json) {
					if (json.Success) {
						formReveal($('ul.action-center form'),'<p><strong>Thank you!</strong><br />You will now receive John Thune updates.</p>');
						$('div#body-foot div.bottom-bar').append('<iframe src="https://pixel.fetchback.com/serve/fb/pdc?cat=&name=success&sid=1436" scrolling="no" width="1" height="1" marginheight="0" marginwidth="0" frameborder="0"></iframe>');
					} else {
						formReveal($('ul.action-center form'),'<p><strong>An error has occurred.</strong><br />Please try again later.</p>');
					}
				},
				error:function() {
					formReveal($('ul.action-center form'),'<p><strong>An error has occurred.</strong><br />Please try again later.</p>');
				}
			});
		}
		return false;
	});
	
	
	
	$('ul.action-center form#ac-cont input#cphone').mask("(999) 999-9999",{placeholder:" "});
	$('ul.action-center form#ac-cont input#czip').mask("99999",{placeholder:" "});
	
	
	
	$('div#ac-form-errors').click(function() {
		$(this).fadeOut(200);
	});
	
	$('ul.action-center li.tab').click(function() {
		if (!$(this).is('.extended')) {
			$('ul.action-center li.extended div.form-container').slideUp(200);
			$('div.form-container',this).slideDown(200);
			$('ul.action-center li').removeClass('extended');
			$(this).addClass('extended');
			if ($(this).is('.top')) {
				$('img.head',this).css({backgroundImage:'url(/cr/images/ac_head_top_on.png)'}).animate({paddingBottom:'9px'},200);
				$('ul.action-center li.bot img.head').css({backgroundImage:'url(/cr/images/ac_head_bot_off.png)'}).animate({paddingBottom:'0'},200);
			}
			if ($(this).is('.bot')) {
				$('img.head',this).css({backgroundImage:'url(/cr/images/ac_head_bot_on.png)'}).animate({paddingBottom:'10px'},200);
				$('ul.action-center li.top img.head').css({backgroundImage:'url(/cr/images/ac_head_top_off.png)'}).animate({paddingBottom:'0'},200);
			}
		}
	}).hover (
		function() {
			if ($(this).is('.top') && !$(this).is('.extended')) $('img.head',this).css({backgroundImage:'url(/cr/images/ac_head_top_hov.png)'});
			if ($(this).is('.bot') && !$(this).is('.extended')) $('img.head',this).css({backgroundImage:'url(/cr/images/ac_head_bot_hov.png)'});
		},
		function() {
			if ($(this).is('.top') && !$(this).is('.extended')) $('img.head',this).css({backgroundImage:'url(/cr/images/ac_head_top_off.png)'});
			if ($(this).is('.bot') && !$(this).is('.extended')) $('img.head',this).css({backgroundImage:'url(/cr/images/ac_head_bot_off.png)'});
	});
	$('form ul li.amount input[name=amt]').click(function() {
		if($(this).val()=='other') {
			$('form ul li.amount ul').slideUp(100,function() {
				$('form div.custom').slideDown(100,function(){$('form ul li.amount div.custom input#amt-custom').focus()});
			});
		} else {
			$('form ul li.amount div.custom input#amt-custom').val('');
		}
	});
	
	$('form :text').each(function() {
		var pre = $(this).siblings('span.title').text();
		if ($(this).val()=='') $(this).val(pre).addClass('pre');
		$(this).focus(function() {
			if ($(this).val()==pre) $(this).val('').removeClass('pre');
		});
		$(this).blur(function() {
			if ($(this).val()=='') $(this).val(pre).addClass('pre');
		});
	});
	
	$('td.take-action div.post,td.news div.post,td.post-list div.post').hover(
		function() {
			$(this).addClass('active');
		},
		function() {
			$(this).removeClass('active');
		});
	$('td.take-action div.post,td.news div.post,td.post-list div.post').each(function() {
		if ($('p.read-more',this).length) {
			var lnk = ($('p.read-more a',this).attr('href'));
			$(this).click(function() {
				location.href=lnk;
			})
		}
	});
	
	$('a').each(function() {
		var re = /^http:\/\/www.johnthune.com\/|^#|^\/|^$/;
		var ln = $(this).attr('href');
		if (!re.exec(ln)) {
			$(this).attr('target','_blank');
		}
	})
	
	
	
	
	
	if ($('td.post-list ul.tabs').length) {
		$('ul.tabs li').hover(
			function() {$(this).addClass('hov')},
			function() {$(this).removeClass('hov')}
			);
		$('ul.tabs li a').click(function() {
			var c = this.className;
			$('ul.tabs li').removeClass('sel');
			$(this).parents('li').addClass('sel');
			$('td.post-list div.tab').fadeOut(200);
			$('td.post-list div.'+c).fadeIn(600);
			return false;
			});
	}
	

	if ($('ul.styled-selects').length) {
		$('ul.styled-selects li img').hover(
			function() { if ($(this).not('.sel')) $(this).addClass('hov'); },
			function() { if ($(this).not('.sel')) $(this).removeClass('hov'); });
		$('ul.styled-selects li img').click(function() {
			$(this).removeClass('hov');
			(this.className != 'sel')? $(this).addClass('sel'): $(this).removeClass('sel');
			});
	}



	if($('dl#qna-videos').length) {
		$('dl#qna-videos dt').hover(function(){$(this).addClass('hov')},function(){$(this).removeClass('hov')});
		$('dl#qna-videos dt').click(function() {
			if (!$(this).is('.exp')) {
				var $dd = $(this).next('dd');
				$('dl#qna-videos dt').removeClass('exp');
				$('dl#qna-videos dd:visible').slideUp(400).removeClass('exp');
				$dd.slideDown(400).addClass('exp');
				$(this).addClass('exp');
			}
		});
	}
	
	
	
	if ($('body div#page.sub table.content td.media-gallery').length) {
		$('body div#page.sub table.content td.media-gallery div.container div.post ul.youtube li.older a.pop')
			.click(function() {
				$.fancybox({
					'overlayOpacity':	0.9,
					'overlayColor':		'#222',
					'padding':			0,
					'autoScale':		false,
					'transitionIn':		'none',
					'transitionOut':	'none',
					'title':			this.title,
					'width':			420,
					'height':			340,
					'href':				this.href.replace(new RegExp("watch\\?v=", "i"), 'v/')+'&autoplay=1',
					'type':				'swf'
					});
				return false;
				});
		}
	
	
	
	
	
	
	$.fn.pause = function(duration) {
		$(this).animate({ dummy: 1 }, duration);
		return this;
	};
	
	function formShade(el) {
		$(el).prepend('<div class="shade"><img src="/cr/images/icon_spinner.gif" alt="" /></div>');
	}
	function formReveal(el,str) {
		$(el)
			.fadeOut(800,function() {
				$(this).html(str);
			})
			.fadeIn(800);
	}
	
	
});