var NutshellSupportWidgetData;

if (typeof NutshellSupportWidgetData === 'undefined') NutshellSupportWidgetData = { };

NutshellSupportWidget = (function($) {
	/*
	looks for a global variable:
	NutshellSupportWidgetData: {
		name: 'Andy Fowler',
		email: 'afowler@nutshell.com',
		defaultArticle: 'foo.html'
	}
	*/
	
	var widgetPath = '//www.nutshell.com/support-widget/', // eventually absolute
		container = '<div id="support-widget"><div id="support-widget-inner"><iframe></iframe><div id="support-widget-close"></div></div></div>',
		widget = null;
	
	var resetWidget = function(overrideHref) {
		var data = NutshellSupportWidgetData;
		data.location = location.href;
		
		if (typeof overrideHref !== 'undefined')
			data.defaultArticle = overrideHref;
			
			widget.find('iframe').attr('src', widgetPath + 'widget.html?' + $.param(data));
	}
	
	var didOpenYet = false;
	
	return {
		init: function() {
			// events for opens
			$('a.action-open-support-widget').live('click', function(event) {
				var href = $(event.target).attr('href');
				event.preventDefault();
				
				if (href && href.length) {
					var kbRegex = /support\/kb\/(.*)/i,
						kbMatches = kbRegex.exec(href);
					if (kbMatches) resetWidget(kbMatches[1]);
				}
				
				NutshellSupportWidget.open();
			});
			
			// add container to body
			widget = $(container).appendTo('body');
			
			// add outer css
			$('body').append('<link rel="stylesheet" href="' + widgetPath + 'external.css">');
			
			$('#support-widget-close').bind('click', NutshellSupportWidget.close);
			
			$(window).bind('message', function(event) {
				if (event && event.originalEvent) {
					if (event.originalEvent.data == 'hideCloser') {
						NutshellSupportWidget.hideCloser();
					} else {
						NutshellSupportWidget.showCloser();
					} 
				}
			})
		},
		open: function(data) {
			$('html,body').addClass('state-support-widget-open');
			if (!didOpenYet) resetWidget();
			
			$('#support-widget-inner').css('top', $(window).scrollTop() + 'px');
			
			didOpenYet = true;
			widget.show();
		},
		close: function() {
			$('html,body').removeClass('state-support-widget-open');
			widget.hide();
		},
		hideCloser: function() {
			$('#support-widget-close').fadeOut('fast');
		},
		showCloser: function() {
			$('#support-widget-close').fadeIn('fast');
		}
	};
}(jQuery));

$(document).ready(function() {
	NutshellSupportWidget.init();
});
// setTimeout(function() { NutshellSupportWidget.open(); }, 1000);


