// Special classes
$(document).ready(function() {
	
	$('.auto_clear').focus(function(){
		if (!$(this).attr('init_text')) $(this).attr('init_text', $(this).val());
		if ($(this).attr('init_text') == $(this).val()) $(this).val('');
	});
	$('.auto_clear').blur(function(){	
		if (trim($(this).val())=='') $(this).val($(this).attr('init_text'));
	});
	
	if($('#search').length) {
		$('#search').submit(function() {
			
			zip = $(this).find('.q').val();
			var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zip);
			
			if(isValidZip) {
				document.location = '/events/search:' + zip;
			} else {
				$(this).find('.error').show();
				$(this).find('.error').fadeOut(3000);
			}
			
			return false;
		});
	}
	
	if($.datepicker) {
		$(".datepicker").datepicker({
			showAnim: 'slideDown',
			onSelect: function(dateText) { if (this.onchange) this.onchange(); },
			showOn: "button",
			buttonImage: "/static/img/datepicker/calendar.gif",
			buttonImageOnly: true,
			firstDay: 0,
			yearRange: '-85:+5'
		});	
	}
	
	$('#add-a-tip').bind('submit', function(e){
		e.preventDefault();
		e.stopPropagation();
		$.post('/polls/vote', $('#add-a-tip').serialize(), function(data){
			if(data == 'OK') {
				window.location.reload();
			}
		});
	});
	
	/* Auto- 'ajaxification' of modules */
	hook_up_ajax();
	
	/* JS rollovers for images */
	$('.js_rollover').hover(
		function() {
			$(this).attr('out_src', $(this).attr('src'));
			$(this).attr('src', $(this).attr('over_src')); 
		},
		function() {
			$(this).attr('src', $(this).attr('out_src'));
		}
	);
	
});

function hook_up_ajax(subsection) {
	if (!subsection) subsection = document;
	
	// Auto- 'ajaxification' of modules
	$(subsection).find('.ajaxify').click(function() {
		if ($(this).attr('confirm')) {
			if (confirm($(this).attr('confirm')) == false) return false;			
		}
		
		var t = $(this).attr('ajax_target');
		var f = $(this).attr('success');

		$('#'+t).load($(this).attr('href'), {			
			}, function(r) { 
				if (f && r) eval(f);
				hook_up_ajax($('#'+t));
			} 
		);
		return false;
	});
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

