var UA = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser)
			|| "unknown";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "unknown";
		this.OS = this.searchString(this.dataOS)
			|| "unknown";
	},
	searchString: function (data) {
		for (var i = 0; i < data.length; i++) {
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1) {
					return data[i].identity;
				}
			} else if (dataProp) {
				return data[i].identity;
			}
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{
			string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera",
			versionSearch: "Version"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{
			// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{
			// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.userAgent,
			subString: "iPhone",
			identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		};
	}//end if
}//end function addLoadEvent()

function applyBlurFocusEventToChildren(which) {
	$(which).find('input, select, textarea').blur(function() { toggleFormField('off', $(this)); });
	$(which).find('input, select, textarea').focus(function() { toggleFormField('on', $(this)); });
}//end function applyBlurFocusEventToChildren()

function copyFormData(source, target) {
	var source_elem = $(source).find('input, select, textarea');
	var target_elem = $(target).find('input, select, textarea');
	for(var i = 0; i < $(source_elem).length; i++) {
		$(target_elem[i]).attr('value', $(source_elem[i]).val());
	}//end for
}//end function copyFormData()

function createModal(title, data, btn, func, width, height, refresh_on_close) {
	try { $('div[aria-labelledby="ui-dialog-title-Modal"]').remove(); } catch (err) { };
	try { $('#Modal').remove(); } catch (err) { };
	$('#Footer').after('<div id="Modal"></div>');
	$('#Modal').html(data);
	if (btn === false) {
		if (refresh_on_close == true) {
			$('#Modal').dialog({
				buttons: [
					{
						text: "Close",
						click: function() {
							$(this).dialog("close");
							window.location.reload();
						}
					}
				],
 				draggable: false,
				height: (height || 'auto'),
//				modal: true,
				resizable: false,
				title: title,
				width: (width || 500),
				close: function(event, ui) {
					$(this).remove();
				}
			});
		} else {
			$('#Modal').dialog({
				buttons: [
					{
						text: "Close",
						click: function() {
							$(this).dialog("close");
						}
					}
				],
				draggable: false,
				height: (height || 'auto'),
//				modal: true,
				resizable: false,
				title: title,
				width: (width || 500),
				close: function(event, ui) {
					$(this).remove();
				}
			});
		}
	} else {
		$('#Modal').dialog({
			buttons: [
				{
					text: btn,
					click: func
				},
				{
					text: "Close",
					click: function() {
						$(this).dialog("close");
					}
				}
			],
			draggable: false,
			height: (height || 'auto'),
//			modal: true,
			resizable: false,
			title: title,
			width: (width || 500),
			close: function(event, ui) {
				$(this).remove();
			}
		});
	}
	$('#Modal').click(function() {
		$('#Modal').css('height', 'auto');
		$('#Modal').dialog('option', 'position', 'center');
	});
	$('#Modal').parent().find('.dialog-minimize').show();
	$('#Overlay').show();
//	$('.ui-widget-overlay').show();
}//end function createModal()

function iframeDialog(title, uri) {
	createModal(
		title,
		'<img src="/omnetrix-ui-2.0.0/css/img/loading.gif" class="iframeDialog"><iframe src="' + uri + '&embedded=true" class="iframeDialog hidden" style="height: 100%; overflow: hidden; overflow-y: auto; width: 100%;" onload="$(\'img.iframeDialog\').addClass(\'hidden\'); $(\'iframe.iframeDialog\').removeClass(\'hidden\'); var iframe = this; var iframedoc = (this.contentDocument || this.contentWindow.document).body; resizeDialog(iframe, iframedoc); rsz = function() { resizeDialog(iframe, iframedoc); }; iframedoc.onclick = rsz;"></iframe>',
		false,
		false,
		300,
		200
	);
	$('#Modal').css('overflow','hidden');
	return false;
}

function iframeResize(iHeight, iWidth) {
	if($.browser.webkit == true) {
		window.parent.$('#Modal').css('width')
		window.parent.$('#Modal').find('iframe').css('height', iHeight);
		window.parent.$('#Modal').find('iframe').css('width', iWidth);
		window.parent.$('#Modal').parent().css('width', iWidth);
		window.parent.$('#Modal').parent().css('height', iHeight);
	} else {
		window.parent.$('#Modal').find('iframe').css('height', iHeight);
		window.parent.$('#Modal').find('iframe').css('width', iWidth);
	}
	
}//end function iframeResize(iHeight, iWidth)

function resizeDialog(cmp1, cmp2, parent) {
	parent = parent || $('#Modal');
	
	var cmp2_w = cmp2.scrollWidth  +  24;
	var cmp2_h = cmp2.scrollHeight + 101;
	
	if($.browser.webkit == true && $(parent).find('iframe').length > 0) {
		var iframedoc = $(parent).find('iframe').contents().find('body > form, body > div, body > table');
		cmp2_w = $(iframedoc).outerWidth() + 24;
		cmp2_h = $(iframedoc).outerHeight() + 101;
	}
	
	var new_h = Math.min(
		$('body').innerHeight() * .9,
		cmp2_h
	);
	
	var new_w = Math.min(
		$('body').innerWidth() * .9,
		cmp2_w
	);
	
	if ($(parent).is(':data(dialog)')) {
		if (new_h != $(parent).dialog('option', 'height')) {
			$(parent).dialog('option', 'height', new_h);
		}
		if (new_w != $(parent).dialog('option', 'width')) {
			$(parent).dialog('option', 'width', new_w);
		}
		$('#Modal').dialog('option', 'position', 'center');
	} else {
		$(parent).css('height', new_h);
		//$(parent).css('width', new_w);
	}
}

function getHTMLTemplate(url, target, method, async) {
	if(typeof method == 'undefined') {
		method = 'replace';
	}
	if(typeof async == 'undefined'){
		async = true;
	} 
	/*
	$.get(url, function(data) {
		switch(method) {
			case 'insert':
				$(target).append(data);
			break;
			case 'replace':
				$(target).html(data);
			break;
		}
	});
	*/
	$.ajax({
		url: url,
		success: function(data) {
			switch(method) {
				case 'insert':
					$(target).append(data);
				break;
				case 'replace':
					$(target).html(data);
				break;
				case 'reload':
					var curpage = window.location.href;
					curpage = curpage.replace(/#.*/, '');
					curpage = curpage.replace(/&rand=[^&]*/, '');
					window.location.href = curpage + '&rand=' + Math.round((new Date()).getTime() / 1000);
				break;
			}
		},
		cache: false,
		async: async	
	}); 
}//end function getHTMLTemplate()

function showgraph(qstr, type) {
	var title = 'Graph';
	var data  = '' +
'<a href="#" onclick="i(0); return false;"><img src="/omnetrix-ui-2.0.0/css/img/graph-bars.png" border="0"></a>' +
'<a href="#" onclick="i(1); return false;"><img src="/omnetrix-ui-2.0.0/css/img/graph-hbars.png" border="0"></a>' +
'<a href="#" onclick="i(2); return false;"><img src="/omnetrix-ui-2.0.0/css/img/graph-lines.png" border="0"></a>' +
'<a href="#" onclick="i(3); return false;"><img src="/omnetrix-ui-2.0.0/css/img/graph-points.png" border="0"></a>'+ 
'<a href="#" onclick="i(4); return false;"><img src="/omnetrix-ui-2.0.0/css/img/graph-linepoints.png" border="0"></a>' +
'<a href="#" onclick="i(5); return false;"><img src="/omnetrix-ui-2.0.0/css/img/graph-pie.png" border="0"></a>' +
'<hr>'+ 
'<img id="graph" src="/graph.pl?' + qstr + '&type=' + type + '" border="0">' +
'<div id="imgmap"></div>'+ 
'<script type="text/javascript">' +
	'var qstr = "' + qstr + '";' +
	'var type = '  + type + ';' +
	'function i(t) {'+ 
		'var imgsrc = "/graph.pl?" + qstr + "&type=" + t;' +
		'$("#graph").attr("src", imgsrc);' +
	'}' +
'</' + 'script>';
	createModal(title, data, false, '', 550, 600);
}//end function showgraph()

function sprintf() { 
	var iCount, iPadLength, aMatch, iMatchIndex = 1;
	var bAlignLeft, sPad, iWidth, iPrecision, sType;
	var aArgs = sprintf.arguments;
	if (aArgs.length < 2) {
		return '';
	}
	var sFormat = aArgs[0];
	var re = /%(-)?(0| |'.)?(\d+)?(\.\d*)?([bcdfosxX]{1})/;
	while (re.test(sFormat)) {
		aMatch = re.exec(sFormat);
		bAlignLeft = (aMatch[1] == '-');
		sPad = (aMatch[2] == '' ? ' ' : aMatch[2]);
		if (sPad.substring(0, 1) == "'") {
			sPad = sPad.substring(1);
		}
		iWidth = (aMatch[3] > 0 ? parseInt(aMatch[3]) : 0);
		iPrecision = (aMatch[4].length > 1 ? parseInt(aMatch[4].substring(1)) : 6);
		sType = aMatch[5];
		mArgument = (aArgs[iMatchIndex] != null ? aArgs[iMatchIndex] : '');
		++iMatchIndex;
		if (mArgument.toString().length) {
			if ('fbcdoxX'.indexOf(sType) != -1 && isNaN(mArgument)) {
				mArgument = 0;
			}
			switch (sType) {
				case 'f':       // floats
					var iPower = Math.pow(10, iPrecision);
					mArgument = (Math.round(parseFloat(mArgument) * iPower) / iPower).toString();
					var aFloatParts = mArgument.split('.');
					if (iPrecision > 0) {
						if (aFloatParts.length == 1) {
							aFloatParts[1] = '';
						}
						// pad with zeroes to precision
						for (iCount = aFloatParts[1].length; iCount < iPrecision; iCount++) {
							aFloatParts[1] += '0';
						}
						mArgument = aFloatParts[0] + '.' + aFloatParts[1];
					} else {
						mArgument = aFloatParts[0];
					}
					iPadLength = aFloatParts[0].length;
				break;
				case 'b':       // binary
					mArgument = parseInt(mArgument).toString(2);
					iPadLength = mArgument.length;
				break;
				case 'c':       // character
					mArgument = String.fromCharCode(parseInt(mArgument));
				break;
				case 'd':       // decimal
					mArgument = mArgument.toString();
					iPadLength = mArgument.length;
				break;
				case 'o':       // octal
					mArgument = parseInt(mArgument).toString(8);
					iPadLength = mArgument.length;
				break;
				case 'x':       // hexadecimal (lowercase)
					mArgument = parseInt(mArgument).toString(16);
					iPadLength = mArgument.length;
				break;
				case 'X':       // hexadecimal (uppercase)
					mArgument = parseInt(mArgument).toString(16).toUpperCase();
					iPadLength = mArgument.length;
				break;
				default:        // strings
					mArgument = mArgument.toString();
					iPadLength = mArgument.length;
			}
			if ('fbdoxX'.indexOf(sType) != -1) {
				// pad with padding-char to width
				if (bAlignLeft) {
					for (iCount = iPadLength; iCount < iWidth; iCount++) {
						mArgument += sPad;
					}
				} else {
					for (iCount = iPadLength; iCount < iWidth; iCount++) {
						mArgument = sPad + mArgument;
					}
				}
			}
		}
		sFormat = sFormat.replace(re, mArgument);
	}
	return sFormat;
}//end function sprintf()

function submitForm(which) {
	if ($(which).find('input[form_submit_method="ajax"]').length == 1) {
		$.ajax({
			url:     $(which).attr('action'),
			type:    $(which).attr('method'),
			data:    $(which).serialize(),
			cache:   false,
			error:   function(msg) {
				alert(msg);
			},
			success: function(msg) {
				alert(msg);
			}
		});
		return false;
	} else {
		return true;
	}//end if
}//end function submitForm()

function tabClick(which) {
	$('a[href="' + which + '"]').click();
}//end function tabClick()

function tbodyScroll() {
	if ($('#Main').length < 1) return;
	if (location.search.match(/app=Offers-Pages-Conditions/)) return;
	var grids = $('table[noresize!="1"].grid');
	if ($(grids).length > 0) {
		$('table[noresize!="1"].grid > tbody').css('height', 'auto');
		var pxAvail = Math.round($('#Main').height() + $('#Main').offset().top -$('#Main').scrollTop() - $('table[noresize!="1"].grid').offset().top - parseInt($('#Main').css('padding-top')) + 35);
		var thead = $(grids[0]).children('thead').outerHeight();
		var tfoot = $(grids[0]).children('tfoot').outerHeight();
		if (pxAvail > 150 && pxAvail < $(grids[0]).children('tbody').outerHeight()) {
			$('table[noresize!="1"].grid > tbody').css('height', (pxAvail - thead - tfoot) + 'px').css('overflow', 'hidden').css('overflow-y', 'auto');
			$('table[noresize!="1"].grid > tbody > tr > td:last-child').css('padding-right', '35px');
		}
	}
}

function toggleFormField(onoff, which) {
	
	var color = '';
	switch (onoff) {
		case 'on':
			try { $(which).removeClass('validation-pass-y'); } catch (err) {};
			try { $(which).removeClass('validation-pass-n'); } catch (err) {};
			$(which).parent().children('input + img, select + img').remove();
			color = '#f9e9ae url(omnetrix-ui-2.0.0/css/custom-theme/images/ui-bg_diagonals-medium_65_f9e9ae_40x40.png)';
			if (typeof $(which).attr('regexp') != 'undefined') {
				$(which).parent().append('<span id="ValidationString">' + ($(which).attr('chartxt') || '&nbsp;') + '</span>');
			}//end if
		break;
		case 'off':
			color = 'none';
			if (typeof $(which).attr('regexp') != 'undefined') {
				if ($(which).val() != '' || $(which).attr('req') == '1') {
					switch (validateFormField($(which))) {
						case 0:
							validationFail(which);
						break;
						case 1:
							validationPass(which);
						break;
					}
				}//end if
				$('#ValidationString').remove();
			}//end if
		break;
	}//end switch
	while ($(which).parent().is('span')) {
		which = $(which).parent();
	}//end while
	if ($(which).parent().is('label')) {
		$(which).parent().css('background', color);
	} else if ($(which).parent().parent().is('tr')) {
		$(which).parent().parent().css('background', color);
	} else {
		//
	}//end if
}//end function toggleFormField()

function validateForm(which) {
	//alert('foo');
	var pass = true;
	var msg  = '';
	$('input[req="1"], select[req="1"], textarea[req="1"]').each(function() {
		if ($(this).val() == '') {
			validationFail($(this));
			pass = false;
			msg += '<span class="ui-icon ui-icon-alert fl"></span>Required fields are missing!<br>';
		}
	});
	$('input[regexp], select[regexp], textarea[regexp]').each(function() {
		var regexp = new RegExp($(this).attr('regexp'),'');
		if ($(this).val() != '' && !$(this).val().match(regexp)) {
			validationFail($(this));
			pass = false;
			msg += '<span class="ui-icon ui-icon-alert fl"></span>Ensure that data passes field restrictions!<br>';
		}
	});
	try {
		var response = customValidation(which);
		if (pass) {
			pass = response[0];
		}
		msg += response[1];
	} catch (err) { };
	if (!pass) {
		msg = '<div class="error ui-state-error ui-corner-all">' + msg + '</div>';
		createModal('Form Validation Error', msg, false, false);
	}
	return pass;
}//end function validateForm()

function validateFormField(which) {
	
	var regexp = new RegExp('^' + ($(which).attr('regexp') || '.+') + '$', '');
	var data = $(which).val();
	return (data.match(regexp) ? 1 : 0);
}//end function validateFormField()

function validationFail(which) {
	$(which).addClass('validation-pass-n');
	$(which).after('<img src="omnetrix-ui-2.0.0/css/img/chk_n.png" style="margin-right: -17px; padding-left: 3px; vertical-align: middle;">');
}

function validationPass(which) {
	$(which).addClass('validation-pass-y');
	$(which).after('<img src="omnetrix-ui-2.0.0/css/img/chk_y.png" style="margin-right: -17px; padding-left: 3px; vertical-align: middle;">');
}

function ______init() {
	UA.init();
	
	// Extended Dialog Functionality
	(
		function($){
			var _init = $.ui.dialog.prototype._init;
			var topMargin = 0;
			
			$.ui.dialog.prototype._init = function() {
				var self = this;
				_init.apply(this, arguments);
				uiDialogTitlebar = this.uiDialogTitlebar;
				
				this.options.originalHeight = this.options.height;
				this.options.originalWidth  = this.options.width;
				this.options.originalLeft   = this.uiDialog.css('left');
				this.options.originalTop    = this.uiDialog.css('top');
				
				this.titlebarHeight = parseInt(uiDialogTitlebar.css('height')) + parseInt(uiDialogTitlebar.css('padding-top')) + parseInt(uiDialogTitlebar.css('padding-bottom')) + parseInt(this.uiDialog.css('padding-top')) + parseInt(this.uiDialog.css('padding-bottom'));
				
				uiDialogTitlebar.children().first().after('<div style="background: transparent url(/omnetrix-ui-2.0.0/css/img/modal-gradient.png) repeat-y left top; bottom: 0.1em; position: absolute; right: 0.3em; top: 0.1em; width: 45px" class="ui-corner-right"></div>');
				
				uiDialogTitlebar.append('<a href="#" class="dialog-restore ui-dialog-titlebar-rest ui-corner-all"><span class="ui-icon">restore</span></a>');
				uiDialogTitlebar.append('<a href="#" class="dialog-minimize ui-dialog-titlebar-min ui-corner-all"><span class="ui-icon">minimize</span></a>');
				
				//Minimize Button
				this.uiDialogTitlebarMin = $('.dialog-minimize', uiDialogTitlebar).hover(
					function() {
						$(this).addClass('ui-state-hover');
					},
					function() {
						$(this).removeClass('ui-state-hover');
					}
				).click(
					function() {
						self.minimize();
						return false;
					}
				).hide();
				
				//Restore Button
				this.uiDialogTitlebarRest = $('.dialog-restore', uiDialogTitlebar).hover(
					function() {
						$(this).addClass('ui-state-hover');
					},
					function() {
						$(this).removeClass('ui-state-hover');
					}
				).click(
					function() {
						self.restore();
						self.moveToTop(true);
						return false;
					}
				).hide();
				
				this.uiDialog.bind('dialogbeforeclose', function(event, ui) {
					$('#Overlay').hide()
					self.uiDialogTitlebarRest.hide();
					self.uiDialogTitlebarMin.hide();
				});
			};
			
			// Custom Dialog Functions
			$.extend(
				$.ui.dialog.prototype, {
					restore: function() {
						this.uiDialog.css('overflow','hidden');
						this.uiDialog.animate({
							height: this.options.originalHeight,
							width: this.options.originalWidth,
							left: this.options.originalLeft,
							top: this.options.originalTop
						}, 200);
						this.element.show();
						this.uiDialog.css('overflow','auto');
						$('#Overlay').show();
//						$('.ui-widget-overlay').show();
						this.uiDialog.removeClass('ui-state-transparent');
						
						this.uiDialogTitlebarRest.hide();
						this.uiDialogTitlebarMin.show();
					},
					minimize: function() {
						this.options.originalHeight = this.options.height;
						this.options.originalWidth  = this.options.width;
						this.options.originalLeft   = this.uiDialog.css('left');
						this.options.originalTop    = this.uiDialog.css('top');
						
						this.uiDialog.animate({
							height: this.titlebarHeight - 1,
							width: 200,
							left: 2,
							top: (parseInt($(window).height()) - this.titlebarHeight - 7)
						}, 200);
						this.element.hide();
						$('#Overlay').hide();
//						$('.ui-widget-overlay').hide();
						this.uiDialog.addClass('ui-state-transparent');
						
						var origBackground = this.uiDialogTitlebar.css('background');
						var dialogBox      = this.uiDialogTitlebar;
						blinkOn = function() {
							$(dialogBox).css('background', '#fc0');
						}
						blinkOff = function() {
							$(dialogBox).css('background', origBackground);
						}
						
						setTimeout(blinkOn,   200);
						setTimeout(blinkOff,  400);
						setTimeout(blinkOn,   600);
						setTimeout(blinkOff,  800);
						setTimeout(blinkOn,  1000);
						setTimeout(blinkOff, 1200);
						
						this.uiDialogTitlebarMin.hide();
						this.uiDialogTitlebarRest.show();
					}
				}
			);
		}
	)(jQuery);
	
	// Tabbed "Step-by-Step" on-page navigation
	try {
		var tabs = $('#StepByStep > ul > li');
		var divs = $('#StepByStep > div');
		for (var i = 0; i < $(tabs).length; i++) {
			if ($(tabs[i]).attr('class') == 'save') {
				$(tabs[i]).css('background', 'none').css('border', '0').css('float', 'right');
				$(tabs[i]).html(
					'<a href="#step-' + (i+1) + '" id="SaveLink-' + (i+1) + '" class="ui-state-default ui-corner-all" style="padding: 4px 10px 3px 5px;">' +
					'<span class="ui-icon ui-icon-disk" style="float: left; margin-right: 5px;"></span>' +
					$(tabs[i]).html() +
					'</a>'
				);
				$('#SaveLink-' + (i+1)).hover(
					function() {
						$(this).toggleClass('ui-state-hover');
					}
				);
				$(divs[i]).css('display', 'none');
			} else {
				$(tabs[i]).html(
					'<a href="#step-' + (i+1) + '">' +
					$(tabs[i]).html() +
					'</a>'
				);
				$(divs[i]).html(
					$(divs[i]).html() +
					'<hr>' +
					((i+1) > 1   ? '<a href="#prev" class="fl ui-state-default ui-corner-all" style="background: none; border: 0; padding: 4px 10px 3px 5px; text-decoration: none;" onclick="tabClick(\'#step-' +   i   + '\'); return false;"><span class="ui-icon ui-icon-circle-triangle-w" style="float: left; margin-right: 5px;"></span>Prev</a>' : '') +
					((i+1) < $(divs).length ? '<a href="#next" class="fr ui-state-default ui-corner-all" style="padding: 4px 5px 3px 10px; text-decoration: none;" onclick="tabClick(\'#step-' + (i+2) + '\'); return false;" onfocus="tabClick(\'#step-' + (i+2) + '\');"><span class="ui-icon ui-icon-circle-triangle-e" style="float: right; margin-left: 5px;"></span>Next</a>' : '')
				);
			}//end if
			$(divs[i]).attr('id', 'step-' + (i+1));
		}//end for
		$('#StepByStep').append('<br style="clear: both;">');
		$('#StepByStep').html(
			'<div>' + 
			$('#StepByStep').html() +
			'</div>'
		);
		$('#StepByStep > div').tabs();
		$('.save a').attr('href', 'javascript: $(\'#Contents form\').submit();');
		$('.save').css('line-height', '1.5').css('margin-top','.5em');
	} catch (err) {};
	
	// Today's date
	$('#Today').html($.datepicker.formatDate('MM d, yy', new Date()));
	$('#CurrentYear').replaceWith($.datepicker.formatDate('yy', new Date()));
	
	//Calendars
	$('#Today').click(function() {
		$('#Calendar').toggleClass('hidden');
	});
	$('input[name="start_date"]').datepicker({
		numberOfMonths: 3,
		showAnim: 'fade',
		showCurrentAtPos: 2,
		stepMonths: 1
	});
	$('input[name="end_date"]').datepicker({
		numberOfMonths: 3,
		showAnim: 'fade',
		showCurrentAtPos: 0,
		stepMonths: 1
	});
	$('input[name="end_date"]').mousedown(function () {
		if ($(this).val() == '') {
			$(this).val($('input[name="start_date"]').val());//.substr(0, 3));
		}
	});
	$('#Calendar').datepicker({
		numberOfMonths: 3,
		showAnim: 'fade',
		showButtonPanel: true,
		showCurrentAtPos: 0,
		stepMonths: 1
	});
	$('#Calendar .ui-datepicker-buttonpane').append('<button onclick="$(\'#Calendar\').toggleClass(\'hidden\');" class="ui-state-default ui-corner-all" type="button">Close</button>');
	$('#Calendar').click(function() {
		if ($('#Calendar .ui-datepicker-buttonpane').children().length == 1) {
			// Needed to prevent button from being removed when the calendar is redrawn upon each click
			$('#Calendar .ui-datepicker-buttonpane').append('<button onclick="$(\'#Calendar\').toggleClass(\'hidden\');" class="ui-state-default ui-corner-all" type="button">Close</button>');
		}
	});
	$('#Calendar').css('margin-right', '327px');
	//$('#Calendar').css('margin-left', Math.floor($('#Calendar').outerWidth() * 1.4) + 'px');
	$('#Calendar').css('position: absolute');
	$('.ui-datepicker').addClass('shadow');
	
	// Help for this page
	$('#Help').dialog({
		autoOpen: false,
		buttons: {
			"Ok": function() { 
				$(this).dialog("close"); 
			}, 
			"Close": function() { 
				$(this).dialog("close"); 
			} 
		},
		height: 300,
		width: 500,
		close: function(event, ui) {
			$(this).remove();
		}
	});
	//$('#Contents > h1').append('<a href="#" id="HelpLink" class="pr ui-widget ui-corner-all">?</a>');
	$('#HelpLink').click(function(){
		$('#Help').dialog('open');
		return false;
	});
	
	// Regrouping options
	$('#RegroupModal').dialog({
		autoOpen: false,
		buttons: {
			"Close": function() { 
				$(this).dialog("close"); 
			} 
		},
		draggable: false,
		height: 250,
		modal: true,
		resizable: false,
		title: 'Regrouping options ...',
		width: 500,
		close: function(event, ui) {
			$(this).remove();
		}
	});
	
	// Enable highlighting when selecting form fields
	$('input, select, textarea').blur(function() { toggleFormField('off', $(this)); });
	$('input, select, textarea').focus(function() { toggleFormField('on', $(this)); });
	
	// The preload class allows us to hide elements while the page is loading
	$('.preload').removeClass('preload');
	
	tbodyScroll();
	
	// Sortable tables
	$('table.sortable').each(function() {
		var cols   = $(this).find('tbody tr:first-child td');
		var ignore = '';
		for (var i = 0; i < $(cols).length; i++) {
			if (/</.test($(cols[i]).html())) {
				ignore = ignore + i + ': { sorter: false}, ';
			}
		}
		if (ignore != '') {
			eval('$(this).tablesorter({ headers: { ' + ignore.substring(0, ignore.length - 2) + ' } });');
		} else {
			$(this).tablesorter();
		}
	});
	
	// Non-standard shells: embedded, noheader, skeleton, widget
	var new_shell = '';
	if (location.search.match(/(?:^\?|&)embedded=true/)) {
		new_shell = 'embedded';
	} else if (location.search.match(/(?:^\?|&)noheader=true/)) {
		new_shell = 'noheader';
	} else if (location.search.match(/(?:^\?|&)skeleton=true/)) {
		new_shell = 'skeleton';
	} else if (location.search.match(/(?:^\?|&)widget=true/)) {
		new_shell = 'widget';
	}
	if (new_shell != '') {
		var f = $(document.body).find('form');
		$(f).each(function() {
			var url = $(f).attr('action');
			url.replace(/(?:embedded|noheader|skeleton|widget)=true&/, '');
			url.replace(/[\?&]$/, '');
			$(f).attr('action', url + (url.match(/\?/) ? '&' : '?') + new_shell + '=true');
		});
		var a = $(document.body).find('a');
		$(a).each(function() {
			var url = $(a).attr('href');
			url.replace(/(?:embedded|noheader|skeleton|widget)=true&/, '');
			url.replace(/[\?&]$/, '');
			$(a).attr('action', url + (url.match(/\?/) ? '&' : '?') + new_shell + '=true');
		});
	}
}//end function ______init()

