// stop image flicker on backgrounds in ie6
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

var cachedAnchorResults = Array();
var Imagini = {
	"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);
			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);
				}, 'json');
			} else {
				anchor.blink();
				Imagini.checkResult(cachedAnchorResults[anchor.attr('href')]);
				anchor.busy(false);
			}
/*
			Imagini.afterCloseDialog = function() {
				$(document).scrollTo(anchor, 200, function() {
					anchor.focus();
					anchor.blink();
				});
			};
*/
			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
				});
		});

		var tipTimer = false;

		// bind tip on a hover
		/*
		$(element).find('a[title]').each(function() {
			$(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.html(link.attr('tip'));
							tip.css('top', e.pageY + 20)
								.css('left', e.pageX + 10)
								.show();
						}, 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('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).animate({width: $(this).css('max-width'), left: ol, top: ot}, 50);
					}, 
					function() {
						$(this).animate({width: this.oldWidth, left: this.oldOffsetLeft, top: this.oldOffsetTop}, 50);
					}
				);
			}
		});

		$(element).find('.quizHolder').each(function() {
			Imagini.startQuiz($(this), $(this).attr('rel'));
		});
		
		$(element).find('.clients').change(function() {
			var location = '/myvdna'; 
			if ($(this).val() != '')
				location = '/display-' + $(this).val();
			window.location = location;
		});
	}, 
	"checkInput" : function() {
		
	}, 
	"checkResult" : function(result) {
		var stopProcess = false;
		if (result.flashEvents && result.flashEvents.length) {
			for (var i in result.flashEvents) {
				var event = $('<div style="display: none;" class="flashEvent ' + result.flashEvents[i].priorityName 
							+ '"><div class="flashTime">[' + result.flashEvents[i].priorityName + ']' + result.flashEvents[i].timestamp + '</div>'
							+ result.flashEvents[i].message + '</div>');
				$('#flashEvents').prepend(event);
				event.slideDown('slow');
				if (parseInt(result.flashEvents[i].priority) < 3)
					stopProcess = true;
			}
			$('#flashEvents')
				.children().click(function() { 
								$(this).blur();
								$(this).hide('fast', function() {
									$(this).remove();
									if (!$('#flashEvents').children('.flashEvent').length) $('#flashEvents').hide('fast');
								});
							});
			$('#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) {
				window.location = result.flashRedirect;
			}
		}
	}, 
	"startQuiz" : function(container, url) {
		quiz = null;
		choices = "";

		var imagesHolder = container.find('.imagesHolder');
		var quizTitle = container.find('.quizTitle');
		var quizProgress = container.find('.quizProgress .progressBar');

		runQuiz = function(key) {
			if (quiz.statements[key]) {
				imagesHolder.empty();
				quizTitle.html('<h1>' + quiz.statements[key].label + '</h1>');
				for (var i in quiz.statements[key].choices) {
					var image = $('<a href="#" rel="' + quiz.statements[key].ident 
									+ '" id="' + quiz.statements[key].choices[i].ident 
									+ '"><img src="' + quiz.defaultImageSource + '/' + quiz.statements[key].choices[i].fileName + '" /></a>');
					image.click(function() {
						quizProgress.animate({width: ((100 / quiz.statements.length) * (key + 1)) + '%'}, 200);
						choices += '&choices[' + $(this).attr('rel') + ']=' + $(this).attr('id');
						runQuiz(key+1);
						return false;
					});
					imagesHolder.append(image);
				}
			} else {
				imagesHolder.empty();
				$.post(url, 
					choices, 
					function(result) {
						Imagini.checkResult(result);
					}, 
					'json'
				);
			}
		};

		$.getJSON(url, {}, function(result) {
			Imagini.checkResult(result);
			quiz = result.quiz;

			container.find('.redoQuiz').click(function() {
				choices = "";
				quizProgress.animate({width: 0});
				runQuiz(0);
				return false;
			});

			runQuiz(0);
		});
	}, 
	"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')
				.css('opacity', 0)
				.show()
				.animate({opacity: .7}, function() {
					$('#mainDialog')
						.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;
	},

	"showInput": function(tagType, thisItem) {
		if ( $("#tagInput").length == 0)
		{
			var html = $(thisItem).parent().parent().find("ul").html();
			$(thisItem).parent().parent().find("ul").html("");
			var funcCall = "Imagini.addTag('" + tagType + "', $(this).parent().find('input').val())";
			$(thisItem).parent().parent().find("ul").append('<li><input id="tagInput" type="text"> <img class="buttonStyle" height="16" onclick="' + funcCall + '" title="Add" src="/skin/default/images/general/confirm.png"> <img class="buttonStyle" height="16" onclick="$(this).parent().remove();" title="Delete" src="/skin/default/images/general/remove.png"></li>' + html);
			$("#tagInput").focus();
			$("#tagInput").bind('keypress', function(e) {
				var key  = (window.event) ? event.keyCode : e.keyCode;
				if(key == 13) {
					Imagini.addTag(tagType, $(this).val());
				}
			});
		}
		else
		{
			alert("Please act on the current input!");
			$("#tagInput").focus();
		}
	},

	"addTag": function(tagType, tagValue) {
		if (tagValue == '')
		{
			alert("Item value cannot be empty!");
			return false;
		}
		var url = "/addtag";
		$.get(url, {tagType: tagType, tagValue: tagValue}, function(result) {
				if (result.success == 'true')
				{
					var thisFontSize = Math.round((Math.log(100)+10));
					var params = "'" + result.tagType + "', '" + result.tagValue + "'";
					var html = '<div style="display:inline;">'+
							'<img class="buttonStyle" height="12" onclick="Imagini.confirmTag(' + params + ')" title="Confirm" src="/skin/default/images/general/confirm.png"> '+
							'<img class="buttonStyle" height="12" onclick="Imagini.removeTag(' + params + ')" title="Remove" src="/skin/default/images/general/remove.png"> '+
							'</div><div style="display:inline;font-size:' + thisFontSize + 'px;">'+ result.tagValue +'</div>';

					$("#tagInput").parent().html(html);
				}
				else
				{
					alert("An error has occurred while trying to add your item. Please try again later.");
					console.log(result.error);
				}
			}, 'json');
	},

	/* delete tag function */
	"deleteTag": function()
	{
		$(".tags-box-body ul").live('click', function() {
			primaryTagArr = $(this).parent().attr("class").split(" ")[1].split("_");
			primaryTagArr.pop();
			primaryTag = primaryTagArr.join("_");
			$.post("/removetag", {completeTagType: $(this).attr("name"), tag_id: $(this).attr("id"), tag_name: primaryTag, tag_value: $(this).find("li:last-child span").html(), type: "remove"},
				function(result) 
				{
					if (result.success == 'true')
					{
						//adding back to the tags array the removed tag, so it can be added again
						tags[primaryTag][tags[primaryTag].length] = {completePath: result.tagtype + "/" + result.tagValue, id: result.tag_id, name: result.tagValue};
						eval("Imagini.autocomplete_" + primaryTag + "(false);");
						eval("Imagini.autocomplete_" + primaryTag + "(true);");

						$("#" + result.tag_id).next().remove();
						if ($("#" + result.tag_id).prev().attr("tagName") == "H4" && ($("#" + result.tag_id).next().attr("tagName") == "H4" || $("#" + result.tag_id).next().attr("tagName") == null))
						{
							$("#" + result.tag_id).prev().remove();
						}
						$("#" + result.tag_id).remove();
					}
				}, "json"
			);
		});
	},

	"showLoader": function(obj)
	{
		var notValid = true;
		$.each(obj, function(){
			if (this.name == "tag_value" && (this.value == "" || this.value == "Type in the new tag you want to add"))
			{
				notValid = false;
				return false;
			}
			if (this.name == "tag_id" && this.value == "")
			{
				notValid = false;
				return false;
			}
			if (this.name == "tag_name")
				thisFormClass = this.value;
		});
		if (!notValid)
			return false;
		$("." + thisFormClass).parent().find("div.loader").show();
	},

	"showResponse": function(result)
	{
		$("." + result.thisForm).parent().find("div.loader").hide();
		$("." + result.thisForm).find(".tags-add-input").val("");
		if (result.success == 'true')
		{
			var tagArr = result.tagType.replace(" / ", "+").split('/');
			for (var i in tagArr)
			{
				tagArr[i] = tagArr[i].replace("+", " / ");
			}
			var contentDiv = result.thisForm + "_content";
			var primaryTagExists = false;
			var primaryTag = tagArr[0];
			$.each($("." + contentDiv).find("h4"), function(){
				if (this.innerHTML == primaryTag)
				{
					primaryTagExists = true;
					var html = "<ul id='" + result.tag_id + "'>";
					if (tagArr.length > 2)
					{
						tagArr.shift();
						for (var i in tagArr)
						{
							html += "<li><span>" + tagArr[i] + "</span></li>";
						}
					}
					else
					{
						html += "<li><span>" + tagArr[1] + "</span></li>";
					}
					html += "</ul>";
					html += '<div class="clear"></div>';
					$(html).insertAfter(this);
				}
			});
			if (!primaryTagExists)
			{
				$("." + contentDiv).append("<h4>" + tagArr[0] + "</h4>");
				var html = "<ul id='" + result.tag_id + "'>";
				if (tagArr.length > 2)
				{
					tagArr.shift();
					for (var i in tagArr)
					{
						html += "<li><span>" + tagArr[i] + "</span></li>";
					}
				}
				else
				{
					html += "<li><span>" + tagArr[1] + "</span></li>";
				}
				html += "</ul>";
				html += '<div class="clear"></div>';
				$("." + contentDiv).append(html);
			}
			$("#" + result.tag_id + " li:last-child").addClass("last-item");
			Imagini.addTagEvents();

			//removing the tag from the array, so it can't be added again
			eval("tags['" + result.thisForm + "'] = jQuery.grep(tags['" + result.thisForm + "'], function(value){return value.id != '" + result.tag_id + "';});");
			eval("Imagini.autocomplete_" + result.thisForm + "(false);");
			eval("Imagini.autocomplete_" + result.thisForm + "(true);");
		}
	},

	"addTagEvents": function(){
		var $tags = $('.tags-box-body').children().find('li');
		$.each($tags, function(){
			$(this).bind('mouseover', function(e){
				$(this).parent().addClass('over');
				var left = (e.pageX - $(this).x()) - 40;
				if($(this).children('div').length == 0){
					$(this).append(
						$('<div></div>').addClass('remove').css('left', left + 'px').html('<strong>Remove Tag</strong>')
					)
					Imagini.zIndexWorkaround();
				}
			})
	
			$(this).bind('mouseout', function(){
				$(this).parent().removeClass('over');
				$(this).children('div').remove();
			})
		});
	},

	"zIndexWorkaround": function(){
		$("div.remove").parents().each(function() {
			var p = $(this);
			var pos = p.css("position");
			
			// If it's positioned,
			if(pos == "relative" || pos == "absolute" || pos == "fixed")
			{
				p.hover(function() {
					$(this).addClass("on-top");
				},
				function() {
					$(this).removeClass("on-top");
				});
			}
		});
	},

	"autocomplete_current_status": function(val)
	{
		if (val == true)
		{
			$("#current_status-box .tags-add-input").autocomplete(tags["current_status"],{
				mustMatch: true,
				autoFill: true,
				width: 370,
				formatItem: function(row, i, max) {
					return i + "/" + max + ": \"" + row.completePath;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.name;
				}
			}).result(function(event,data,formatted){ if (typeof(data) != "undefined") $(".current_status .tag_id").val(data["id"])});
		}
		else
		{
			$("#current_status-box .tags-add-input").unautocomplete();
		}
	},
	
	/* interests */
	"autocomplete_interests": function(val)
	{
		if (val == true)
		{
			$("#interests-box .tags-add-input").autocomplete(tags["interests"],{
				mustMatch: true,
				autoFill: true,
				width: 370,
				formatItem: function(row, i, max) {
					return i + "/" + max + ": \"" + row.completePath;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.name;
				}
			}).result(function(event,data,formatted){ if (typeof(data) != "undefined") $(".interests .tag_id").val(data["id"])});
		}
		else
		{
			$("#interests-box .tags-add-input").unautocomplete();
		}
	},
	
	/* goals */
	"autocomplete_long_term_goals": function(val)
	{
		if (val == true)
		{
			$("#long_term_goals-box .tags-add-input").autocomplete(tags["long_term_goals"],{
				mustMatch: true,
				autoFill: true,
				width: 370,
				formatItem: function(row, i, max) {
					return i + "/" + max + ": \"" + row.completePath;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.name;
				}
			}).result(function(event,data,formatted){ if (typeof(data) != "undefined") $(".long_term_goals .tag_id").val(data["id"])});
		}
		else
		{
			$("#long_term_goals-box .tags-add-input").unautocomplete();
		}
	},
	
	/* intent */
	"autocomplete_intent": function(val)
	{
		if (val == true)
		{
			$("#intent-box .tags-add-input").autocomplete(tags["intent"],{
				mustMatch: true,
				autoFill: true,
				width: 370,
				formatItem: function(row, i, max) {
					return i + "/" + max + ": \"" + row.completePath;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.name;
				}
			}).result(function(event,data,formatted){ if (typeof(data) != "undefined") $(".intent .tag_id").val(data["id"])});
		}
		else
		{
			$("#intent-box .tags-add-input").unautocomplete();
		}
	},
	
	/* traits */
	"autocomplete_traits": function(val)
	{
		if (val == true)
		{
			$("#traits-box .tags-add-input").autocomplete(tags["traits"],{
				mustMatch: true,
				autoFill: true,
				width: 370,
				formatItem: function(row, i, max) {
					return i + "/" + max + ": \"" + row.completePath;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.name;
				}
			}).result(function(event,data,formatted){ if (typeof(data) != "undefined") $(".traits .tag_id").val(data["id"])});
		}
		else
		{
			$("#traits-box .tags-add-input").unautocomplete();
		}
	},
	
	/* tastes */
	"autocomplete_tastes_preferences": function(val)
	{
		if (val == true)
		{
			$("#tastes_preferences-box .tags-add-input").autocomplete(tags["tastes_preferences"],{
				mustMatch: true,
				autoFill: true,
				width: 370,
				formatItem: function(row, i, max) {
					return i + "/" + max + ": \"" + row.completePath;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.name;
				}
			}).result(function(event,data,formatted){ if (typeof(data) != "undefined") $(".tastes_preferences .tag_id").val(data["id"])});
		}
		else
		{
			$("#tastes_preferences-box .tags-add-input").unautocomplete();
		}
	},
	
	/* demographics */
	"autocomplete_demographic": function(val)
	{
		if (val == true)
		{
			$("#demographic-box .tags-add-input").autocomplete(tags["demographic"],{
				mustMatch: true,
				autoFill: true,
				width: 370,
				formatItem: function(row, i, max) {
					return i + "/" + max + ": \"" + row.completePath;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				},
				formatResult: function(row) {
					return row.name;
				}
			}).result(function(event,data,formatted){ if (typeof(data) != "undefined") $(".demographic .tag_id").val(data["id"])});
		}
		else
		{
			$("#demographic-box .tags-add-input").unautocomplete();
		}
	}
};

$(function() {
	if ($('#flashEvents').children('.flashEvent').length) {
		$('#flashEvents').slideDown('slow');
		$('#flashEvents')
			.children().click(function() { 
							$(this).hide('fast', function() {
								$(this).remove();
								if (!$('#flashEvents').children('.flashEvent').length) $('#flashEvents').hide('fast');
							});
						});
	}
	Imagini.bindEvents($('body'));
});

if(jQuery) (function($){

	$.fn.x = function(n){
		var result = null;
		this.each(function(){
			var o = this;
			if(n === undefined){
				var x = 0;
				if(o.offsetParent){
					while(o.offsetParent){
						x += o.offsetLeft;
						o = o.offsetParent;
					}
				}
				if(result === null){
					result = x;
				}else{
					result = Math.min(result, x);
				}
			}else{
				o.style.left = n + 'px';
			}
		});
		return result;
	};
	
	$.fn.y = function(n) {
		var result = null;
		this.each(function() {
			var o = this;
			if(n === undefined){
				var y = 0;
				if(o.offsetParent){
					while(o.offsetParent){
						y += o.offsetTop;
						o = o.offsetParent;
					}
				}
				if(result === null){
					result = y;
				}else{
					result = Math.min(result, y);
				}
			}else{
				o.style.top = n + 'px';
			}
		});
		return result;
	};
	
	$.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);