/*
google.load('search','1',{'callback':function(){
	$(function(){
		if (google.loader.ClientLocation) {
		}
	});
}});
*/

// Load $.cookie (if not present)
if ($.cookie === undefined)
{
	$.cookie=function(key,value,options){if(arguments.length>1&&String(value)!=="[object Object]"){options=$.extend({},options);if(value===null||value===undefined){options.expires=-1;}
if(typeof options.expires==='number'){var days=options.expires,t=options.expires=new Date();t.setDate(t.getDate()+days);}
value=String(value);return(document.cookie=[encodeURIComponent(key),'=',options.raw?value:encodeURIComponent(value),options.expires?'; expires='+options.expires.toUTCString():'',options.path?'; path='+options.path:'',options.domain?'; domain='+options.domain:'',options.secure?'; secure':''].join(''));}
options=value||{};var result,decode=options.raw?function(s){return s;}:decodeURIComponent;return(result=new RegExp('(?:^|; )'+encodeURIComponent(key)+'=([^;]*)').exec(document.cookie))?decode(result[1]):null;};
}

$.fn.serializeObject = function () {
	"use strict";

	var result = {};
	var extend = function (i, element) {
		var node = result[element.name];

// If node with same name exists already, need to convert it to an array as it
// is a multi-value field (i.e., checkboxes)

		if ('undefined' !== typeof node && node !== null) {
			if ($.isArray(node)) {
				node.push(element.value);
			} else {
				result[element.name] = [node, element.value];
			}
		} else {
			result[element.name] = element.value;
		}
	};

// For each serialzable element, convert element names to camelCasing and
// extend each of them to a JSON object

	$.each(this.serializeArray(), extend);
	return result;
};

// Tag External Links
jQuery.extend(jQuery.expr[':'], { external: function(o) { return !o.href.match(/^mailto\:/) && (o.hostname !== location.hostname); } });

function trackAd(e) {
    // Prevent Default Action
    e.preventDefault();

    // Set some vars, default delay to 200ms
    var delay = ( typeof e.data == 'undefined' || typeof e.data.delay == 'undefined' )? 200: e.data.delay,
        a = $(e.currentTarget)[0],
        eventLabel = $(e.currentTarget).attr('title');

    // Check for _gaq; if present, track.
    if ( typeof _gaq !== 'undefined' ) _gaq.push(['_trackEvent','ad','click',eventLabel + '(' + a.href + ')',1]);

    // Check Targets
    if ( typeof a.target !== 'undefined' && ( '_blank' == a.target || '_new' == a.target ) ) {
        // Open _blank and _new links in new window
        setTimeout(function(){ window.open(a.href); },delay);
    } else {
        // Open targetless links in same window
        setTimeout(function(){ document.location = a.href; },delay);
    }
}

function trackResource(e) {
    // Prevent Default Action
    e.preventDefault();

    // Set some vars, default delay to 200ms
    var delay = ( typeof e.data == 'undefined' || typeof e.data.delay == 'undefined' )? 200: e.data.delay,
        a = $(e.currentTarget)[0],
        eventLabel = $('.title',e.currentTarget).text();

    // Check for _gaq; if present, track.
    if ( typeof _gaq !== 'undefined' ) _gaq.push(['_trackEvent','resource','click',eventLabel + '(' + a.href + ')',1]);

    // Check Targets
    if ( typeof a.target !== 'undefined' && ( '_blank' == a.target || '_new' == a.target ) ) {
        // Open _blank and _new links in new window
        setTimeout(function(){ window.open(a.href); },delay);
    } else {
        // Open targetless links in same window
        setTimeout(function(){ document.location = a.href; },delay);
    }
}

$(function(){

	// Open External Links & PDFs in New Tab
	$('a').each(function(){
		if ( $(this).is(':external') ) {
			$(this).attr('target','_blank').addClass('external');
		}
	});
	$("a[href$='pdf']").attr('target','_blank');

	/* Article Hovers */
	if ($('.listed-article:not(.full-article)').length) {
		$('.listed-article').hover(
			function(){ $(this).addClass('hovered-article'); },
			function(){ $(this).removeClass('hovered-article'); }
		);
	}

	// Get Markets

	$.get('/dtn-markets.html',function(d){
		$('#widget-bar #markets-tab .panel-body').html(d);
		$('#widget-bar #markets-tab .panel-body a').each(function(){
			$(this).after('<span class="anchor" style="font-weight:bold">'+$(this).text()+'</span>');
			$(this).remove();
		});
	});


	/* Widget Bar Tabs */
	$('#widget-bar .tab-item').hover(
		function(){ $(this).addClass('par-hov'); },
		function(){ $(this).removeClass('par-hov'); }
	);
	$('#widget-bar .tab-item .tab-link').click(function(e){
		e.preventDefault();
		var tabID = $(this).closest('.tab-item').attr('id');
		if ( ! $(this).parent().is('.hover'))
		{
			$('#widget-bar .tab-item:not(#'+tabID+') .panel').stop().fadeOut(100);
			$('#widget-bar .tab-item:not(#'+tabID+')').removeClass('hover');
			$('#widget-bar #'+tabID+' .panel').stop().fadeIn(200,function(){});
			$('#widget-bar #'+tabID).addClass('hover');
		}
		else
		{
			$('#widget-bar .panel').stop().fadeOut(100);
			$('#widget-bar .tab-item').removeClass('hover');
		}
		if ( typeof _gaq !== 'undefined' ) _gaq.push(['_trackEvent','footer-widget','click',tabID,1]);
		return false;
	});
        $('#tools-tab .panel ul li').on('click.footerTracker','a',function(e){
                var linkTitle = $(this).text();
                if ( typeof _gaq !== 'undefined' ) _gaq.push(['_trackEvent','footer-widget','click','Tools Link: ' + linkTitle,1]);
        });

	$('#widget-bar .tab-close').click(function(){
		$('#widget-bar .panel').stop().fadeOut(400);
		$('#widget-bar .tab-item').removeClass('hover');
		return false;
	});
	$('#widget-bar .panel-body a:not(#locale-changer)').unbind('click');
	$('#widget-bar .panel-body a:not(#locale-changer)').click(function(){
		window.open($(this).attr('href'));
		return false;
	});

	/* Social Networking Tabs & Panes */
	if ($('#sw-socnets').length)
	{
		$('#sw-socnets .ctrl a').click(function(){
			var c = this.className;
			$('#sw-socnets .active-tab-title').text(c + ' live feed');
			$('#sw-socnets .ctrl li').removeClass('active');
			$('#sw-socnets .panes .pane').hide();
			$('#sw-socnets .ctrl li.'+c).addClass('active');
			$('#sw-socnets .panes .'+c).show();
			return false;
		});
		$('#sw-socnets .ctrl li:eq(0) a').click();
	}

	/* Primary Nav */
	$('#primary-nav > ul > li').hover(
		function(){ $(this).addClass('hov');$('> ul',this).show(); },
		function(){ $(this).removeClass('hov');$('> ul',this).hide(); }
		);
	$('#primary-nav ul ul li').hover(
		function(){ $(this).addClass('hov'); },
		function(){ $(this).removeClass('hov'); }
		);
	$('#primary-nav > ul > li > ul').append('<li><a href="/4h/south-dakota-4h/state-fair">State Fair</a></li>');
	if ($('#section-nav').length)
	{
		$('#section-nav ul li a').hover(
			function(){ $(this).addClass('hov'); },
			function(){ $(this).removeClass('hov'); }
		);
	}

	/* Category Nav */
	if ($('#category-nav').length)
	{
		$('#category-nav .tab').hover(
			function(){ $(this).addClass('hov'); },
			function(){ $(this).removeClass('hov'); }
		);
		$('#category-nav .tab').click(function(){
			$('#category-nav .tab').removeClass('active-tab');
			$(this).addClass('active-tab');
			$('div.tab-pane').hide();
			$('div.tab-pane.'+$(this).attr('id')+'-tab').show();
		});
	}
	
	/* Section Nav */
	$('#section-nav:has(header h2 a[href="/4h/"]) > ul').append('<li><a href="/4h/south-dakota-4h/state-fair">State Fair</a></li>');

	/* Featured Article Carousel */
	if ($('#featured-articles .article-container article').length > 2)
	{
		$('#featured-articles .featured-articles-head').append('<a class="feat-nav feat-prev" href="#">Prev</a><a class="feat-nav feat-next" href="#">Next</a>');
		if ($('#featured-articles .rot-articles').length) {
			$('#featured-articles .article-container').jcarousel({
				scroll:1,
				buttonNextHTML:null,
				buttonPrevHTML:null,
				initCallback:function(c){
					$('#featured-articles .featured-articles-head .feat-prev').bind('click',function() {
						c.prev();
						return false;
					});
					$('#featured-articles .featured-articles-head .feat-next').bind('click',function() {
						c.next();
						return false;
					});
				}
			});
		}
	}

	if ($('#product-page .content-head .category-title').length && $('#br-topbar .breadcrumb').length) {
		$('#br-topbar .breadcrumb li:eq(0)').after('<li>'+$('#product-page .content-head .category-title').html()+'</li>');
	}
	if ($('#product-page').length && $('#category-nav').length) {
		var pc = $('#product-page .content-head .category-title a').attr('class');
		$('#category-nav li').each(function(){
			if ($(' > a[href="http://igrow.org/catalog/'+pc+'"]',this).length) {
				$(this).addClass('active');
			}
		});
		$('#category-nav li').each(function(){
			if ($(this).has('li.active').length) {
				$(this).addClass('active-parent');
			}
		});
	}
	if ($('#catalog-page').length && $('#br-topbar li:eq(1)').length) {
		var sc = $('#br-topbar li:eq(1)').attr('class');
		$('#category-nav li').each(function(){
			if ($(' > a[href="http://igrow.org/catalog/'+sc+'"]',this).length) {
				$(this).addClass('active');
			}
		});
		$('#category-nav li').each(function(){
			if ($(this).has('li.active').length) {
				$(this).addClass('active-parent');
			}
		});

	}

	/* All Feature Slideshows */
	if ($('#feature .slides .slide').length > 1)
	{
		if ($('#feature .slides .feat-prod').length) {
			$('#feature .slides .feat-prod').each(function(){
				var img = $('a:not(.link)',this).attr('href');
				var title = $('a:not(.link)',this).text('');
				$('a.link',this).html('<img src="'+img+'" alt="'+title+'">');
				$('a:not(.link)',this).hide();
			});
		}
		$('#feature .slides').cycle({'timeout':7000});
	}

	/* Resource List */
	if ($('#sw-resource-library .resource-group').length > 1)
	{
		$('#sw-resource-library .resource-group .resource-group-title').click(function(){
			var p = $(this).parent();
			if (p.is('.collapsed')) {
				p.removeClass('collapsed');
			} else {
				p.addClass('collapsed');
			}
		});
	}

	/* Resource List Table */
	if ($('#resources-table').length)
	{
		var catStr = $('#resources-table').attr('class');
		$('#resources-table').dataTable( {
			"bJQueryUI": true,
			"bProcessing": true,
			"sAjaxSource": '/a/res/' + catStr + '/'
		});
	}

	// Freeform Forms
	$('.ff-form form').each(function(){
		var $f        = $(this),
			formWidth = $f.outerWidth();

		if ( formWidth >= 0 && formWidth <= 320) {
			$f.addClass('lte320');
		} else if ( formWidth > 320 && formWidth <= 720 ) {
			$f.addClass('lte720');
		} else {
			$f.addClass('gt720');
		}

		$f.addClass('visible');
	});
});


function crNOAAGetWeather(oz)
{
	var d = new Date().getDay();
	var wk = ['S','M','T','W','T','F','S'];
	var wkl = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
	var wkls = ['sun','mon','tue','wed','thu','fri','sat'];
	var wkd = [];
	var wkdl = [];
	var wkdls = [];

	for (i = 0;i < 7;i++)
	{
		u = i + d;
		if (u > 6) { u = u - 7; }
		wkd.push(wk[u]);
		wkdl.push(wkl[u]);
		wkdls.push(wkls[u]);
	}
	var crLocalityZip = jQuery.cookie('cr_locality_zip');
	if (oz !== undefined) { crLocalityZip = oz; }
	$.getJSON('/a/c/zip/' + crLocalityZip + '/',function(d){
var wx = '\
<h2 class="locality"><span class="locale">' + d.location + '</span> <span class="change-locale"><a href="http://google.com/" id="locale-changer">Change</a></span></h2>\
		<div class="current-conditions" style="background-image:url(' + d.icon_url_base + d.icon_url_name + ')">\
			<p class="ctemp">' + d.temp_f + 'F</p>\
			<p class="cwx">' + d.weather + '</p>\
			<p class="cwind">Wind: ' + d.wind_string + '</p>\
		</div>\
';
		$('#widget-bar #weather-tab .panel-body').html(wx);
		$('#widget-bar #weather-tab #weather-time').text(d.observation_time.replace('Last Updated on ',''));
		if ($('#sw-weather').length) { $('#sw-weather h3.locality').text(d.location); }
		$.getJSON('/a/f/zip/' + crLocalityZip + '/',function(d){
			if (d.temps.maximum !== undefined)
			{
var wx = '\
		<table class="forecast">\
			<thead>\
				<tr>\
					<th></th>\
					<th colspan="5">5-day Forecast</th>\
				</tr>\
				<tr>\
					<th></th><th>' + wkd[1] + '</th><th>' + wkd[2] + '</th><th>' + wkd[3] + '</th><th>' + wkd[4] + '</th><th>' + wkd[5] + '</th>\
				</tr>\
			</thead>\
			<tbody>\
				<tr class="highs">\
					<th>High</th>\
					<td>' + d.temps.maximum[0] + '</td><td>' + d.temps.maximum[1] + '</td><td>' + d.temps.maximum[2] + '</td><td>' + d.temps.maximum[3] + '</td><td>' + d.temps.maximum[4] + '</td>\
				</tr>\
				<tr class="lows">\
					<th>Low</th>\
					<td>' + d.temps.minimum[0] + '</td><td>' + d.temps.minimum[1] + '</td><td>' + d.temps.minimum[2] + '</td><td>' + d.temps.minimum[3] + '</td><td>' + d.temps.minimum[4] + '</td>\
				</tr>\
				<tr class="precip">\
					<th>Precip.</th>\
					<td>' + d.precip[0] + '%</td><td>' + d.precip[2] + '%</td><td>' + d.precip[4] + '%</td><td>' + d.precip[6] + '%</td><td>' + d.precip[8] + '%</td>\
				</tr>\
			</tbody>\
			<tfoot>\
				<tr>\
					<td colspan="6"><a href="' + d.info_url + '" class="more-info">More Forecast Information</a></td>\
				</tr>\
			</tfoot>\
		</table>';
var fore = '\
			<dt class="' + wkdls[1] + '">' + wkdl[1] + '</dt>\
			<dd style="background-image:url(' + d.icons[1] + ')">\
				<span class="conditions">' + d.conditions[1] + ' </span>\
				<span class="temp-hi">High: ' + d.temps.maximum[1] + '&#176;F </span>\
				<span class="temp-lo">Low: ' + d.temps.minimum[1] + '&#176;F </span>\
			</dd>\
			<dt class="' + wkdls[2] + '">' + wkdl[2] + '</dt>\
			<dd style="background-image:url(' + d.icons[2] + ')">\
				<span class="conditions">' + d.conditions[2] + ' </span>\
				<span class="temp-hi">High: ' + d.temps.maximum[2] + '&#176;F </span>\
				<span class="temp-lo">Low: ' + d.temps.minimum[2] + '&#176;F </span>\
			</dd>\
			<dt class="' + wkdls[3] + '">' + wkdl[3] + '</dt>\
			<dd style="background-image:url(' + d.icons[3] + ')">\
				<span class="conditions">' + d.conditions[3] + ' </span>\
				<span class="temp-hi">High: ' + d.temps.maximum[3] + '&#176;F </span>\
				<span class="temp-lo">Low: ' + d.temps.minimum[3] + '&#176;F </span>\
			</dd>';
			}
			else
			{
				var wx = '<p class="error">Forecast currently unavailable.</p>';
				var fore = '<p class="error">Forecast currently unavailable.</p>';
			}

			$('#widget-bar #weather-tab .panel-body .current-conditions').after(wx);
			if ($('#sw-weather #sw-weather-data').length) { $('#sw-weather #sw-weather-data').html(fore); }

			$('#widget-bar .panel-body a:not(#locale-changer)').unbind('click');
			$('#widget-bar .panel-body a:not(#locale-changer)').click(function(){
				window.open($(this).attr('href'));
				return false;
			});

			$('#locale-changer').click(function(){
				$('#widget-bar #weather-tab .panel-body h2.locality').html('<label>Your Zip Code: <input type="text" name="wx-zip" id="wx-zip"></label> <button id="get-new-locale">Submit</button>');
				$('#get-new-locale').click(function(){
					var newZip = $('#wx-zip').val();
					if (newZip !== '')
					{
						$.cookie('cr_locality_zip',newZip,0.25);
						$('#widget-bar #weather-tab .panel-body').html('');
						crNOAAGetWeather(newZip);
					}
					return false;
				});
				return false;
			});
			if ($('#sw-weather #sw-weather-data').length)
			{
				$('#sw-locale-changer').click(function(){
					$('#sw-weather h3.config').html('<label class="customize">Zip: <input type="text" name="wx-zip" id="sw-wx-zip"></label> <button id="sw-get-new-locale">Submit</button>');
					$('#sw-get-new-locale').click(function(){
						var newZip = $('#sw-wx-zip').val();
						if (newZip !== '')
						{
							$.cookie('cr_locality_zip',newZip,0.25);
							$('#sw-weather #sw-weather-data').html('');
							$('#sw-weather h3.config').html('<a href="" id="sw-locale-changer">Customize &#187;</a>');
							crNOAAGetWeather(newZip);
						}
						return false;
					});
					return false;
				});
			}
		});
	});



	// Contact Form Submission
	if ($('form#reg-form').length)
	{
		$('form#reg-form').append('<input type="hidden" name="jssub" value="1">');
		var cFormVal = {
			debug:true,
			rules: {
				name:'required',
				email: {
					required:true,
					email:true
				}
			},
			errorClass:'invalid',
			highlight:function(e,ec) {
				$(e).addClass(ec);
			},
			unhighlight:function(e,ec) {
				$(e).removeClass(ec);
			},
			submitHandler:function(f) {
				formHide(f);
				$.ajax({
					type:'POST',
					url:$(f).attr('action'),
					dataType:'json',
					data:$(f).serialize(),
					success:function(json) {
						var m = '';
						if (json.success) {
							m = '<p class="message">'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Submitted','contact']);
							if ( typeof GoSquared !== 'undefined' ) {
								GoSquared.DefaultTracker.TrackEvent('Event Registration',$(f).serializeObject());
								GoSquared.UserName = $('input[name="name"]',f).val();
							}
						} else {
							m = '<p class="message">'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Error','contact, json error']);
						}
						$('.ie7 #interior-content').css('margin-right','-10px');
						formShow(f,m,false,100);
					},
					error:function(x,t,e) {
						var m = '<p class="message">There was a problem submitting the form.</p>';
						formShow(f,m,true);
						$('.ie7 #interior-content').css('margin-right','-10px');
						_gaq.push(['_trackEvent','Forms','Form Error','']);
					}
				});
			},
			invalidHandler: function(f,v) {
			},
			errorPlacement: function(err,el) {
			}
		};
		$('form#reg-form').validate(cFormVal);
	}



	/* FREEFORM SUBMISSIONS */
	$('.ff-form form').each(function(){
		var $f     = $(this),
			url    = document.URL,
			height = $f.outerHeight();
		$f.validate({
			errorClass:'invalid',
			highlight:function(e,ec) {
				$(e).addClass(ec);
			},
			unhighlight:function(e,ec) {
				$(e).removeClass(ec);
			},
			submitHandler:function(f) {
				// formHide(f);
				$f.css({display:'none'});
				$.ajax({
					type:'POST',
					url:$(f).attr('action'),
					dataType:'json',
					data:$(f).serialize(),
					success:function(json) {
						var m = '';
						if (json.success) {
							m = '<p class="message success">The form was successfully submitted.</p>';
							_gaq.push(['_trackEvent','Forms','Form Submitted',url]);

							// formShow(f,m,false,100);
							$('.ff-form .message').remove();
							$('.ff-form').prepend(m);
						} else {
							for ( var field in json.errors ) {
								$('[name="' + field + '"]',$f).addClass('invalid');
							}
							m = '<p class="message error">An error occurred when the form was submitted. Please check for required fields below and try again.</p>';
							_gaq.push(['_trackEvent','Forms','Form Error',url + ', json error']);
							// formShow(f,m,true);
							$('.ff-form .message').remove();
							$('.ff-form').prepend(m);
							$f.css({display:'block'});
						}
						$('.ie7 #interior-content').css('margin-right','-10px');
					},
					error:function(x,t,e) {
						var m = '<p class="message">There was a problem submitting the form.</p>';
						$('.ff-form .message').remove();
						$('.ff-form').prepend(m);
						//formShow(f,m,true);
						$f.css({display:'block'});
						$('.ie7 #interior-content').css('margin-right','-10px');
						_gaq.push(['_trackEvent','Forms','Form Error',url]);
					}
				});
			},
			invalidHandler: function(f,v) {
			},
			errorPlacement: function(err,el) {
			}
		});
	});



	/* EVENT TRACKING */

	// Ad Lists
	$('#ad-wrap,.ad-list').on('click','a',trackAd);

	// Omnibox
	$('.omnibox .results').on('click','li:not(.video) a',trackResource);



	/* Colorbox */
	$('.cb-pop').colorbox({
		innerWidth:'680px',
		innerHeight:'520px'
	});
	$('.pcal-close').live('click',function(){
		$.colorbox.close();
		return false;
	});
	$('.omnibox .results').on('click','.video a',function(e){
		e.preventDefault();

		var videoTitle = $(this).attr('title'),
			videoURL   = $(this).attr('href'),
			videoID    = videoURL.split('=').pop(),
			videoLink  = 'https://youtube.com/embed/' + videoID + '?rel=0&wmode=transparent';

		// Pop the box
		$.colorbox({iframe: true, width: '680px', height: '520px', href: videoLink});

		// Track the Event
		if ( typeof _gaq !== 'undefined' ) _gaq.push(['_trackEvent','resource','click','Video - ' + videoTitle + ' (' + videoURL + ')',1]);
	});
	$('#contours .video').on('click','a',function(e){
		e.preventDefault();

		var $link    = $(this);
		var vidTitle = $link.attr('title');
		var vidURL   = $link.attr('href');

		// Pop the box
		$.colorbox({iframe: true, innerWidth: '680px', innerHeight: '540px', href: vidURL});

		// Track the Event
		if ( typeof _gaq !== 'undefined' ) _gaq.push(['_trackEvent','contours','click','Video - ' + vidTitle + ' (' + vidURL + ')',1]);
	});
	$('.contours-autoplay').each(function(){
		$.colorbox({iframe: true, innerWidth: '680px', innerHeight: '540px', href: $(this).attr('href')});
	});



	/* Contours Info Hover */
	$('#contours .video').hoverIntent({
		over:function(){ $(this).addClass('hover'); },
		out:function(){ $(this).removeClass('hover'); }
	});



	/* Form Processing: em-sub */
	if ($('#em-sub').length) {

		// SlideToggle Form
		$('#em-sub-title').click(function(){
			$('#em-sub').slideToggle();
		});

		// Validate Email Subscription Form
		var emSubVal = {
			debug:true,
			rules: {
				fname:'required',
				lname:'required',
				email: {
					required:true,
					email:true
				}
			},
			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(),
						'em-sub':'1'
					},
					success:function(json) {
						var m = '';
						if (json.success) {
							m = '<p>'+json.message+'</p>';
							_gaq.push(['_trackEvent','Forms','Form Submitted','em-sub']);
							if ( typeof GoSquared !== 'undefined' ) {
								GoSquared.DefaultTracker.TrackEvent('Email Subscription',{firstName:$('input#em-sub-fname',f).val(),lastName:$('input#em-sub-lname',f).val(),email:$('input#em-sub-email',f).val()});
								GoSquared.UserName = $('input#em-sub-fname',f).val() + ' ' + $('input#em-sub-lname',f).val();
							}
						} 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);
	}

	if ($('#store-faq').length) {
		$('#store-faq-list li .q').click(function(){
			$(this).siblings('.a').slideToggle(200);
		});
	}



	// To Make Buttons Submit Forms (IE <= 7 Only)
	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');

		if ( $(f).is('.visible') ) fh = $(f).outerHeight() + 200;

		$(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(https://igrow.org/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').stop().animate({height:h+'px'},200); }
	}
}
