var cachedAnchorResults = Array();

var Imagini = {
	"flashCallbacks" : Array(),
	"startedCalls" : Array(),
	"bindEvents" : function(element) {
		// bind ajax functionality to all anchors with "ajaxable" css class & cache results on request
		$(element).find('a.ajaxable').click(function(e) {
			var anchor = $(this);
			if (Imagini.startedCalls[anchor.attr('href')] == null) 
					Imagini.startedCalls[anchor.attr('href')] = true;
				else return false;
			anchor.busy(true);
			if (!cachedAnchorResults[anchor.attr('href')]) {
				$.get($(this).attr('href'), {}, function(result) {
					anchor.blink();
					Imagini.checkResult(result);
					cachedAnchorResults[anchor.attr('href')] = result;
					anchor.busy(false);
					Imagini.startedCalls[anchor.attr('href')] = null;
				}, 'json');
			} else {
				anchor.blink();
				Imagini.checkResult(cachedAnchorResults[anchor.attr('href')]);
				anchor.busy(false);
				Imagini.startedCalls[anchor.attr('href')] = null;
			}
			return false;
		});

		// bind ajax functionality to all forms with "ajaxPost" method
		$(element).find('form.ajaxable').each(function() {
			$(this)
				.ajaxForm({
					dataType: 'json',
					beforeSubmit: Imagini.checkInput, 
					success: Imagini.checkResult
				});
		});
	}, 
	"checkInput" : function() {
		
	}, 
	"checkResult" : function(result) {
		var stopProcess = false;
		if (!result) {
			Imagini.addEvent({priorityName: 'CRIT', timestamp: new Date(), message: 'An error has occured while processing server response. Please try again or contact support'});
			Imagini.checkEvents();
			return false;
		}
		if (result.flashEvents && result.flashEvents.length) {
			for (var i in result.flashEvents) {
				Imagini.addEvent(result.flashEvents[i]);
				if (parseInt(result.flashEvents[i].priority) < 3)
					stopProcess = true;
			}
			if ($('#flashEvents').children('.flashEvent').length)
				$('#flashEvents').slideDown('slow');
		} 
		if (!stopProcess) {
			if (result.jsonDialog) {
				Imagini.openDialog(result.jsonDialog);
			}
			if (result.flashCallbacks && result.flashCallbacks.length) {
				for (var i in result.flashCallbacks)
					eval(result.flashCallbacks[i]);
			}
			if (result.flashRedirect) {
				document.location.assign(result.flashRedirect);
			}
		}
	}, 
	"addEvent" : function(flashEvent) {
		var event = $('<div style="display: none;" class="flashEvent ' + flashEvent.priorityName 
					+ '"><div class="flashTime">[' + flashEvent.priorityName + ']' + flashEvent.timestamp + '</div>'
					+ flashEvent.message + '</div>');
		$('#flashEvents').prepend(event);
		event.click(function() { 
			$(this).hide('fast', function() {
				$(this).remove();
				if (!$('#flashEvents').children('.flashEvent').length) $('#flashEvents').hide('fast');
			});
		});
		event.slideDown('slow');
	},
	"showMessage" : function(message) {
		Imagini.addEvent({priorityName: 'INFO', timestamp: new Date(), message: message});
		Imagini.checkEvents();
	}, 
	"checkEvents" : function() {
		if ($('#flashEvents').children().length) {
			$('#flashEvents').children()
				.unbind('click')
				.click(function() { 
					$(this).hide('fast', function() {
						$(this).remove();
						if (!$('#flashEvents').children('.flashEvent').length) $('#flashEvents').hide('fast');
					});
				});
			$('#flashEvents').slideDown('slow');
		}
		if (Imagini.flashCallbacks && Imagini.flashCallbacks.length) {
			for (var i in Imagini.flashCallbacks)
				eval(Imagini.flashCallbacks[i]);
		}
	}, 
	"loadDialog" : function(url) {
		if (!cachedAnchorResults[url]) {
			$.get(url, {}, function(result) {
				Imagini.checkResult(result);
				cachedAnchorResults[url] = result;
			}, 'json');
		} else {
			Imagini.checkResult(cachedAnchorResults[url]);
		}
		return false;
	}, 
	"openDialog" : function(options) {
		$('#modalOverlay')
				.stop()
				.css('opacity', 0)
				.show()
				.animate({opacity: .7}, function() {
					$('#mainDialog')
						.stop()
						.css('opacity', 0)
						.html(options.content || '')
						.css('top', $(window).height() / 2 - $('#mainDialog').height() / 2)
						.css('left', $(window).width() / 2 - $('#mainDialog').width() / 2)
						.show()
						.click(function(e) {
							if ($(e.target).attr('id') == $(this).attr('id')) {
								return false;
							}
						})
						.animate({opacity: 1}, 500, function() {
							$(this).find('input:first').focus();
							Imagini.bindEvents($(this));
							$(this).find('.closeDialogTrigger').click(function(e) {
								if (options.confirm) {
									if (confirm(options.confirm)) Imagini.closeDialog();
								} else Imagini.closeDialog();
							});
							if (options.callback) eval(options.callback);
						})
						.unbind('keypress')
						.bind('keypress', function(e) {
							var key  = (window.event) ? event.keyCode : e.keyCode;
							if(key == 27) {
								if (options.confirm) {
									if (confirm(options.confirm)) Imagini.closeDialog();
								} else Imagini.closeDialog();
							}
						});
				})
				.unbind('click')
				.bind('click', function() {
					if (options.confirm) {
						if (confirm(options.confirm)) Imagini.closeDialog();
					} else Imagini.closeDialog();
				});
	}, 
	"closeDialog" : function() {
		if (Imagini.beforeCloseDialog) {
			Imagini.beforeCloseDialog();
			Imagini.beforeCloseDialog = false;
		}
		$('#modalOverlay').unbind('click');
		$('#mainDialog').animate({opacity: 0}, 500, function() {
			$(this).html('');
			$('#modalOverlay').animate({opacity: 0}, 500, function() {
				$(this).hide();
				if (Imagini.afterCloseDialog) {
					Imagini.afterCloseDialog();
					Imagini.afterCloseDialog = false;
				}
			});
		});
		return false;
	},

	"startQuiz" : function(container, quizData, url) {
		var quiz = null;
		var choices = "";

		var imagesHolder = container.find('.imagesHolder');
		var quizTitle = container.find('.quizTitle');
		var quizProgress = container.find('.quizProgress .progressBar');

		$('#spinnerHolder')
			.css('top', (parseInt(imagesHolder.offset().top) + (parseInt(imagesHolder.height()) / 2)) - 100)
			.css('left', (parseInt(imagesHolder.width()) / 2))
			.css('position', 'absolute')
			.css('z-index', '99')
			.show();

		animateBox = function(boxId) {
			box = imagesHolder.find('a#' + boxId);
			box.effect('pulsate', {times: 1}, 200);
			nextBox = box.next('a');
			if (nextBox.attr('id') && nextBox.attr('id').length) {
				setTimeout("animateBox('" + nextBox.attr('id') + "');", 50);
			}
		};

		runQuiz = function(key) {
			if (quizData.statements[key]) {

				var next = null;
				var current = 0;
				var total = 0;
				for (var k in quizData.statements) {
					if (next == true)
						next = k;
					if (k == key && next == null) next = true;
					if (next == null)
						current++;
					total++;
				}

				quizTitle.html('<h1>' + quizData.statements[key].label + '</h1><h2>Click one image</h2>');
				
				var j=0;
				for (var i in quizData.statements[key].choices) j++
				if (j == 3) 
				{
					imagesHolder.css("padding-left", "75px");
				}
				else 
				{
					if (j == 2) 
					{
						imagesHolder.css("padding-left", "150px");
					}
					else
					{
						imagesHolder.css("padding-left", "0");
					}
				}		
				 
				for (var i in quizData.statements[key].choices) {
				
					var image = $('<a href="javascript:void(0)" rel="' + quizData.statements[key].ident 
									+ '" id="' + quizData.statements[key].choices[i].ident 
									+ '" alt="' + ((100 / total) * (current + 1)) + '"><img src="' + quizData.defaultImageSource + '/' + quizData.statements[key].choices[i].fileName + '" /></a>');
					image.click(function() {
						sendStatementEvent($(this).attr('rel'), "CLICK");
						quizProgress.animate({width: parseInt($(this).attr('alt')) + '%'}, 200);
						if (tipTimer) {
							clearTimeout(tipTimer);
							tipTimer = false;
						}
						$('#toolTip').hide();
						$('#toolTip').empty();
						choices += '&choices[' + $(this).attr('rel') + ']=' + $(this).attr('id');
						container.animate({opacity: 0}, 100, function() {
							imagesHolder.empty();
							imagesHolder.show();
							runQuiz(next);
						});
						return false;
					});
					imagesHolder.append(image);
				}

				sendStatementEvent(quizData.statements[key].ident, "IMPRESSION");

				var tipTimer = false;
				// bind tip on a hover
//				Imagini.bindEvents(imagesHolder);

			} else {
				imagesHolder.empty();
				quizTitle.html('<h1>Loading your results ...</h1>');
				$('#spinnerHolder').show();
				$.post(url, choices, 
					function(result) {
						Imagini.checkResult(result);
						if (result && result.responseId)
							sendModuleCompleteEvent(result.responseId);
						$('#spinnerHolder').hide();
					}, 'json');
			}

			container.animate({opacity: 1}, 100, function() {});
		};

		var first = null;

		for (var key in quizData.statements) {
			if(typeof(quizData.statements[key]) !== 'function') {
				first = key;
				break;
			}
		}

		container.find('.redoQuiz').click(function() {
			$('#spinnerHolder').hide();
			choices = "";
			quizProgress.animate({width: 0});
			imagesHolder.empty();
			runQuiz(first);
			return false;
		});

		$('#spinnerHolder').hide();
		sendModuleStartEvent();
		runQuiz(first);
		firstBox = imagesHolder.find('a').eq(0);
		setTimeout("animateBox('" + firstBox.attr('id') + "')", 100);
	}, 
	"selectText" : function(text) {
		if ($.browser.msie) {
			var range = document.body.createTextRange();
			range.moveToElementText(text);
			range.select();
		} else if ($.browser.mozilla || $.browser.opera) {
			var selection = window.getSelection();
			var range = document.createRange();
			range.selectNodeContents(text);
			selection.removeAllRanges();
			selection.addRange(range);
		} else if ($.browser.safari) {
			var selection = window.getSelection();
			selection.setBaseAndExtent(text, 0, text, 1);
		}
	}
};

$(function() {
	if ($.browser.msie == true && parseInt($.browser.version.substring(0, 1)) <= 6) {
//		Imagini.showMessage("Sorry you're having problems viewing this page - we recommend that you <a href='http://www.microsoft.com/windows/internet-explorer/default.aspx' target='_blank'>upgrade your browser to the latest version of Internet Explorer</a>. It will help your experience of Audience Analytics, and other sites across the web too.");
	}
	setTimeout(Imagini.checkEvents, 300);
	Imagini.bindEvents($('body'));
});

if(jQuery) (function($){
	$.extend($.fn, {
		busy: function(flag) {
			if (flag == true) {
				var busyModal = $('<div class="busyModal"></div>');
				$(this).after(busyModal);
				busyModal
					.css('opacity', 0)
					.show()
					.css('left', $(this).offset().left)
					.css('top', $(this).offset().top)
					.css('width', $(this).outerWidth())
					.css('height', $(this).outerHeight())
					.animate({opacity: .5});
			} else {
				$(this).next('.busyModal')
						.animate({opacity: 0}, 500, function() {
							$(this).remove();
						});
			}
		}, 
		blink: function(callback) {
			$(this).animate({opacity: 0}, 200, function() {
				$(this).animate({opacity: 1}, 200, callback);
			});
		}
	});
})(jQuery);