var Tertiary, Simple_Slideshow;

(function($) {
	Tertiary = {
		timeout: 500,
		close_timer: null,
		menu: null,
		init: function() {
			if ($('#navigation li.tertiary').length)
			{
				$('#navigation li.tertiary').hover(Tertiary.open, Tertiary.start_close);
				$(document).click(Tertiary.close);				
			}
		},
		open: function() {
			Tertiary.cancel_timer();
			Tertiary.close();
			var $this = $(this);
			Tertiary.menu = $this.find('div.tertiary_nav').show();
		},
		close: function() {
			if (Tertiary.menu)
			{
				Tertiary.menu.hide();
			}
		},
		start_close: function() {
			Tertiary.close_timer = window.setTimeout(Tertiary.close, Tertiary.timeout);
		},
		cancel_timer: function() {
			if (Tertiary.close_timer)
			{
				window.clearTimeout(Tertiary.close_timer);
				Tertiary.close_timer = null;
			}
		}

	};
	
	Simple_Slideshow = {
		selector: null,
		init: function(selector) {
			Simple_Slideshow.selector= selector;
			if ($(selector + ' img').length > 1)
			{
				$(selector + ' img:first').addClass('active');
		    	setInterval(Simple_Slideshow.turn, 7000);
			}
		},
		
		turn: function() {
			var selector = Simple_Slideshow.selector;
		    var $active = $(selector + ' img.active');
		    if ($active.length == 0)
			{
				$active = $(selector + ' img:last');
			}

		    var $next =  $active.next().length ? $active.next() : $(selector + ' img:first');

	    	$active.addClass('last-active');

		    $next.css({opacity: 0.0})
				.addClass('active')
		        .animate({opacity: 1.0}, 1000, function() {
		            $active.removeClass('active last-active');
		        });
		}
	};

})(jQuery);

(function($) {

	$.twitter_pager = function(settings) {
		var config = {
			// Next page link, all next page requests will use the href attribute, until this element can no longer be found.  It will then be hidden.
			next_page_link_selector: '#next_page',
			
			// Container in which the items will be appended to.
			item_container_selector: '#posts',
			
			// Items / Records
			item_selector: '#posts div.post'
		};

		if (settings)
		{
			$.extend(config, settings);
		}

		var loading = function(on) {
			if ($(config.next_page_link_selector + '_loading').length == 0)
				return false;

			$(config.next_page_link_selector).css('display', on ? 'none' : '');
			$(config.next_page_link_selector + '_loading').css('display', on ? '' : 'none');
		};

		$(config.next_page_link_selector).click(function(e) {
			e.preventDefault();
			var $next_page_link = $(this);

			loading(true);
			$.get($next_page_link.attr('href'), function(data) {
				var $next_page = $(data);
				var $items = $next_page.find(config.item_selector);
				var next_page_href = $next_page.find(config.next_page_link_selector).attr('href');
				if ($items.length)
				{
					$items.appendTo(config.item_container_selector);

					if (next_page_href)
					{
						$next_page_link.attr('href', next_page_href);				
					}
				}

				loading(false);
				if ($items.length == 0 || !next_page_href)
				{
					$next_page_link.hide();
				}
			});
		});

	};

})(jQuery);

jQuery.extend(jQuery.easing, {
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	}
});

jQuery.fn.charCounter = function (max, settings) {
	max = max || 100;
	settings = $.extend({
		container: "<span></span>",
		classname: "charcounter",
		format: "(%1 characters remaining)",
		pulse: true,
		delay: 0
	}, settings);
	var p, timeout;
	
	function count(el, container) {
		el = $(el);
		if (el.val().length > max) {
		    el.val(el.val().substring(0, max));
		    if (settings.pulse && !p) {
		    	pulse(container, true);
		    };
		};
		if (settings.delay > 0) {
			if (timeout) {
				window.clearTimeout(timeout);
			}
			timeout = window.setTimeout(function () {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}, settings.delay);
		} else {
			container.html(settings.format.replace(/%1/, (max - el.val().length)));
		}
	};
	
	function pulse(el, again) {
		if (p) {
			window.clearTimeout(p);
			p = null;
		};
		el.animate({ opacity: 0.1 }, 100, function () {
			$(this).animate({ opacity: 1.0 }, 100);
		});
		if (again) {
			p = window.setTimeout(function () { pulse(el) }, 200);
		};
	};
	
	return this.each(function () {
		var container;
		if (!settings.container.match(/^<.+>$/)) {
			// use existing element to hold counter message
			container = $(settings.container);
		} else {
			// append element to hold counter message (clean up old element first)
			$(this).next("." + settings.classname).remove();
			container = $(settings.container)
							.insertAfter(this)
							.addClass(settings.classname);
		}
		$(this)
			.unbind(".charCounter")
			.bind("keydown.charCounter", function () { count(this, container); })
			.bind("keypress.charCounter", function () { count(this, container); })
			.bind("keyup.charCounter", function () { count(this, container); })
			.bind("focus.charCounter", function () { count(this, container); })
			.bind("mouseover.charCounter", function () { count(this, container); })
			.bind("mouseout.charCounter", function () { count(this, container); })
			.bind("paste.charCounter", function () { 
				var me = this;
				setTimeout(function () { count(me, container); }, 10);
			});
		if (this.addEventListener) {
			this.addEventListener('input', function () { count(this, container); }, false);
		};
		count(this, container);
	});
};


jQuery.fn.input_hint = function() {
	return this.each(function() {
		var $this = $(this);

		if ($this.attr('value').length == 0)
			$this.attr('value', $this.attr('title'));

		$this.focus(function() {
			if ($this.attr('value') == $this.attr('title'))
				$this.attr('value', '');
		}).blur(function() {
			if ($this.attr('value') == '')
				$this.attr('value', $this.attr('title'));
		}).parents('form').submit(function() {
			if ($this.attr('value') == $this.attr('title'))
				$this.attr('value', '');
		});
	});
};

jQuery.fn.input_hint2 = function() {
	return this.each(function() {
		var $this = $(this);

		if ($this.attr('value').length == 0)
			$this.attr('value', $this.attr('title'));

		$this.focus(function() {
			if ($this.attr('value') == $this.attr('title'))
				$this.attr('value', '');
		}).blur(function() {
			if ($this.attr('value') == '')
				$this.attr('value', $this.attr('title'));
		});
	});
};

var Site = {

	// this vars should be set in <head> server-side
	config: {
		base_url: '',
		site_url: ''
	},
	
	// this method is called on every page
	init: function() {

		// On Dom Ready
		jQuery(function($) {

			$.each($('#navigation a.subnavigation_title'), function() {
				var $this = $(this);
				$this.click(function(e) {
					e.preventDefault();
					
					// Make sure all subnav's are closed.
					$.each($('#navigation a.subnavigation_title'), function(k, v) {
						var $this = $(this);
						$this.next().hide('slow', 'easeOutQuart');
						$this.removeClass('on');
					});
					

					// Open subnav only if it's closed
					if ($this.next().css('height') == 'auto')
					{
						$('#navigation a').removeClass('on');
						$this.addClass('on');
						$this.next().animate({
							height: 'toggle'
						}, 'slow','easeOutQuart');
					}

				});

			});
			
			$("#blog_comment").charCounter(1000);

			if ($('#landing_page_form').length)
			{
				Site.contact_info.validate();
			}
			$('input.hint, textarea.hint').input_hint();
			
			$('#infusionsoft_newsletter_signup #newsletter_signup_form').submit(function() {
				var $this = $(this);
				return Site.is_valid_email($this.find('input[type=text]').val());
			});

			Tertiary.init();
			// $('.lightbox').open_colorbox();
			
			Site.flash();
		});
		
		// On Window Load
		jQuery(window).load(function($) {

		});
		
		// Load Immediately
		(function($) {
		
		})(jQuery);

		if ($.browser.msie && $.browser.version <= 6 )
		{
			jQuery(window).load(function($) {
				DD_belatedPNG.fix('.pngfix');				
			});
		}
	},
	
	flash: function() {
		$('.flash').each(function() {
			$this = $(this);
			var flashvars = {
			};
			
			$this.flash({
				swf: $this.attr('data-file'),
				width: $this.attr('data-width') ? $this.attr('data-width') : $this.width(),
				height: $this.attr('data-height') ? $this.attr('data-height') : $this.height(),
				flashvars: flashvars,
				allowfullscreen: 'true',
				allowscriptaccess: 'always',
				wmode : 'transparent'
			});
			
			if (!$.flash.available)
			{
				$this.find('div').css('display', '');
			}
		});	
	},
	is_valid_email: function(email)
	{
		return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
	},
	
	landing_pages: function() {
		if ($('#landingpage_download').length)
		{
			setTimeout(function() {
				window.location = $('#landingpage_download').attr('href');
			}, 1000);
		}
		
		if ($('#infusionsoft_contactus_form').length)
		{
			Site.contact_info.infusionsoft();
		}
	},
	
	blog: function() {
		$('#blogcomment_submit_button').mouseover(function() {
			$('#name2').val('blogcomment_form_submitted');
		});

		$('#blogcomment_submit_button').click(function() {
			var $this = $(this);
			$this.parents('form').submit();
		});
	},

	contact_info: {
		// This function shall be called inline around a domready event.
		init: function() {
			$('form.submit_once').submit(function(e) {
				var $this = $(this);
				if ($this.data('form_submitted'))
				{
					return false;
				}
				$this.data('form_submitted', true);
			});

			if ($('#infusionsoft_contactus_form').length)
			{
				Site.contact_info.infusionsoft();
			}
			else if ($('#salesforce_contactus_form').length)
			{
				Site.contact_info.salesforce();
			}
			else
			{
				$('#contact_submit_button').mouseover(function() {
					$('#name2').val('contact_form_submitted');
				});

				$('#contact_submit_button').click(function() {
					var $this = $(this);
					$this.parents('form').submit();
				});
			}

			Site.contact_info.validate();
		},
		
		salesforce: function() {
			$('#salesforce_contactus_form input[type=submit]').addClass('submit_btn');
		},

		infusionsoft: function() {
			var $trs = $('#infusionsoft_contactus_form tbody:first > tr');

			// Removing headers
			$trs.find('td[colspan=99]').remove();
			
			// Removing submit button
			$trs.eq($trs.length - 1).remove();
			
			$trs = $('#infusionsoft_contactus_form tbody:first > tr');

			var $form_label, $td1, $td2, $input, valid_form_types = ['text', 'checkbox', 'textarea'];

			$trs.each(function(k, v) {
				var $this = $(this);
				var $tds = $this.children('td');
				if ($tds.length == 2)
				{
					$td1 = $tds.eq(0);
					$td2 = $tds.eq(1);
					
					$td1.addClass('form_label');
					$td2.addClass('form_element');
					$td2.find('input[type=text]').addClass('text');

					if ($td2.find('input[type=text]').length == 0 && $td2.find('textarea').length == 0)
					{
						$td2.addClass('nontext');
					}

					if ($td1.text().indexOf('*') >= 0)
					{
						$td1.text('* ' + $td1.text().replace('*', ''));
						$td2.find('input[type=text]').addClass('validate').attr('rel', 'required');
					}
					

				}
			});

			$('#infusionsoft_contactus_form form').append('<div class="submit_button_wrapper"><input type="image" src="/files/home/images/submit_button.png" value="Submit" /></div>');
			$('#infusionsoft_contactus_form form').submit(function(e) {
				var form_success = true;
				var $this = $(this);
				$this.find('input[type=text]').each(function() {
					var $input = $(this);
					if ($input.attr('rel') == 'required' && ($input.val() == '' || $input.val() == $input.attr('title')))
					{
						form_success = false;
						return false;
					}
				});
				return form_success;
			});

			$('#infusionsoft_contactus_form').show();
			
		},

		legalcoops: function() {
			$('#location').change(function() {
				var $this = $(this);
				$('#contact_us_legalcoops .contact_us_legalcoop').css('display', 'none');

				var legalcoop_id = $this.val();
				if (legalcoop_id)
				{
					$('#contact_us_legalcoop_' + legalcoop_id).fadeIn(500);
				}
			});
		},
		
		validate: function() {
			(function($) {
				$('.tooltip').bt();
			
				$(".validate").blur(function(){
					var el = $(this);
					if (!el.attr('rel'))
						return false;
					$.ajax({
						type: 'POST',
						url: '/validate/',
						data: { action: 'validate', rule: el.attr('rel'), value: el.val() == el.attr('title') ? '' : el.attr('value') },
						async: false,
						success: function(str) {
							el.next('span').remove();

							var result = str.split("|");
							var valid = result[0];
							var tip = result[1];

							if(valid) {
								el.after('<span style="margin:0 0 0 7px;"><img src="/files/icons/accept.png" border=0 ></span>') ;
								el.css( 'background-color', '#FFFFFF' );
							} else if(str.length > 0) {
								el.after('<span class="tooltip" title="' + tip + '" style="margin:0 0 0 7px;"><img src="/files/icons/exclamation.png" border="0"></span>'); 
								el.css( 'background-color', '#FFFF99' );
								$('.tooltip').bt();
							}
						}
					});
				});
			
			})(jQuery);

		}
	},
	forms: {
		init: function() {
			$form_submit_once = $('form.submit_once');
			if ($form_submit_once.length == 0)
			{
				return false;
			}
			
			$form_submit_once.find('.hint').input_hint();
			
			$form_submit_once.submit(function(e) {
				var $this = $(this);
				if ($this.data('form_submitted'))
				{
					return false;
				}
				$this.data('form_submitted', true);
			});

			$form_submit_button = $('.form_submit_button');
			$form_submit_button.mouseover(function() {
				$form_submit_once.find('input.action').val('form_user_submitted');
			});

			$form_submit_button.click(function() {
				var $this = $(this);
				$this.parents('form').submit();
			});
			
			Site.forms.validate();
		},
		validate: function() {
			$('.tooltip').bt();
			$(".validate").blur(function() {
				var el = $(this);
				if (!el.attr('rel'))
					return false;
				$.ajax({
					type: 'POST',
					url: '/validate/',
					data: { action: 'validate', rule: el.attr('rel'), value: el.val() == el.attr('title') ? '' : el.attr('value') },
					async: false,
					success: function(str) {
						el.next('span').remove();

						var result = str.split("|");
						var valid = result[0];
						var tip = result[1];

						if(valid)
						{
							el.after('<span class="tooltip" ><img src="/files/icons/accept.png" border=0 ></span>') ;
							//el.css( 'background-color', '#FFFFFF' );
						}
						else if(str.length > 0) 
						{
							el.after('<span class="tooltip" title="' + tip + '"><img src="/files/icons/exclamation.png" border="0"></span>'); 
							//el.css( 'background-color', '#FFFF99' );
							$('.tooltip').bt();
						}
					}
				});
			});
		}
	}
};

Site.init();



