jQuery(document).ready(function($) {

	// ie6 png fixes
	if ($.browser.msie && $.browser.version.substr(0,1)<7) {
		DD_belatedPNG.fix("a.continue");
		DD_belatedPNG.fix("a.answer");
		DD_belatedPNG.fix("span.overlay");
		DD_belatedPNG.fix("a.quiz-back");
		DD_belatedPNG.fix("h2.question");
		DD_belatedPNG.fix("img.quiz-png");
		DD_belatedPNG.fix("div.indicator");
		DD_belatedPNG.fix("div#indicator-1");
		DD_belatedPNG.fix("div#indicator-2");
		DD_belatedPNG.fix("div#indicator-3");
		DD_belatedPNG.fix("div#banner");
		DD_belatedPNG.fix("div#result-content");
		DD_belatedPNG.fix("a#start-over");
	}
	
	// global vars
	var choice = [];
	var curQuestion = 1;
	var quizData;
	var inTransit = false;
	
	// get JSON data
	$.ajax({
		url: "/j/traveldeals/quiz-data.js",
		cache: false,
		dataType: "json",
		contentType: "application/json; charset=utf-8",
		success: function(data) {
			quizData = data;
			init();
		},
		error:function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status);
			alert(ajaxOptions);
			alert(thrownError);
		}
	});
	
	var init = function() {
		
		// set click and mouseover events for answers
		$("div#quiz div.answers > a.answer").live("click", function(e) {
			e.preventDefault();
			// check inTransit flag - it is set to "true" during fades between questions; prevent clicking elements during transitions
			if (!inTransit) {
				var questionNum = $(this).parents("div.questions").attr("id").split("question-");
				setClicks(e, questionNum[1]);
			}
		});

		$("div#quiz div.answers > a.answer").live("mouseenter", function(e) {
			if (!inTransit) {
				$(this).addClass("hovered");
			}
		});
		
		$("div#quiz div.answers > a.answer").live("mouseleave", function(e) {
			if (!inTransit) {
				$(this).removeClass("hovered");
			}
		});
		
		// set sub-answers on rollover for Question 2 answers
		$("div#quiz > div#question-2 > div.answers > a#flip-flops").mouseenter(function(e) {
			if (!inTransit) {
				setSubAnswer("By the water and in the sun, where no shirt and no shoes is no problem");
			}
		});
		
		$("div#quiz > div#question-2 > div.answers > a#sneakers").mouseenter(function(e) {
			if (!inTransit) {
				setSubAnswer("Ready for anything, from amusement park lines to mountain trails.");
			}
		});
		
		$("div#quiz > div#question-2 > div.answers > a#dress-shoes").mouseenter(function(e) {
			if (!inTransit) {
				setSubAnswer("Nights on the town, restaurants and maybe even a party.");
			}
		});
		
		$("div#quiz > div#question-2 > div.answers > a.answer").mouseleave(function(e) {
			setSubAnswer("");
		});
		
		// set Back button
		$("div#quiz a.quiz-back").click(function(e) {
			e.preventDefault();
			if (!inTransit) {
				// clear current question
				$("div#quiz > div#question-" + curQuestion + " > div.answers > a.answer").removeClass("selected");
				$("div#quiz div#question-" + curQuestion + " a.continue-active").addClass("continue");
				$("div#quiz div#question-" + curQuestion + " a.continue").removeClass("continue-active");
				choice[curQuestion] = null;
				
				// clear previous question
				$("div#quiz > div#question-" + (curQuestion - 1) + " > div.answers > a.answer").removeClass("selected");
				$("div#quiz div#question-" + (curQuestion - 1) + " a.continue-active").addClass("continue");
				$("div#quiz div#question-" + (curQuestion - 1) + " a.continue").removeClass("continue-active");
				choice[curQuestion - 1] = null;
				transition(-1);
			}
		});

		// set Continue button - Question 1
		$("div#quiz > div#question-1 > a.continue").click(function(e) {
			e.preventDefault();
			if (!inTransit) {
				if (choice[1] != null) {
					transition(1);
				}
			}
		});

		// set Continue button - Question 2
		$("div#quiz > div#question-2 > a.continue").click(function(e) {
			e.preventDefault();
			if (choice[2] != null && !inTransit) {
				var first = quizData[choice[1]];
				var question = first[choice[2]].question;
				var qImg = first[choice[2]].qImg;
				var answers = first[choice[2]].answers;
				
				// populate question 3
				$("div#quiz > div#question-3 > h2.question").html("<img src='" + qImg + "' alt='" + question + "' title='' class='quiz-png' />");
				
				// populate question 3 answers
				var ansWidth = 0;
				$("div#quiz > div#question-3 > div.answers").html("");
				$.each(answers, function(key, value) {
					var ansBg = "url(/i/quiz/icons/icon-q3-" + value["icon"] + ".png) no-repeat top left";
					var ansId = key.replace(/\s/g, "_");
					var ans = $("<a id='" + ansId + "' class='answer' href='#'><img src='" + answers[key]["aImg"] + "' alt='" + key + "' title='' width='115' height='36' class='quiz-png' /><span class='overlay'></span></a>");
					$("div#quiz > div#question-3 > div.answers").append(ans);
					$("div#quiz > div#question-3 > div.answers > a#" + ansId).css("background", ansBg);
					
					ansWidth += 145;
				});
				$("div#quiz > div#question-3 > div.answers").css("width",ansWidth + "px");
				transition(1);
			}
			
			//png fix ISN'T WORKING for question 3 icons.
			if ($.browser.msie && $.browser.version.substr(0,1)<7) {
				DD_belatedPNG.fix("img.quiz-png"); // not working
				DD_belatedPNG.fix("a.answer");
			}
			
		});

		// preload results once Question 3 selection is made
		$("div#quiz > div#question-3 > div.answers > a.answer").live("click",function(e) {
			if (!inTransit) {
				var first = quizData[choice[1]];
				var answers = first[choice[2]].answers;
				var result = answers[choice[3].replace(/_/g, " ")];
				loadResults(result);
			}
		});

		// set Continue button - Question 3
		$("div#quiz > div#question-3 > a.continue-active").live("click", function(e) {
			e.preventDefault();
			if (choice[3] != null && !inTransit) {
				$("div#quiz > div.indicator").fadeOut("slow");
				inTransit = true;
				$("div#question-3").fadeOut("slow", function() {
					$("div#quiz div#result").fadeIn("slow", function() {						
						inTransit = false;
					});
				});
			}
		});

		// set Start Over button
		$("div#quiz > div#result > a#start-over").live("click", function(e) {
			e.preventDefault();
			if (!inTransit) {
				for (i=1; i<=3; i++) {
					choice[i] = null;
					if (i > 1) {
						$("div#quiz div#indicator-" + i).css("background","url(/i/quiz/indicators/indicator-" + i + ".png)");
					} else {
						$("div#quiz div#indicator-" + i).css("background","url(/i/quiz/indicators/indicator-" + i + "-on.png)");
					}
				}
				$("div#quiz > div.questions > div.answers > a.selected").removeClass("selected");
				$("div#quiz div#result").fadeOut("slow", function() {
					$("div#question-1").fadeIn("slow");
					inTransit = true;
					$("div#quiz > div.indicator").fadeIn("slow", function() {						
						inTransit = false;
					});
				});
				curQuestion = 1;
			}
		});
	}
	
	var setClicks = function(e, questionNum) {
		// get the parent anchor node
		if ($(e.target).is("span")) {
			var selectedAnswer = $(e.target).parent("a.answer");
		} else {
			var selectedAnswer = e.target;
		}
		
		// get answer id and set to choice[] array
		var id = $(selectedAnswer).attr("id");
		choice[questionNum] = id;
		
		// set answer's selected state
		selectAnswer(selectedAnswer);
		
		// make continue button active
		$("div#quiz div#question-" + questionNum + " a.continue").addClass("continue-active");
		$("div#quiz div#question-" + questionNum + " a.continue").removeClass("continue");
		
		// ie6 png fix
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			DD_belatedPNG.fix("a.continue-active");
		}
	}
	
	var selectAnswer = function(item) {
		$(item).addClass("selected");
		
		// remove any other selected class settings
		$.each($(item).siblings("a"), function(index, value) {
			$(this).removeClass("selected");
		});
	};
	
	var setSubAnswer = function(text) {
		$("div#quiz > div#question-2 > div.sub-answers").html(text);
	}
	
	var transition = function(dir) {
		// dir = 1 to move forward in question flow, dir = -1 to move backwards
		var from = "div#question-" + curQuestion;
		curQuestion += dir;
		var to = "div#question-" + (curQuestion);
		
		// set inTransit flag, prevent anchor elements from being active
		inTransit = true;
		$(from).fadeOut("fast", function() {
			$(to).fadeIn("fast", function() {						
				inTransit = false;
			});
		});
		
		// set indicators
		indicators();
	};

	var indicators = function() {
		for (i=1; i<=3; i++) {
			var target = "div#quiz div#indicator-" + i;
			if (i < curQuestion) {
				// set indicator icon to the choice made for previous questions
				var url = "/i/quiz/indicators/indicator-" + i + "-" + choice[i] + ".png";
			}
			if (i == curQuestion) {
				// set indicator on-state
				var url = "/i/quiz/indicators/indicator-" + i + "-on.png";
			}
			if (i > curQuestion) {
				// set indicator default off state
				var url = "/i/quiz/indicators/indicator-" + i + ".png";
			}
			loadBGImage(target, url);
		}
	};

	var loadResults = function(resultData) {
		// make sure results are cleared:
		$("div#quiz div#result div#result-content").html("");
		$("div#quiz div#result div#featured-hotel div#hotel-content").html("");
		if ($("div#quiz div#result div#other-destinations").length > 0) {
			$("div#quiz div#result div#other-destinations").remove();
		}
		
		// append results body content
		loadBGImage("div#result", resultData["bgImg"]);
		$("div#result").append("<a id=\"hero-link\" href=\"" +resultData["seeAllUrl"] + "\">&nbsp;</a>");
		$("div#quiz div#result div#result-content").append("<h2><a href=\"" + resultData["seeAllUrl"] + "\">" + resultData["result"] + "</a></h2>");
		
		//var shareContent = "<div id='share' class='clearfix'>";
		//shareContent += "<a href='" + resultData["share"]["twitter"] + "' id='btn-twitter'>Twitter</a>";
		//shareContent += "<a href='" + resultData["share"]["facebook"] + "' id='btn-facebook'>Facebook</a>";
		//shareContent += "<a href='mailto:' id='btn-email'>Email</a>";
		//shareContent += "<a href='#' id='btn-print'>Print</a>";
		//shareContent += "</div>";
		//$("div#quiz div#result div#result-content").append(shareContent);
		//$("div#quiz div#result div#result-content div#share a#btn-print").click(function(e) {
			//e.preventDefault();
			//$("div#quiz").printElement();
		//});
		$("div#quiz div#result div#result-content").append("<p>" + resultData["desc"] + "</p>");
		$("div#quiz div#result div#result-content").append("<a href='" + resultData["seeAllUrl"] + "' class='see-all'>" + resultData["seeAll"] + "</a>");
		
		// append other destinations
		var otherDest = "<div id='other-destinations'>Other destinations you may like: <a href='" + resultData["alt1"]["url"] + "'>" + resultData["alt1"]["dest"] + "</a>";
		if (resultData["alt2"]) {
			otherDest += ", <a href='" + resultData["alt2"]["url"] + "'>" + resultData["alt2"]["dest"] + "</a>";
		}
		otherDest += "</div>";
		$("div#quiz div#result").append(otherDest);
		
		// append photo credit
		$("div#quiz div#result div#result-content").append("<div id='photo-credit'>" + resultData["credit"] + "</div>");
		
		// append featured hotel content
		$("div#quiz div#result div#featured-hotel div#hotel-content").append("<h3><a href=\"" + resultData["hotel"]["more"] + "\">" + resultData["hotel"]["title"] + "</a></h3>");
		$("div#quiz div#result div#featured-hotel div#hotel-content").append("<a href=\"" + resultData["hotel"]["more"] + "\"><img src='" + resultData["hotel"]["img"] + "' alt='" + resultData["hotel"]["title"] + "' title='' /></a>");
		$("div#quiz div#result div#featured-hotel div#hotel-content").append("<p>" + resultData["hotel"]["desc"] + "</p>");
		$("div#quiz div#result div#featured-hotel div#hotel-content").append("<a href='" + resultData["hotel"]["more"] + "' class='more'>" + resultData["hotel"]["moretext"] + "</a>");
		$("div#quiz div#result div#featured-hotel div#hotel-content").append("<a href='" + resultData["hotel"]["letsgo"] + "' class='lets-go-blue'>Let's Go</a>");

		// append results indicators
		$("div#quiz div#result div#result-content").append("<div id='result-indicators'></div>");
		for (i=1; i<=3; i++) {
			if (i != 3) {
				var indicatorBG = "url(/i/quiz/indicators/indicator-" + i + "-" + choice[i] + ".png)";
			} else {
				var indicatorBG = "url(/i/quiz/indicators/indicator-" + i + "-" + resultData["icon"] + ".png)";
			}
			$("div#quiz div#result div#result-content div#result-indicators").append("<div id='result-indicator-" + i + "' class='result-indicator'></div>")
			$("div#quiz div#result div#result-content div#result-indicators div#result-indicator-" + i).css("background",indicatorBG + " no-repeat");
		}
		if ($.browser.msie && $.browser.version.substr(0,1)<7) {
			DD_belatedPNG.fix("div#share a");
			DD_belatedPNG.fix("div.result-indicator");
			DD_belatedPNG.fix("a.see-all");
			DD_belatedPNG.fix("div#other-destinations");
		}
		
	};
	
	var loadBGImage = function(target, url) {
		// loads background image first before setting to the CSS of a node; prevents blinking effect
		$("<img />").attr("src", url).load(function() {			
			$(target).css("background", "url(" + url + ") no-repeat 0px 0px");
		});
	};

});
