var Ajax;
if (Ajax && (Ajax != null)) {
	Ajax.Responders.register({
		onCreate: function() {
			if ($('spinner') && Ajax.activeRequestCount > 0)
				Effect.Appear('spinner', {duration:0.5,queue:'end'});
		},
		onComplete: function() {
			if ($('spinner') && Ajax.activeRequestCount == 0)
				Effect.Fade('spinner', {duration:0.5,queue:'end'});
		}
	});
}

function confirmAndRedirect(prompt, url) {
	var confirmed = confirm(prompt);

	if (confirmed) {
		window.location = url;
	}
}

function markCheckboxes(query, mark) {
	query.find("input[type=checkbox]").each(function() {
		$(this).attr("checked", mark);
	})
}

function deselectAll(theForm) {
	for (i = 0; i < theForm.elements.length; i++) {
		if (theForm.elements[i].type == "checkbox") {
			theForm.elements[i].checked = false;
		}
	}
}

function selectAll(theForm) {
	for (i = 0; i < theForm.elements.length; i++) {
		if (theForm.elements[i].type == "checkbox") {
			theForm.elements[i].checked = true;
		}
	}
}

function selectUninvited(theForm) {
	deselectAll(theForm);
	for (i = 0; i < theForm.elements.length; i++) {
		if (theForm.elements[i].type == "checkbox" && theForm.elements[i].className == "uninvited") {
			theForm.elements[i].checked = true;
		}
	}
}

function selectRsvpByResponse(theForm, response) {
	deselectAll(theForm);
	for (i = 0; i < theForm.elements.length; i++) {
		if (theForm.elements[i].type == "checkbox" && theForm.elements[i].className == ('rsvp_' + response)) {
			theForm.elements[i].checked = true;
		}
	}
}

function logToConsole(data) {
	$("#console").text(data);
}

function logHTMLToConsole(data) {
	$("#console").html(data);
}

function setSuccessMessage(message) {
	if ($("#successMessage").size() > 0) {
		$("#successMessage").html(message);
	}
	else {
		$("#messages").append("<div id='successMessage'>" + message + "</div>");
	}
}

function setFailMessage(message) {
	if ($("#failMessage").size() > 0) {
		$("#failMessage").html(message);
	}
	else {
		$("#messages").append("<div id='failMessage'>" + message + "</div>");
	}
}

function localizeDates() {
	$("span.utcDate").each(function() {
		var outputFormat = $(this).attr("title");

		if (outputFormat) {
			var utcDate = Date.parseDate($(this).text(), Date.patterns.ISO8601Long);

			var offsetMillis = utcDate.getTimezoneOffset() * -60 * 1000;

			var localDate = new Date();
			localDate.setTime(utcDate.getTime() + offsetMillis);
			$(this).text(localDate.dateFormat(outputFormat));
			$(this).removeAttr("title");
		}
	});
}

function addDatePicker(changeMonthYear) {
	$(document).ready(function() {
		if (changeMonthYear) {
			$("input[type='text'].datePicker").datepicker({yearRange: '1900:' + (new Date().getYear() + 1901),
				changeMonth: true,
				changeYear: true
			});
		}
		else {
			$("input[type='text'].datePicker").datepicker({yearRange: '1900:' + (new Date().getYear() + 1901)});
		}
	});
}

/*
 * Image preview script
 * powered by jQuery (http://www.jquery.com)
 *
 * written by Alen Grakalic (http://cssglobe.com)
 *
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */

this.imagePreview = function(){
	/* CONFIG */

		xOffset = 10;
		yOffset = 30;

		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result

	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#preview").remove();
    });
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

/*
 * Tooltip script
 * powered by jQuery (http://www.jquery.com)
 *
 * written by Alen Grakalic (http://cssglobe.com)
 *
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
/*this.tooltip = function() {
	*//* CONFIG *//*
		xOffset = 10;
		yOffset = 20;
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
	*//* END CONFIG *//*
	$(".tooltip").hover(function(e) {
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");

		var ttWidth = $("#tooltip").width();

		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#tooltip").remove();
    });
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};*/

/**
 * Insert content at caret position (converted to jquery function)
 * @link
 http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript
 */
$.fn.insertAtCaret = function (myValue) {
	return this.each(function() {
		//IE support
		if (document.selection) {
			this.focus();
			sel = document.selection.createRange();
			sel.text = myValue;
			this.focus();
		}
			//MOZILLA/NETSCAPE support
		else if (this.selectionStart || this.selectionStart == '0') {
			var startPos = this.selectionStart;
			var endPos = this.selectionEnd;
			var scrollTop = this.scrollTop;
			this.value = this.value.substring(0, startPos)
			 + myValue
			 + this.value.substring(endPos,
			 this.value.length);
			this.focus();
			this.selectionStart = startPos + myValue.length;
			this.selectionEnd = startPos + myValue.length;
			this.scrollTop = scrollTop;
		}
		else {
			this.value += myValue;
			this.focus();
		}
	});

};

// start autogrow
//Private variables
var colsDefault = 0;
var rowsDefault = 0;
//var rowsCounter = 0;

//Private functions
function setDefaultValues(txtArea)
{
	colsDefault = txtArea.cols;
	rowsDefault = txtArea.rows;
	//rowsCounter = document.getElementById("rowsCounter");
}

function bindEvents(txtArea)
{
	txtArea.onkeyup = function() {
		grow(txtArea);
	}
}

//Helper functions
function grow(txtArea)
{
    var linesCount = 0;
    var lines = txtArea.value.split('\n');

    for (var i=lines.length-1; i>=0; --i)
    {
        linesCount += Math.floor((lines[i].length / colsDefault) + 1);
    }

    if (linesCount >= rowsDefault)
        txtArea.rows = linesCount + 1;
	else
        txtArea.rows = rowsDefault;
	//rowsCounter.innerHTML = linesCount + " | " + txtArea.rows;
}

//Public Method
jQuery.fn.autoGrow = function(){
	return this.each(function(){
		setDefaultValues(this);
		bindEvents(this);
	});
};
// end autogrow


/**
* Display interactive character limit feedback for text field or text area.
* see http://ndpsoftware.com/show_char_limit.php
*/
jQuery.fn.show_char_limit = function(limit_or_opts, opts) {

  if (!opts) opts = {};

  // if provided max_length, save it
  if (typeof limit_or_opts === 'number') {
  	opts['maxlength'] = limit_or_opts
  } else {
  	opts = limit_or_opts || {}
  }

  var o = jQuery.extend({
    error_class: 'error',
    status_style: 'text',
    status_element_suffix: '__status'
  }, opts);

  var show_limit = function(src) {

    src = jQuery(src);

    var chars_typed = src.val().length;

    var m = src.attr('maxlength');
    if (!m || m == "" || m == -1 || m > 500000) {
    	m = o['maxlength'];
    }
    var left = m - chars_typed;

    var msg;
    if (o.status_style == 'chars_typed') {
      msg = "" + chars_typed;
    } else if (o.status_style == 'chars_left') {
      msg = "" + left;
    } else {
       var status = left >= 0 ? 'left' : 'over';
       var unit = (Math.abs(left) != 1 ? "characters" : "character");
       msg = "" + Math.abs(left) + " " + unit + " " + status;
    }

    var e = o.status_element ? o.status_element : ("#" + src.attr('id') + o.status_element_suffix);
    if (jQuery(e).size() == 0) {
    	if (src.attr('id') == '') {
    	    var id = "" + Math.floor(Math.random() * 9999999999);
    		src.attr('id', id);
    		e = '#'+id + o.status_element_suffix;
    	}
    	src.after('<span class="status" id="'+src.attr('id') + o.status_element_suffix +'"></span>');
    }
    jQuery(e).html(msg);
    if (o.error_element || o.error_element_suffix) {
		var e = o.error_element ? o.error_element : ("#" + src.attr('id') + o.error_element_suffix);
		if (left < 0) {
		  jQuery(e).addClass(o.error_class);
		} else {
		  jQuery(e).removeClass(o.error_class);
		}
    }
  };

  return this.each(function() {
    show_limit(this);
    jQuery(this).keyup(function() {
      show_limit(this);
    });
  });
};

/* CooQuery cookie plugin */
(function($){$.setCookie=function(name,value,options){if(typeof name==='undefined'||typeof value==='undefined')
return false;var str=name+'='+encodeURIComponent(value);if(options.domain)str+='; domain='+options.domain;if(options.path)str+='; path='+options.path;if(options.duration){var date=new Date();date.setTime(date.getTime()+options.duration*24*60*60*1000);str+='; expires='+date.toGMTString();}
if(options.secure)str+='; secure';return document.cookie=str;};$.delCookie=function(name){return $.setCookie(name,'',{duration:-1});};$.readCookie=function(name){var value=document.cookie.match('(?:^|;)\\s*'+name.replace(/([-.*+?^${}()|[\]\/\\])/g,'\\$1')+'=([^;]*)');return(value)?decodeURIComponent(value[1]):null;};$.CooQueryVersion='v 2.0';})(jQuery);

function addSlideHeader() {
	$(".slideHeader").click(function() {
		// do the google analytics event tracking
		if (pageTracker != null) {
			if ($(this).hasClass("slideHeaderExpanded")) {
				pageTracker._trackEvent('Progressive Disclosure', 'Hide', $(this).attr("title"));
			}
			else {
				pageTracker._trackEvent('Progressive Disclosure', 'Show', $(this).attr("title"));
			}
		}

		var slhdr = $(this);

		// do the toggling
		$(this).toggleClass("slideHeaderExpanded");
		slhdr.trigger("slideHeaderStart", $(this).next().height());
		$(this).next().slideToggle("fast", function() {
			slhdr.trigger("slideHeaderFinish");
		});


	});
	$(".slideHeader").each(function() {
		if (!$(this).hasClass("slideHeaderExpanded")) {
			$(this).next().css("display", "none");
		}
	});
}

function addCheckboxShow() {
	$("input.checkboxShow").each(function() {
		if (!$(this).hasClass("show") && !$(this).attr("checked")) {
			$(this).next().css("display", "none");
		}
	});

	$("input.checkboxShow").click(function() {
		handleCheckBoxShowClick($(this));
	});
}

function handleCheckBoxShowClick(checkbox) {
	if (checkbox.attr("checked")) {
		checkbox.next().fadeIn("fast");
	}
	else {
		checkbox.next().fadeOut("fast");
	}
}

function pluralize(singular, count, plural) {
	if (!plural) {
		plural = singular + "s";
	}

	return count == 1 ? singular : plural;
}

function initFeedbackForm() {
	$("#feedback h3").click(function() {
		var theform = $("#feedback form");
		theform.slideToggle("fast");

		//more robust solution
		/*if (!theform.data('jsYes')) {
			theform.prepend("<input type='hidden' name='jsYes' value=''/>");
			theform.data('jsYes', true);
		}*/
	});

	$(document).click(function(e) {
		if ($("#feedback form").css("display") != "none" && $(e.target).closest("#feedback").size() == 0) {
			$("#feedback form").slideUp("fast");
		}
	});

	$("input[name=submitFeedback]").click(function() {

		var theForm = $(this).closest("form");

		$.post(theForm.attr("action"), theForm.serialize(), function(data, status) {
			theForm.find(".console").text(data);
		});
	});

	$("#feedback form").prepend("<input type='hidden' name='jsYes' value=''/>");
}

// resize images automatically
$(function() {
	$('.wiki img').each(function() {
		$(this).bind('load readystatechange', function() {
			var parentWidth = $(this).parent().attr("clientWidth");
			if (this.width > parentWidth && parentWidth > 20) {
				this.width = parentWidth;
			}
		});

		// key line - don't remove. Makes load and readystatechange fire correctly even for cached images
		this.src = this.src;

	});
});

$(document).ready(function() {
	localizeDates();
	imagePreview();
	$(".tooltip").tooltip({showURL: false});
	addSlideHeader();
	$("table.striped tbody tr:odd td").addClass("odd");
	initFeedbackForm();
});


