// yes this is straight from prototype... its handy but I don't want the overhead of loading all that JS when I don't need it
function $()
{
	var elements = new Array();

	for (var i = 0; i < arguments.length; i++)
	{
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);

		if (arguments.length == 1)
			return element;

		elements.push(element);
	}

	return elements;
}

String.prototype.trim = function() { return this.replace(/^\s*(.*?)\s*$/, '$1'); };

function popupwindow(url, w, h)
{
	if (! w) w = 600;
	if (! h) h = 400;
	mywindow = window.open(url, 'nutpopup', 'status=no,toolbar=no,location=no,menubar=no,scrollbars=yes,resizable=yes,width=' + w + ',height=' + h);
	mywindow.location = url;
}


function addRollover(obj, url)
{
	(new Image).src = url;
	var oldSrc = obj.src;
	obj.onmouseover = function () { this.src = url; }
	obj.onmouseout = function () { this.src = oldSrc; }
}

function addRollovers(objs)
{
	for(var i=objs.length-1; i>=0; i--)
	{
		var value = objs[i].attributes.rollover ? objs[i].attributes.rollover.value : objs[i].rollover || 0;
		if (value)
			addRollover(objs[i], value);
	}
}

// resizes Iframe according to content
function resizeIFrameByID(id)
{
	var obj = $(id);
	if (! obj) return;
	var docHeight = eval(obj.name + '.document.body.scrollHeight');
	obj.style.height = docHeight + 'px';
}

function truncateTestimonial()
{
	var temp = $('truncate-it');
	var dest = $('truncate-dest');
	var inner = $('truncate-quote');

	if (! temp || ! dest || ! inner) return;

	var str = inner.innerHTML;

	var destHeight = 35;

	if (temp.clientHeight > destHeight)
	{
		var suffix = '...';

		var nextOffset = Math.pow(2, Math.floor(Math.log(str.length) / Math.LN2));
		var len = nextOffset;

		do {
			nextOffset = nextOffset >> 1;
			inner.innerHTML = str.substr(0, len) + suffix;
			len = len + (temp.clientHeight > destHeight ? -nextOffset : nextOffset);
		} while (nextOffset > 1);

		inner.innerHTML = str.substr(0, len) + suffix;
		while (len > 0 && temp.clientHeight > destHeight)
		{
			len--;
			inner.innerHTML = str.substr(0, len) + suffix;
		}

		inner.innerHTML = str.substr(0, len).replace(/\s+\S*$/, '') + suffix;

		// if something has gone wrong and we couldn't fit
		// anything, then don't show anything... better than just
		// a quoted ellipsis :)
		if (len == 0)
			return;
	}

	dest.innerHTML = temp.innerHTML;
}

function buttonClicked(targ)
{
	targ.value = 'Please wait...';
	setTimeout('disableButtons()', 0);
}

function disableButtons()
{
	if (! document.getElementsByTagName) return true;
	var inputs = document.getElementsByTagName('input');

	for (i = 0; i < inputs.length; i++)
	{
		var type = inputs.item(i).getAttribute('type');
		if ((type == 'submit') || (type == 'button'))
			inputs.item(i).disabled = true;
	}
}

var tfData = {};
var tfS = '#ffeeae';
var tfE = '#a0e3f6';

function tempFlashGo()
{
	tfData.element = $('tempFlashThis');

	if (! tfData.element)
		return;

	tfData.base = [
		parseInt(tfS.slice(1,3),16),
		parseInt(tfS.slice(3,5),16),
		parseInt(tfS.slice(5),16) ];

	tfData.delta = [
		parseInt(tfE.slice(1,3),16) - tfData.base[0],
		parseInt(tfE.slice(3,5),16) - tfData.base[1],
		parseInt(tfE.slice(5),16) - tfData.base[2] ];

	tfData.frame = 0;
	tfData.interval = setInterval(tempFlashUpdate, 100);
};

function tempFlashUpdate() {
	tfData.frame += 0.2;
	var pos = (-Math.cos(tfData.frame*Math.PI)/2) + 0.5;
	if (tfData.frame > 5.999)
	{
		clearInterval(tfData.interval);
		pos = 0;
	}
	var color = '#';
	for (var i = 0; i < 3; i++)
	{
		var dec = Math.round(tfData.base[i] + (tfData.delta[i] * pos));
		if (dec < 16)
			color += '0';
		color += dec.toString(16);
	}

	tfData.element.style.backgroundColor = color;
}

var needSfFocus = false;
var afterSfSetup = window.onload;
window.onload = function() {
	var navEl = document.getElementById('nav');
	if (navEl) {
		navEl.className = ''; // strip out "noscript" class
		if (window.attachEvent)
			needSfFocus = true;
	//		navEl.className += ' stickyPops';
		var sfEls = navEl.getElementsByTagName('LI');
		for (var i=0; i<sfEls.length; i++) {
			if (sfEls[i].className.match(/\bpop\b/))
			{
				sfEls[i].onmouseover = sfMouseOver;
				sfEls[i].onmouseout = sfMouseOut;
			}
		}
	}

	if (afterSfSetup)
		afterSfSetup();
}

var currentTimeout = null;
var currentPop = null;
var nextPop = null;

function sfMouseOver()
{
	if (needSfFocus)
		this.className += ' sfhover';

	if (currentPop)
		nextPop = this;
	else
		sfPop(this);
}

function sfPop(obj)
{
	currentPop = obj;
	obj.className += ' sfpop';
}

function sfMouseOut()
{
	if (needSfFocus)
		this.className = this.className.replace(/ ?sfhover\b/, '');

	nextPop = null;
	if (currentTimeout)
		clearTimeout(currentTimeout);
	if (currentPop)
		currentTimeout = setTimeout('sfUnpop()', 250);
}

function sfUnpop()
{
	currentTimeout = null;
	currentPop.className = currentPop.className.replace(/ ?sfpop\b/, '');
	currentPop = null;
	if (nextPop)
	{
		sfPop(nextPop);
		nextPop = null;
	}
}


function formatNumber(number, precision, forcePrecision)
{
	number = roundPrecision(number, precision);
	number += '';
	var dpos = number.indexOf('.');
	var numberEnd = '';
	if (dpos != -1)
	{
		numberEnd = number.substring(dpos, number.length);
		number = number.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(number))
	{
		number = number.replace(rgx, '$1,$2');
	}
	if (forcePrecision)
	{
		if (numberEnd.length == 0)
			numberEnd = '.';
		while (numberEnd.length < (precision + 1))
			numberEnd += '0';
	}
	return number + numberEnd;
}

function roundPrecision(number, precision)
{
	number *= Math.pow(10, precision);
	number = Math.round(number);
	number /= Math.pow(10, precision);

	return number;
}

(function($) {

	$.fn.nutsJsonForm = function(options) {
		if (typeof options.clearForm == 'undefined')
			options.clearForm = true;

		options.dataType = 'json';

		if (options.errorDest || options.spinner) {
			var oldBeforeSend = options.beforeSend || function(){};
			options.beforeSend = function() {
				oldBeforeSend.apply(this, arguments);
				if (options.errorDest) { options.errorDest.slideUp('fast'); }
				if (options.spinner)   { options.spinner.show();            }
			};
		}

		if (options.spinner) {
			var oldComplete = options.complete || function(){};
			options.complete = function() {
				options.spinner.hide();
				oldComplete.apply(this, arguments);
			};
		}

		var oldSuccess = options.success || function(){};
		options.success = function(result) {
			if (result.errors && options.errorDest) {
				var ul = options.errorDest.find('ul').empty();
				$.each(result.errors, function() {
					if (this.message) { ul.append($('<li></li>').text(this.message)); }
				});
				options.errorDest.slideDown('fast');
			} else {
				oldSuccess.call(this, result.data, result);
			}
		};

		this.ajaxForm(options);
	};

})(jQuery);
