// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function() {
	$('textarea.short_text').charCounter(180) // to prevent blurbs from growing beyond 256 chars
	$('textarea.long_text').charCounter(800)
	//$('textarea').attr("textarea_trigger", true)
	$('#content iframe') // to make alpaca nation iframes look nice in IE6
		.attr('width','760')
		.css('overflow', 'auto')
		.css('float','left')
	Search.init()
	$('#about_menu').hover(
		function(){$('#about_menu_links').show()},
		function(){$('#about_menu_links').hide()}
	)
	$('#alpaca_sales').each(function(){
		$('a.alpaca_snap').each(function() {
			var id = this.id.replace("a_","ai_")  
			$(this).Tooltip({
			    html: $('#' + id).html() + 'AlpacaSnap',
			    track: true,
			    delay: 0,
			    showURL: false,
			    top:0
			})
		})
	})
	$(".editable").each(function(){
		var tag = $(this).attr("id")
		var cols = 100
		var rows = 40
		if ($('#col1').size() > 0) {
			cols = 25
			rows = 25
		}
		$(this).editInPlace({
		    url: "/snippets/save",
		    tag: tag,
		    bg_over: "#cff",
		    field_type: "textarea",
			textarea_cols: cols,
			textarea_rows: rows,
		    saving_image: "/images/indicator.gif",
			update_value: "content"
		  });
	})
	
})

function check_for_submit() {
	var errors = $('.error').size();
  	if (errors > 0) {
		$('img.progress').hide();
    	$('button[@type=submit], input[@type=submit]').show();
    	window.clearInterval(timer);
  	}
}

var timer = null;
$(document).ready(function(){
  $('button[@type=submit], input[@type=submit]').before('<img src="/images/indicator.gif" title="Submitting form, please wait" class="progress" />')
  $("form").submit(function(){
    $('img.progress',this).css("display","inline");
    $('button[@type=submit], input[@type=submit]').hide();
	timer = window.setInterval("check_for_submit()",200);
	check_for_submit()
  });
	check_for_submit()
});

window.onbeforeunload = check_for_submit;


/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */

	$.fn.charCounter = function(max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<span>",
			classname: "charcounter",
			format: "(%1 characters remaining)",
			pulse: true
		}, settings);
		var p;

		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);
			    };
			};
			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 = (!settings.container.match(/^<.+>$/)) 
				? $(settings.container) 
				: $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			$(this)
				.bind("keydown", function() { count(this, container); })
				.bind("keypress", function() { count(this, container); })
				.bind("keyup", function() { count(this, container); })
				.bind("focus", function() { count(this, container); })
				.bind("mouseover", function() { count(this, container); })
				.bind("mouseout", function() { count(this, container); })
				.bind("paste", 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);

var Popup = {
  create: function(obj) {
      myWindow = open(obj.href, 'Photo', 'location=no,status=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width=500,height=400')
      myWindow.focus()
      return false     
  }
}

var Search = {
	url: null,
	msg: null,
	set_vars: function() {
		$('#member_autocomplete').each(function(){ 
			Search.url = "/search/members_autocomplete" 
			Search.msg = "Enter a member name"
		})
		$('#alpaca_autocomplete').each(function(){ 
			Search.url = "/search/alpacas_autocomplete" 
			Search.msg = "Enter an alpaca name"
		})
		$('#herdsire_autocomplete').each(function(){ 
			Search.url = "/search/herdsires_autocomplete" 
			Search.msg = "Enter a herdsire name"
		})
		$('#product_autocomplete').each(function(){ 
			Search.url = "/search/products_autocomplete" 
			Search.msg = "Enter a product name"
		})
	},
	set_autocomplete: function() {
		$('#search_string').each(function(){
			if ($(this).val().length == 0)
			  $(this).val(Search.msg).toggleClass('inactive')
			$(this).focus(function(){
				if ($(this).val() == Search.msg)
					$(this).val("").toggleClass("inactive")
			})
			$(this).blur(function(){
				if ($(this).val().length == 0)
				  $(this).val(Search.msg).toggleClass('inactive')
			})

			$(this).autocomplete(	
				Search.url,	
				{
					delay:10,
					width:"190px",
					minChars:2,
					matchSubset:1,
					matchContains:1,
					cacheLength:10,
					onItemSelect:Search.select_item,
					onFindValue:Search.find_value,
					formatItem:Search.format_item,
					autoFill:false
				}
			)
		})
	},
	select_item: function(li) {
		Search.find_value(li)
	},
	format_item: function(row) {
		return row[0]
	},
	lookup_ajax: function(){
		var oSuggest = $("#search_string")[0].autocompleter
		oSuggest.findValue()
		return false
	},
	find_value: function(li) {
		if( li == null ) return alert("No match!");

		// if coming from an AJAX call, let's use the CityId as the value
		if( !!li.extra ) var sValue = li.extra[0];
	    if (sValue.length > 0) 
		  window.location = sValue
	    else
		  document.form.submit()
	},
	set_buttons: function() {
		$('#modify_search').click(Search.toggle_form)
		$('a.reset_search').click(Search.reset_form)
	},
	toggle_form: function() {
		$('#browse').slideToggle()
	},
	reset_form: function() {
		$('input[@type=checkbox]').attr('checked',false)
		$('input[@type=radio]').attr('checked',false)
		$('#sort_recent').attr('checked',false)
		$('#sort_all').attr('checked', true)
		$('select').each(function(){ $(this).val($('option:first',this).attr('value')) })
		$('#browse a.active').removeClass("active")
		$('#search_form #search_string').val(Search.msg).toggleClass("inactive")
	},
	submit_form: function() {
		if ($('#search_string').val() == Search.msg)
			$('#search_string').val('')
	},
	init: function() {
		$('#search').each(function(){
			Search.set_vars()
			Search.set_autocomplete()
			Search.set_buttons()
			$('#search_form').submit(Search.submit_form)
		})
	}
}

