(function($) {

	var cbs = {};
	
	$(document).ready(function() {
		cbs.heroshots();
		//cbs.columns();
		cbs.login();
		cbs.searchResults();
		//cbs.formDefaults(); // NEEDS WORK
		//cbs.typeAheadFind();
		cbs.navHover();
		cbs.areaSort();
		cbs.shareIt();
		cbs.disclaimerDialog();
	});

	$(".columns").columnize({columns: 3, buildOnce: true, lastNeverTallest: true});
	$("#bd #main .feeds ul li:first-child").addClass("first")


	cbs.formDefaults = function() { // NEEDS WORK -- breaking search button
		$('#bd :input[value], #search-form :input[value]').filter(function(){ return $(this).val() != "" }).each(function() { var originalText = $(this).val(); $(this).focus(function() { $(this).val($(this).val() == originalText ? '' : $(this).val()); }).blur(function() { $(this).val($(this).val() == '' ? originalText : $(this).val()); }); });
	}

	cbs.disclaimerDialog = function() {
		// disclaimer
		var email_disclaim = $("<div id='disclaim'><div class='bor'><p>Sending this email does not establish a client-lawyer relationship, and the mere sending of this email does not, without more, indicate that Chambliss, Bahner & Stophel, P.C. or any lawyer here is willing to discuss the possibility of forming a client-lawyer relationship.	 By providing an email link to individual lawyers, Chambliss, Bahner & Stophel, P.C. does not intend to initiate a discussion with you about forming a client-lawyer relationship on any matter.  As such, please be advised that, unless Chambliss, Bahner & Stophel, P.C. either agrees to represent you or agrees later to discuss the possibility of representing you, information that you send to this firm will not be kept confidential or privileged.	 By clicking the \"accept\" button below, you confirm that you have read and understand this notice and that you agree to its terms.</p></div></div>");
		var contact_disclaim = $("<div id='disclaim'><div class='bor'><p>If you are inquiring about possible legal representation, please note that we cannot discuss representing you until we determine that we do not have a conflict of interest.  Sending this communication does not establish a client-lawyer relationship, and the mere sending of this communication does not, without more, indicate that Chambliss, Bahner & Stophel, P.C. or any lawyer here is willing to discuss the possibility of forming a client-lawyer relationship.	 By providing this communication tool, Chambliss, Bahner & Stophel, P.C. does not intend to initiate a discussion with you about forming a client-lawyer relationship on any matter.  As such, please be advised that, unless Chambliss, Bahner & Stophel either agrees to represent you or agrees later to discuss the possibility of representing you, information that you send to this firm through this link will not be kept confidential or privileged, and you consent to Chambliss, Bahner & Stophel's use of that information for any purpose consistent with applicable law.	 Please read our full statement of our Terms and Conditions relating to use of this website.</p><p>We welcome your comments and questions and will direct your inquiries to the appropriate person at Chambliss, Bahner & Stophel, who will contact you via the email or the phone number you have provided. Thank you!</p></div></div>");
		$('form.contact').submit(function(s) {
			s.preventDefault();
			$(contact_disclaim).dialog({ 
				modal: true,
				width: 450,
				title: 'Important Notice',
				buttons: { 
					"cancel": function() { 
						$(this).dialog("close");
					},
					"accept": function() {
						document.contactForm.submit();
					}
				}
			});
		});
		$('a[href^="mailto:"]').each(function() {
			$(this).click(function(c) {
				c.preventDefault();
				var targetUrl = $(this).attr("href");
				$(email_disclaim).dialog({ 
					modal: true,
					width: 450,
					title: 'Important Notice',
					buttons: { 
						"cancel": function() { 
							$(this).dialog("close");
						},
						"accept": function() {
							window.location.href = targetUrl;
							$(this).dialog("close");
						}}
				});
			});
		});
	}

	cbs.heroshots = function() {
		$('.heroshot').not('.disabled').each(function() {
			var heroshot = $(this);
			var images   = heroshot.find('img');
			
			images.hide().eq(0).show();

			var fade = parseInt(heroshot.find('input[name=fade]').remove().val(),10);
			var dur  = parseInt(heroshot.find('input[name=duration]').remove().val(),10);

			var captionContainer = $('<div class="caption"></div>');
			var caption          = $('<span class="text"></span>');
			
			caption.text(images.eq(0).attr('alt'));
			if(images.eq(0).parent('a').size()) {
				caption.append($('<a href="' + images.eq(0).parent('a').attr('href') +  '" class="read-more">Read More</a>'));
			}
			caption.appendTo(captionContainer);

			var counter = $('<span class="counter"></span>');
			var currentCount = $('<span class="count"></span>');
			currentCount.text('1').appendTo(counter);
			counter.append($('<span class="of">of</span>'));
			counter.append($('<span class="total">' + images.size() + '</span>'));
			counter.appendTo(captionContainer);

			captionContainer.appendTo(heroshot).append($('<div class="clear"></div>'));

			images.each(function(index) {
				$(this).attr({'count': index});
			});

			if(images.size() > 1) {
				setInterval(function() {
					var current = images.filter(':visible');
					var next = images.eq(parseInt(current.attr('count'),10) + 1).size() ? images.eq(parseInt(current.attr('count'),10) + 1) : images.eq(0);
					current.fadeOut(fade * 1000);
					next.fadeIn(fade * 1000);
					var caption = captionContainer.find('.text');
					var newCaption = caption.clone(true);
					newCaption.text(next.attr('alt'));
					if(next.parent('a').size()) {
						newCaption.append($('<a href="' + next.parent('a').attr('href') +  '" class="read-more">Read More</a>'));
					}
					caption.fadeOut(fade * 1000,function() { caption.remove(); });
					newCaption.hide().prependTo(captionContainer).fadeIn(fade * 1000);
					currentCount.text(parseInt(next.attr('count'),10) + 1);
				}, (dur + fade) * 1000);
			}

		});
	}

	cbs.columns = function() {
		var lists = $('.list');
		if(!lists.size()) { return; }

		lists.each(function() {
			var list = $(this);
			if(list.css('column-count') != '' || list.css('-moz-column-count') != '' || list.css('-webkit-column-count') != '') { return; }

			var colHeight = Math.ceil(list.height() / 3);

			var col1 = $('<div class="col"></div>');
			var col2 = col1.clone();
			var col3 = col1.clone();
			col1.addClass('first');
			list.append(col1).append(col2).append(col3);

			var cols = new Array(col1,col2,col3);
			var currentColumn = 0;

			var groups = new Array();
			list.find('h2').each(function() {
				groups[groups.length] = {'header': $(this), 'items': $(this).next('ul')};
			});

			$.each(groups,function() {
				this.header.appendTo(cols[currentColumn]);
				if(cols[currentColumn].height() > colHeight && currentColumn < cols.length) {
					currentColumn++;
					this.header.appendTo(cols[currentColumn]);
				}
				this.header.after(this.items);
			});

			if(col2.height() > col1.height()) {
				col2.find('h2:first-child').appendTo(col1);
				col2.find('ul:first-child').appendTo(col1);
			}

			if(col3.height() > col3.height()) {
				col3.find('h2:first-child').appendTo(col2);
				col3.find('ul:first-child').appendTo(col2);
			}
		});
	}

	cbs.login = function() {
		var form = $('form#login-form');
		form.css({'width':'auto'});
		var defaultWidth = form.width();
		form.css({'width': form.find('a[rel=toggle]').width()});
		form.find('span').hide()
		form.find('a[rel=toggle]').click(function() {
			if(form.is(':animated')) { return; }
			if(form.width() < defaultWidth) {
				form.find('span').show()
				form.animate({'width': defaultWidth},'fast');
			} else {
				form.find('span').hide()
				form.animate({'width': form.find('a[rel=toggle]').width()},'fast');
			}
		});
		form.find('input').focus(function() {
			if(form.width() < defaultWidth) {
				form.animate({'width': defaultWidth},'fast', function() { $(this).focus(); });
			}
		});
	}

	cbs.searchResults = function() {
		cbs.searchResults.toggleCategories();
		cbs.searchResults.eventsShowHide();
	}

	cbs.searchResults.toggleCategories = function() {
		if(!$('body#search').size()) { return; }
		
		var headers = $('.results h2');
		
		headers.each(function() {
			var header = $(this);
			header.addClass('open');
			header.click(function() {
				header.toggleClass('open').toggleClass('closed').next().slideToggle();
			});
		});
	}
	
	cbs.searchResults.eventsShowHide = function() {
		var links = $('a[rel=more]');
		if(!links.size()) { return; }
		links.each(function() {
			var link = $(this);
			var teaser = link.parents('tr').find('div.teaser');
			var content = link.parents('tr').find('div.content');
			if(!teaser.size() || !content.size()) { return; }
			
			link.click(function(c) {
				c.preventDefault();
				if(link.text() == 'Learn More') {
					link.text('Show Less');
					teaser.slideUp('fast');
					content.slideDown('fast');
				} else {
					link.text('Learn More');
					content.slideUp('fast');
					teaser.slideDown('fast');
				}
			});
		});
	}
	
	cbs.navHover = function() {
		$('ul.navigation li').each(function() {
			thisLink = $(this);
			thisLink.hover(function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');

			});			   
		});
	};
	
	cbs.areaSort = function() {
		if(!$('body.practice-areas ul.sort-by').size()) { return; }
		
		var sortBy = $('ul.sort-by');
		var catList = $('ul.sort-by li#category-sort a');
		var alphaList = $('ul.sort-by li#alpha-sort a');
		var catDiv = $('div#cat_list');
		var alphaDiv = $('div#alpha_list');
		alphaDiv.hide();
		
		catList.click(function(c) {
			c.preventDefault();
			$(this).addClass('selected');
			alphaList.removeClass('selected');
			catDiv.show()
			alphaDiv.hide()
			$(this).blur()
		});
		alphaList.click(function(c) {
			c.preventDefault();
			$(this).addClass('selected');
			catList.removeClass('selected');
			alphaDiv.show().css("text-indent", "0")
			catDiv.hide()
			$(this).blur()
		});
	}
	
	cbs.shareIt = function(){
	  var links = $('a.stbutton')
	  var links_s = $('a.st-side')
	  
	  cbs.workintitle = document.title || "CB&S Law Firm"

	cbs.bitlyParse = function(data){
		var result
		for(var i in data.results){
			result = data.results[i]; break
		}
		return result.shortUrl
	}
	cbs.bitly = function(url,funk){
		BitlyClient.shorten(url,funk)
	}
	cbs.twitterBoom = function(data){
		var url = cbs.bitlyParse(data)
		window.open('http://twitter.com/home?status=' + encodeURIComponent(cbs.workintitle) + '%20' + encodeURIComponent(url), 'tweet')
	}
	cbs.twitterGo = function(u){
		cbs.bitly(u,'cbs.twitterBoom')
	}
	
	// Upwards ones, like at bottom of news items
	  if(typeof links != undefined){
	  links.each(function(){
		var link = $(this)
		var butan = new ShareDis(link,null,null,'top center', [null,["Twitter",function(url,title,event){cbs.twitterGo(window.location)}],["Email","mailto:?subject=__TITLE__&body=__URL__"]])
	  })
	}
	//Sidewards ones, like on the Events
	if(typeof links_s != undefined){
	  links_s.each(function(){
		var link = $(this)
		var butan = new ShareDis(link,null,null,'bottom left', [null,["Twitter",function(url,title,event){cbs.twitterGo(window.location)}],["Email","mailto:?subject=__TITLE__&body=__URL__"]])
	  })
	}
	}
	
	cbs.typeAheadFind = function() {
		var input = $('#search-form input[name=term]');
		if(!input.size()) { return; }
		var listContainer = $('<div class="search-results" style="display: none;" />');
		listContainer.css({'right': (parseInt(input.css('margin-right'),10) + input.next('button').outerWidth()) + 'px'}).appendTo(input.parent());
		var list = $('<dl />');
		list.appendTo(listContainer);
		input.attr({'autocomplete':'off'}).blur(function() {
			listContainer.hide();
		});
		input.parents('form').submit(function(s) {
			return !list.find('a.selected').size();
		});
		input.keyup(function(e) {
			e.preventDefault();
			var key = e.which;
			var term = input.val();
			if(term.length > 0) { listContainer.css({'display':'block'}); }
			var selected = list.find('a.selected').size() ? list.find('a.selected').removeClass('selected') : false;

			if(key == 38 || key == 40) { // Up & Down arrows
				var links = list.find('a');
				links.each(function(index) {
					$(this).attr({'count':index});
				});
				if(key == 38) { // Up Arrow
					if(selected) {
						list.find('a[count=' + (parseInt(selected.attr('count'),10) - 1) + ']').addClass('selected');
					} else {
						list.find('a').eq(list.find('a').size() - 1).addClass('selected');
					}
				} else {
					if(selected) { // Down Arrow
						list.find('a[count=' + (parseInt(selected.attr('count'),10) + 1) + ']').addClass('selected');
					} else {
						links.eq(0).addClass('selected')
					}
				}
			} else if(key == 13) { // Enter key
				if ( selected ) {
					input.val( selected.text() );
					selected.addClass('selected');
					window.location = selected.attr('href');
				}
				input.parents('form').submit();
			} else {
				$.getJSON('/search.json', {'term': term}, function(data) {
					try {
						list.empty();
						var categories = data.categories;
						$.each(categories,function() {
							var dt = $('<dt>' + this.title + '</dt>');
							var dd = $('<dd />');
							list.append(dt).append(dd);
							var matches = $('<ul />');
							matches.appendTo(dd);
							$.each(this.results, function() {
								var item = $('<li />');
								item.appendTo(matches);
								var link = $('<a />');
								link.attr({'title': this.title, 'href': this.get_absolute_url}).text(this.title).appendTo(item);
							})
						})
						list.find('a[href=' + selected.attr('href') + ']').eq(0).addClass('selected');
					} catch(err) {
						// Do nothing
					}
				});
			}
			return false;
		});
	}
	
})(jQuery);
