var cachedAnchorResults = Array();
var mouseX = 0;
var mouseY = 0;

$().mousemove( function(e) {
	mouseX = e.pageX;
	mouseY = e.pageY;
});

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
				});
		});

		// add frames to .imageFrame class elements
		$(element).find('.imageFrame').each(function() {
			$(this).append('<div class="frame"></div>');
			var img = $(this).find('img');
			if (!img.attr('onerror'))
				img.attr('onerror', 'this.src=\'' + Imagini.skinImagePath + 'icons/user.jpg\';');
			
		});

		var tipTimer = false;

		// bind tip on a hover
		// interferes with callouts on home page
		/*$(element).find('a[title|tip]').each(function() {
			if (!$(this).attr('tip')) 
				$(this).attr('tip', $(this).attr('title'));
			$(this).removeAttr('title');
			$(this).hover(
				function(e) {
					if (!tipTimer)
					{
						var link = $(this);
						tipTimer = setTimeout(function() {
							if (!$('body > #toolTip').attr('id')) {
								var tip = $('<div id="toolTip"></div>');
								$('body').append(tip);
							} else tip = $('#toolTip');

							tip.stop()
								.html(link.attr('tip'));
							tip.css('top', mouseY + 20)
								.css('left', mouseX + 10)
								.css('opacity', 0)
								.css('width', 'auto')
								.css('white-space', 'nowrap')
								.show();
							if (tip.width() > 600) 
							{
								tip.css('width', 600)
									.css('white-space', 'normal');
							}

							if (tip.offset().left + tip.width() > $('body').width())
								tip.css('left', mouseX - tip.width() - 10);
							if (tip.offset().top + tip.height() > $('body').height())
								tip.css('top', mouseY - tip.height() - 20);
							tip.animate({opacity: 1});
						}, 300);
					}
				}, 
				function(e) {
					if (tipTimer) {
						clearTimeout(tipTimer);
						tipTimer = false;
					}
					$('#toolTip').hide();
				}
			);
		});*/

		// Hover Zoom functionality
		$(element).find('.hoverZoom').each(function() {
			if ($(this).css('max-width')) {
				$(this).hover(
					function() {
						if (!this.oldHeight) {
							this.oldHeight = parseInt($(this).height());
							this.oldOffsetTop = $(this).offset().top;
							this.oldWidth = parseInt($(this).width());
							this.oldOffsetLeft = $(this).offset().left;
							$(this)
								.css('position', 'absolute')
								.css('top', this.oldOffsetTop)
								.css('left', this.oldOffsetLeft);
						}
						maxWidth = parseInt($(this).css('max-width'));
						ot = this.oldOffsetTop - (maxWidth - this.oldWidth) / 2;
						ol = this.oldOffsetLeft - (maxWidth - this.oldWidth) / 2;
						$(this).css('z-index', 2)
								.animate({width: $(this).css('max-width'), left: ol, top: ot}, 50);
					}, 
					function() {
						$(this).css('z-index', 0)
							.animate({width: this.oldWidth, left: this.oldOffsetLeft, top: this.oldOffsetTop}, 50);
					}
				);
			}
		});
	}, 
	"checkInput" : function() {
		
	}, 
	"checkResult" : function(result) {
		var stopProcess = 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) {
		// display tip message
/*		if (!$('body > #toolTip').attr('id')) {
			var tip = $('<div id="toolTip"></div>');
			$('body').append(tip);
		} else tip = $('#toolTip');

		$().mousemove( function(e) {
			mouseX = e.pageX;
			mouseY = e.pageY;
			tip.css('top', mouseY + 20)
				.css('left', mouseX + 10);
		});

		tip.html(message);
		tip.css('top', mouseY + 20)
			.css('left', mouseX + 10)
			.fadeIn();
		tipTimer = setTimeout(function() { 
			$('#toolTip').fadeOut(); 
			$().mousemove( function(e) {
				mouseX = e.pageX;
				mouseY = e.pageY;
			});
		}, 15000);
*/
		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('fast');
		}
		if (Imagini.flashCallbacks && Imagini.flashCallbacks.length) {
			for (var i in Imagini.flashCallbacks)
				eval(Imagini.flashCallbacks[i]);
		}
	}, 
	"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');
		var quizLoader = container.find('.quizLoader');
		var loaderPreview = container.find('.loaderPreview');

		quizTitle.html('<h1>Please hold on whilst we load your quiz... It\'s really worth it!</h1>');
		container.busy(true);

		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>');
				for (var i in quizData.statements[key].choices) {
					var image = $('<a href="#" 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>Calculating your VisualDNA</h1>');
				$('#spinnerHolder').show();
				$.post(url, choices, 
					function(result) {
						Imagini.checkResult(result);
						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;
		});

		// assets preloader
		var assets = [];
		Imagini.quizAssetsLoaded = 0;
		for (var s in quizData.statements) {
			for (var c in quizData.statements[s].choices) {
				assets.push(quizData.defaultImageSource + '/' + quizData.statements[s].choices[c].fileName);
			}
		}
		for (var i in assets) {
			var img = document.createElement('img');
			quizLoader[0].appendChild(img);
			img.onload = function() {
				Imagini.quizAssetsLoaded++;
				quizProgress.css({width: ((Imagini.quizAssetsLoaded / assets.length) * 100) + '%'});
				loaderPreview.html('<img src="' + this.src + '" />');
				if (Imagini.quizAssetsLoaded == assets.length) {
					container.busy(false);
					loaderPreview.remove();
					imagesHolder.css({opacity: 0}).show('slow').animate({opacity: 1}, 1000, function () {
						$('#spinnerHolder')
							.css('top', (parseInt(imagesHolder.offset().top) + (parseInt(imagesHolder.height()) / 2)) - 100)
							.css('left', (parseInt(imagesHolder.offset().left) + (parseInt(imagesHolder.width()) / 2)) - 100);
					});
					quizProgress.animate({width: '0%'}, 1000);
					sendModuleStartEvent();
					runQuiz(first);
					firstBox = imagesHolder.find('a').eq(0);
					setTimeout("animateBox('" + firstBox.attr('id') + "')", 100);
				}
			}
			img.src = assets[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;
	},
	"relocate" : function(obj) {
		document.location.assign(obj.value);
	},
	"getQuestion" : function(url, obj) {
		if (!isNaN(obj.value))
			document.location.assign(url.replace("0", obj.value));
		else
			document.location.assign(obj.value);
	},
	"deleteQuestion" : function(question, deleteUrl) {
		var mess = "Are you sure you want to delete this question: \n\n " + question;
		if (confirm(mess))
			document.location.assign(deleteUrl);
	}
};

$(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 Youniverse, 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);
			});
		}, 
		tabs: function(selected) {
			$(this).find('.tabTrigger').click(function() {
				$('.tabTrigger.selected').removeClass('selected');
				$(this).addClass('selected');
				$(this).children('*').blur();
				$('.tabContent:visible').hide();
				$('.tabContent.' + $(this).attr('id')).show(200, function() {
				});
				return false;
			});
			if (selected) {
				$('.tabTrigger#' + selected + 'Tab').click();
			}
		}
	});
})(jQuery);
