$(document).ready(function() {

/* help dialog */

$.fn.positionHelpDialog = function() {
	return this.position({
		my: 'left top',
		at: 'left top',
		of: window,
		offset: [state.left !== null ? state.left : $(window).width() - state.width, state.top].join(' '),
		collision: 'fit'
	});
};

var dialog = $('<div id="helpDialog"></div>')
		.hide()
		.appendTo('body'),
	// used to  cover the iframe while resizing
	cover = $('<div id="helpDialogCover"></div>')
		.appendTo(dialog),
	fixed = dialog.css('position') == 'fixed',
	state = $.cookie('helpDialog') ? JSON.parse($.cookie('helpDialog')) : {
		top: 0,
		left: null,
		width: 500,
		height: 400,
		open: false,
		minimized: false,
		selected: 0
	},
	searchUrl = state.open && state.selected == 0
		? '/helpdialog/persist/' + icp.now() + Math.random()
		: '/helpdialog/search/node/PAGE_' + window.location.href
			// strip off core URL
			.replace(RegExp(icp.getCoreUrl('/')), '')
			// convert slashes to underscores
			.replace(/\//g, '_')
			// remove query string
			.replace(/\?.*/, '')
			// remove trailing underscore and trailing digits
			.replace(/_\d*$/, '');

function storeState() {
	$.cookie('helpDialog', JSON.stringify(state), {
		path: '/',
		expires: 365
	});
}

function init(url) {
	dialog
		.css({
			height: state.height,
			width: state.width
		})
		.positionHelpDialog()
		.draggable({
			containment: 'document',
			handle: '.controls',
			iframeFix: true,
			stop: function(event, ui) {
				state.left = ui.offset.left - $(window).scrollLeft();
				state.top = ui.offset.top - $(window).scrollTop();
				storeState();
			}
		})
		.resizable({
			containment: 'document',
			alsoResize: '#helpDialogContent, #helpDialogContent iframe, #helpDialogCover',
			minWidth: 450,
			minHeight: 30,
			start: function() {
				cover.css('left', 0);
			},
			stop: function() {
				cover.css('left', '-9999px');

				state.width = dialog.width();
				state.height = dialog.height();

				// resizable doesn't support fixed positioning
				(fixed && dialog.css({
					position: 'fixed',
					top: state.top,
					left: state.left
				}));

				// iframes in other tabs don't resize for some reason
				// TODO: figure out why
				var panels = $('#helpDialogContent .ui-tabs-panel'),
					visibleIframe = panels.filter(':visible').find('iframe'),
					iframeWidth = visibleIframe.width(),
					iframeHeight = visibleIframe.height();
				panels.find('iframe')
					.width(iframeWidth)
					.height(iframeHeight);

				storeState();
			}
		})
		.show();

	cover.css({
		height: dialog.height(),
		width: dialog.width()
	});

	state.open = true;
	storeState();

	var tabs = $('<div>' +
		'<ul>' +
			'<li><a title="helpDialogSearch" href="' +
				(url || icp.getCoreUrl(searchUrl)) + '">Search Help</a></li>' +
			'<li><a title="helpDialogBrowse" href="' +
				icp.getCoreUrl('/helpdialog/browse') + '">Browse Resources</a></li>' +
			'<li><a title="helpDialogContact" href="' +
				icp.getCoreUrl('/helpdialog/contact') + '">Contact Support</a></li>' +
		'</ul>' +
		'<div id="helpDialogContent">' +
			'<div id="helpDialogSearch"></div>' +
			'<div id="helpDialogBrowse"></div>' +
			'<div id="helpDialogContact"></div>' +
		'</div>' +
	'</div>')
		.appendTo(dialog)
		.tabs({
			cache: true,
			selected: state.selected,
			select: function(event, ui){
				state.selected = ui.index;
				storeState();
			},
			load: function(event, ui) {
				$('iframe', ui.panel).height(content.height());
			}
		})
		//remove the title attributes so that tooltips don't display
		.find('> ul a')
			.removeAttr('title')
		.end();
	var content = $('#helpDialogContent');

	$('#helpDialogContent').height(dialog.height() - 30);

	var controls = $('<div></div>')
			.addClass('controls')
			.prependTo(dialog),

		closeButton = $('<a href="#"></a>')
			.attr('id', 'helpCloseButton')
			.click(function() {
				dialog.hide();
				state.selected = 0;
				state.open = false;
				storeState();
				return false;
			})
			.appendTo(controls),

		closeButtonText = $('<span></span>')
			.text('close')
			.appendTo(closeButton),

		minimizeButton = $('<a href="#"></a>')
			.attr('id', 'helpMinimizeButton')
			.click(function() {
				if (state.minimized) {
					content.show();
					minmizeButtonText.text('minimize');
					dialog
						.css('height', state.height)
						.resizable('enable')
						.find('.ui-tabs')
							.tabs('enable', 0)
							.tabs('enable', 1)
							.tabs('enable', 2);
					state.minimized = false;
				} else {
					content.hide();
					minmizeButtonText.text('maximize');
					dialog
						.css('height', 'auto')
						.resizable('disable')
						.find('.ui-tabs')
							.tabs('disable', 0)
							.tabs('disable', 1)
							.tabs('disable', 2);
					state.minimized = true;
				}
				storeState();
				return false;
			})
			.appendTo(controls),

		minmizeButtonText = $('<span></span>')
			.text('minimize')
			.appendTo(minimizeButton);

	if (state.minimized) {
		content.hide();
		minmizeButtonText.text('maximize');
		dialog
			.css('height', 'auto')
			.resizable('disable')
			.find('.ui-tabs')
				.tabs('disable', 0)
				.tabs('disable', 1)
				.tabs('disable', 2);
	}
	
	$(window).bind('resize', function() {
		if (state.open) {
			dialog.positionHelpDialog();
		}
	});
	
	init = function(url) {
		if (!url) { return; }
		
		tabs.tabs('url', 0, url);
		if (tabs.tabs('option', 'selected') !== 0) {
			tabs.tabs('select', 0);
		} else {
			tabs.tabs('load', 0);
		}
	};
	
	if (!fixed) {
		$(window).scroll(function() {
			if (!state.open) { return; }
			
			dialog.stop(true).animate({
				top: $(window).scrollTop() + state.top,
				left: $(window).scrollLeft() + state.left
			}, 200);
		});
	}
}

icp.helpDialog = {
	open: function(url) {
		init(url);
		dialog
			.positionHelpDialog()
			.show();
		state.open = true;
		storeState();
	}
};

var helpUrl = icp.getHelpUrl(),
	helpUrlLength = helpUrl.length;
$('a').live('click', function(event) {
	if (this.href.substr(0, helpUrlLength) == helpUrl) {
		icp.helpDialog.open(icp.getCoreUrl('/helpdialog/' + this.href.substr(helpUrlLength)));
		return false;
	}
});

$('#helpButton a').bind('click', function() {
	icp.helpDialog.open();
	return false;
});

// if the dialog was previously open, open it
if (state.open) {
	icp.helpDialog.open();
}



/* feedback buttons */

$('#feedbackButton a').click(function() {
	icp.openWindow(this.href, {}, {
		name: this.target,
		width: 550,
		height: 600,
		toolbar: 'no'
	});
	return false;
});

});

