/**
 *
 * Ajax Content Dialog (ACD)
 *
 * @version 1.0 alpha
 * @author Gareth Clarke
 *
 * @todo Refactor
 * @todo Create as a hash map object
 * @todo Remove dependance on thickbox
 * @todo Extend jQuery?
 * @todo Add min width
 *
**/
var acdContentPadding	= 0;
var acdLayoutWidth		= 400;
var acdLayoutHeight		= 400;
var acdMaxWidth			= 800;
var acdMaxHeight		= 600;
var acdAction			= null;

$(document).ready(function() {
	if (!$.browser.msie || !/8.0/.test(navigator.userAgent)) {
		$(window).resize(acdPosition);

		if (!isUser) $('#my_bookings, .acdQuickLogin, .btnRegister a').click(acdFetchAction);

		$('.acdAction, .but_newcustomer, .but_returningcustomer').click(acdFetchAction);
	}
});

function acdIncludeAssets()
{
	$('#TB_ajaxContent .acdJS').each(function() {
		$.getScript('/js/' + this.name + '.js');
		$(this).remove();
	});
}

function acdRenderView(content)
{
	$('#TB_ajaxContent').append(content);

	acdLayoutWidth = $('#acdLayout dd.content').width();
	acdLayoutHeight = $('#acdLayout').height();

	acdLoadContent($('#acdLayout dt').html(), $('#acdLayout dd.content').html(), $('#acdLayout dd.flashMessage').text());
}

function acdLoadContent(title, content, flashMessage)
{
	$('#TB_ajaxWindowTitle').html(title);
	$('#TB_ajaxContent').html('<div id="acdContent">' + content + '</div>');

	if (flashMessage.length > 0) $('#acdContent').prepend('<strong class="acdFlashMessage">' + flashMessage + '</strong>');

	$('#TB_ajaxContent').height('');
	$('#acdLayout').remove();

	acdIncludeAssets();
	acdPosition();
	setTimeout(acdTrackEvents, '500');
}

function acdFetchAction()
{
	acdAction = this.rel || this.id || null;

	if ($('#TB_window').length < 1) acdCreateDialog();

	this.blur();

	$.get(this.href, function(content) {
		acdRenderView(content);
	});

	return false;
}

function acdTrackEvents()
{
	$('#acdContent .refreshAcd').click(function() {
		document.location = document.location;

		return false;
	});

	$('#acdContent .closeAcd').click(tb_remove);
	$('#acdContent a[rel!="nofollow"]').not('.closeAcd').not('.refreshAcd').click(acdFetchAction);
	$('#acdContent form').submit(acdSubmitForm);

	//loadCount++;
}

function acdCakePostData(inputs)
{
	var cakeData = 'new Object({';

	for (var x = 0; x < inputs.length; ++x) {
		if (inputs[x].name.length > 0) {
			// send through only the selected radio field values
			if (inputs[x].checked || inputs[x].type != 'radio') {
				cakeData += '"' + inputs[x].name + '": "' + inputs[x].value + '",';
			}
		}
	}

	if (acdAction != null) cakeData += '"data[Acd][action]": "' + acdAction + '",';

	return eval(cakeData.substr(0, (cakeData.length - 1)) + '})');
}

// @todo Add support for get method
function acdSubmitForm()
{

	$.post(this.action, acdCakePostData($('#acdContent form :input')), function(response) {
		if (response.indexOf('<') > -1) {
			acdRenderView(response);
		}
		else {
			document.location = (response == 'refresh') ? document.location : response;
		}
	});

	return false;
}

function acdPosition()
{
	if ($('#TB_window').length > 0) {
		acdDetectMaxDimensions();

		TB_WIDTH = acdLayoutWidth + acdContentPadding + 20;

		if (TB_WIDTH > acdMaxWidth) TB_WIDTH = acdMaxWidth + acdContentPadding;
		if ($('#TB_ajaxContent').height() > acdMaxHeight) $('#TB_ajaxContent').height(acdMaxHeight);

		TB_HEIGHT = $('#TB_window').height();

		$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px'});
		$('#TB_ajaxContent').width(TB_WIDTH - acdContentPadding);

		if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
			$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px'});
		}
	}
}

function acdCreateDialog()
{
	$('body').append('<div id="acdLoader" style="display: none;"><p id="acdLoaderContainer">Please wait while we load the content</p></div>');
	tb_show('loading', '#TB_inline?inlineId=acdLoader&width=400&height=200', false);
	$('#acdLoader').remove();

	acdContentPadding = ($('#TB_ajaxContent').css('padding-left').replace('px', '') * 1) + ($('#TB_ajaxContent').css('padding-right').replace('px', '') * 1);
}

function acdDetectMaxDimensions()
{
	var browser = {
		IE:		!!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1),
		Opera:	navigator.userAgent.indexOf('Opera') > -1,
		WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
		Gecko:	navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') === -1,
		getViewHeight: function() {
			return browser.IE ?
			// IE Cases
			// Test for IE 5-7 Quirks and IE 4
			(!(document.documentElement.clientHeight) || (document.documentElement.clientHeight === 0)) ?
				// IE 5-7 Quirks and IE 4 case
				document.body.clientHeight :

				//IE 6+ Strict Case
				document.documentElement.clientHeight:

				// Gecko and Other DOM compliant case
				window.innerHeight;
		},
		getViewWidth: function() {
			return browser.IE ?
			// IE Cases
			// Test for IE 5-7 Quirks and IE 4
			(!(document.documentElement.clientWidth) || (document.documentElement.clientWidth === 0)) ?
				// IE 5-7 Quirks and IE 4 case
				document.body.clientWidth :

				//IE 6+ Strict Case
				document.documentElement.clientWidth:

				// Gecko and Other DOM compliant case
				window.innerWidth;
		}
	};

	acdMaxWidth = browser.getViewWidth() - 80;
	acdMaxHeight = browser.getViewHeight() - 120;
}
