﻿var isValidating = false;
var modelString = "";
var model;
var redirectUrl;
var videoPlayer;
var isEligible = false;
var isIE = false;
var isIE7 = false;
var isIE8 = false;
var brandName = "utherverse";
var headers = ["/Controls/Login/HeaderText_SelectGender.png", "/Controls/Login/HeaderText_Selectethnicity.png", "/Controls/Login/HeaderText_SelectOutfit.png"];
var date_arr = {};
var days_arr = {};

$(document).ready(function () {
	// Init recaptcha
	if ($.browser.msie) {
		Recaptcha.create("6LfFPr0SAAAAAJco54iuXMKpgiP72eSsgq4U7AdT", 'recaptcha', { theme: "white" });
	} else {
		Recaptcha.create("6LfFPr0SAAAAAJco54iuXMKpgiP72eSsgq4U7AdT", 'recaptcha', { theme: "white", callback: Recaptcha.focus_response_field });
	}

	isIE = $.browser.msie;
	isIE7 = $.browser.msie && $.browser.version.substr(0, 1) <= 7;
	isIE8 = $.browser.msie && $.browser.version.substr(0, 1) == 8;
	//showSignUp();

	// Form close events
	$("#closeTabs").click(function () { hideSignUp(false); });

	// Loading animation
	$('#loader').hide().ajaxStart(function () {
		$(this).show();
	}).ajaxStop(function () {
		$(this).hide();
	});

	$(".zoom").live("click", function () { return false; });

	// Change tabs
	$(".backButton").button().click(function () {
		var previousStepIndex = $("#tabs").tabs('option', 'selected') - 1;
		if (previousStepIndex >= 0) {
			$("#tabs").tabs('select', previousStepIndex);
		} else {
			if ($("#outfitContainer").is(':visible')) {
				$('#headerImage').attr("src", headers[1]);
				$("#outfitContainer").fadeOut(0, function () {
					$("#outfitRace").fadeIn("normal");
				});
			} else if ($("#outfitRace").is(':visible')) {
				$('#headerImage').attr("src", headers[0]);
				$(this).hide();
				$("#outfitRace").fadeOut(0, function () {
					$("#outfitSex").fadeIn("normal");
				});
			} else {
				$('#headerImage').attr("src", headers[0]);
				$(this).hide();
				$("#outfitRace").add("#outfitContainer").fadeOut(0, function () {
					$("#outfitSex").fadeIn("normal");
				});
			}
			$("#tabs").center();
		}
	});

	$(".nextButton").button().click(function () {
		var nextStepIndex = $("#tabs").tabs('option', 'selected') + 1;
		$("#tabs").tabs('enable', nextStepIndex);
		$("#tabs").tabs('select', nextStepIndex);
		return false;
	});

	$(".skipButton").button().click(function () {
		var nextStepIndex = $("#tabs").tabs('option', 'selected') + 1;
		$("#tabs").data("validated", true);
		$("#tabs").tabs('enable', nextStepIndex);
		$("#tabs").tabs('select', nextStepIndex);
		$(".error").remove();
		return false;
	});

	/*
	//Init Datepicker
	$('#birthDate').datepicker({
	changeMonth: true,
	changeYear: true,
	altFormat: 'm/d/yy',
	yearRange: '-100:-0'

	});
	*/
	initDOB();

	$('#agreeVerification').bind('change', function () {
		var $submit = $('#submit');
		if ($(this).is(':checked')) {
			$submit.button("option", "disabled", false);
		} else {
			$submit.button("option", "disabled", true);
		}
	});
	$('#submit').attr('disabled', 'disabled');

	$('#ageVerification').bind('change', function () {
		if ($(this).is(':checked')) {
			$(this).attr('checked', false);
			$('#datepicker').show();
		}
	});

	// Submit form
	$(".submitButton").button().click(function () {
		var currentStepIndex = $("#tabs").tabs('option', 'selected');
		validate(currentStepIndex, currentStepIndex + 1);
		return false;
	});

	$(".proceedButton").button().click(function () {
		var currentStepIndex = $("#tabs").tabs('option', 'selected');
		validate(currentStepIndex, currentStepIndex + 1);
		return false;
	});

	// Outfits
	$("#outfitContainer .avatars").add("#outfitRace .avatars").each(function () {
		$(this).data("link", $(this).attr("alt"));
		$(this).removeAttr("alt");
	});


	var gender, race;

	// Sub 1
	$("#outfitSex .avatarWrapper").live("click", function () {
		$(".backButton").show();
		if (this.parentNode.className.indexOf("genderMale") != -1) {
			gender = 1;
		}
		else if (this.parentNode.className.indexOf("genderFemale") != -1) {
			gender = 2;
		}

		$("#outfitRace .avatars").each(function () {
			var txt = $(this).data("link");
			$(this).attr("src", txt.replace("{gender}", gender == 1 ? "male" : "female"));
			$(this).attr("alt", (gender == 1 ? "Male" : "Female") + " avatar");
			$(this).next().find('a.zoom').attr('href', getUnresized($(this).attr('src')));
		});

		$('#headerImage').attr("src", headers[1]);
		$("#outfitSex").fadeOut(0, function () {
			$("#outfitRace").fadeIn("normal");
			$("#tabs").center();
		});
	});

	// Sub 2
	$("#outfitRace .avatarWrapper").live("click", function () {
		race = $("#outfitRace .avatarWrapper").index(this);
		$("#outfitContainer .avatars").each(function () {
			var txt = $(this).data("link");
			var imageIndex = parseInt(txt.match(/{index:(\d+)}/)[1]);
			var index = 6 * race + imageIndex;
			$(this).attr("src", txt.replace("{gender}", gender == 1 ? "male" : "female").replace(/{index:(\d+)}/g, index));
			$(this).attr("alt", (gender == 1 ? "Male" : "Female") + " avatar");
			$(this).next().find('a.zoom').attr('href', getUnresized($(this).attr('src')));

			$(this).parent().data("index", index);
		});

		$('#headerImage').attr("src", headers[2]);
		$("#outfitRace").fadeOut(0, function () {
			$("#outfitContainer").fadeIn("normal");
			$("#tabs").center();
		});
	});

	// Sub 3
	$("#outfitContainer .avatarWrapper").live("click", function () {
		model = { gender: gender, index: $(this).data("index") };
		var name = (gender == 1 ? "male" : "female") + $(this).data("index") + ".png";
		var img = '<img src="/Controls/Login/images/' + name + '" alt="Model" class="avatars"/>';
		$(".model").empty().append(img);

		$('#headerImage').attr("src", headers[0]);
		var nextStepIndex = $("#tabs").tabs('option', 'selected') + 1;
		$("#tabs").tabs('enable', nextStepIndex);
		$("#tabs").tabs('select', nextStepIndex);

		// Prepare the first step
		$("#outfitContainer").hide();
		$("#outfitSex").show();
		$(".backButton").first().hide();
		return false;
	});

	$(".avatars").each(function () { $(this).fancyBorder(); });

	$("#outfitSex .avatars").each(function () {
		$(this).next().find('a.zoom').attr('href', getUnresized($(this).attr('src')));
	});

	$("#tabs ul > li").each(function () {
		$(this).addClass('ui-corner-bottom');
	});

	$('.input > input').focus(function () {
		$(this).parent().addClass("focused");
	}).blur(function () {
		$(this).parent().removeClass("focused")
	});

	// FU Chrome and Safari
	if ($.browser.webkit) {
		$('input[name="password"]').attr('autocomplete', 'off');
	}

	// 
	if (SIGNUP.mutePlayer !== undefined && SIGNUP.mutePlayer === true) 
		videoPlayer = getFlashMovie(SIGNUP.playerName);
	if (SIGNUP.returnUrl !== undefined && SIGNUP.returnUrl.length > 0)
		redirectUrl = SIGNUP.returnUrl;
	if (SIGNUP.isAutostart !== undefined && SIGNUP.isAutostart === true)
		showSignUp();
});


/********************************************************************************************************************
************************************************HELPER FUNCTIONS AND PLUGINS*****************************************
********************************************************************************************************************/

$.fn.center = function () {
	this.css("position", "absolute");
	this.css("top", "10%");
	this.css("left", "50%");
	this.animate({ "margin-left": -((this.width()) / 2) + "px" }, { "duration": "fast" });
	return this;
}

/********************************************************************************************************************
************************************************COMBOBOX PLUGIN******************************************************
********************************************************************************************************************/
$.fn.imageset = function (gender, text) {
	var el = $(this);
	var prev = $('<a/>').addClass('arrow').addClass('previous').click(function () {
		clicked(true);
	});
	var next = $('<a/>').addClass('arrow').addClass('next').click(function () {
		clicked(false);
	});
	var currentImage = $('<img/>')
						.attr('src', el.val().replace("{gender}", gender))
						.attr('alt', $('option:selected', el).text())
						.addClass('avatars');
	var header = $('<div/>').addClass('ui-imageset-title').text(text);
	var element = $('<div/>').addClass('ui-imageset').addClass('ui-imageset-single').append(header).append(currentImage).append(next).prepend(prev);
	el.hide();
	el.after(element);

	function clicked(back) {
		var val = el.selectedIndex();
		var len = $('option', el).length;
		if (back) {
			if (val == 0)
				val = len - 1;
			else
				val--;
		} else {
			if (val == (len - 1))
				val = 0;
			else
				val++;
		}

		el.selectIndex(val);
		element.find('.avatars:first').hide(0, function () {
			$(this).attr('src', el.val().replace("{gender}", gender))
			$(this).attr('alt', $('option:selected', el).text())
			$(this).show('slide', { direction: back ? 'right' : 'left', queue: false }, 'fast');
		});
		el.trigger('change')
	}
	return element;
}

$.fn.selectedIndex = function () {
	var el = $(this);
	var val = 0;
	$('option', el).each(function () {
		if ($(this).attr("selected")) {
			return false;
		}
		val++;
	});
	return val;
}

$.fn.selectIndex = function (val) {
	var el = $(this);
	$('option:selected', el).removeAttr('selected');
	$($('option', el)[val]).attr('selected', 'selected');
}

/********************************************************************************************************************
************************************************FANCY BORDER PLUGIN**************************************************
*****************************************Inspired by 'insetBorder' plugin********************************************
********************************************************************************************************************/
$.fn.fancyBorder = function () {
	var el = $(this);
	var wrapper = $("<div />", {
		"css": {
			"top": 0,
			"left": 0,
			"height": el.height(),
			"width": el.width()
		},
		"mouseenter": function () {
			el.next().animate({
				"top": 0,
				"left": 0,
				"height": el.height() - 10,
				"width": el.width() - 10,
				"opacity": "1"
			}, {
				"duration": 250,
				"queue": false
			});
			if (isIE8) {
				el.next().find("a").animate({ "opacity": 1 }, { "duration": 250, "queue": false });
			}
		},
		"mouseleave": function () {
			el.next().animate({
				"height": el.height(),
				"width": el.width(),
				"top": "-5px",
				"left": "-5px",
				"opacity": "0"
			}, {
				"duration": 250,
				"queue": false
			});
			if (isIE8) {
				el.next().find("a").animate({ "opacity": 0 }, { "duration": 250, "queue": false });
			}
		}
	}).addClass('avatarWrapper');
	var after = $("<div/>", {
		"css": {
			"height": el.height(),
			"width": el.width(),
			"top": "-5px",
			"left": "-5px",
			"border": "5px solid #000",
			"position": "absolute",
			"opacity": "0"
		}
	}).addClass("ui-corner-all")
	  .addClass("fancyBorder").append($('<a href="#" class="single_image zoom"></a>').fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 200, 'speedOut': 100 }));
	if (isIE8) {
		after.find('a').fadeTo(0, 0);
	}
	el.wrap(wrapper).after(after);
}

function validate(index, nextIndex) {
	// add some javascript validation here
	//...
	//
	var validatorObject = new Object();
	switch (index) {
		case 0:
			// UtherCloth validation, probably is not needed at all
			validatorObject = {
				gender: model.gender,
				index: model.index
			};
			break;
		case 1:
			validatorObject = {
				screenName: $("#screenName").val(),
				password: $("#password").val(),
				email: $("#email").val()
			};
			break;
		case 2:
			validatorObject = {
				challenge: Recaptcha.get_challenge(),
				response: Recaptcha.get_response(),
				/*ageVerification: $("#ageVerification").is(':checked'),*/
				birthDate: getBirthDate()
			};
			break;
		case 3:
			proceed();
			//loadThankYou();
		default:
			return;
	}

	var str = JSON.stringify({ step: index, nextStep: nextIndex, fields: validatorObject });

	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: "/AjaxSignUp.aspx/validate",
		data: str,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			for (var i = index + 1; i < $("#tabs").tabs('length'); i++)
				$("#tabs").tabs('disable', i);
		},
		success: ajaxCallback,
		dataType: "json"
	});
}

// AJAX Response from the server
function ajaxCallback(data, textStatus, XMLHttpRequest) {
	var response = data.d;
	var tabs = $("#tabs");

	if (response.success) {
		for (var i = 0; i < response.messages.length; i++) {
			var message = response.messages[i];
			if (message.target == 'signupusername') {
				$("#importcontacts").attr('src', $("#importcontacts").attr('src') + "&signupusername=" + message.message);
				break;
			}
			//if (message.target == 'isEligibleforTrial') {
			//	isEligible = message.message;
				// removed as per NicoleA, Dec 15, 2010 MikeB
				//if (isEligible) {
					//$('#gratzImage').attr('src', '/images/JoinThankYou_VIP.png'); 
				//}
			//}
			if (response.banned) {
				$('#gratzImage').attr('src', '/images/banned.png');
				$('.proceedButton').attr('disabled', 'disabled').hide();
			}
			else if (SIGNUP.isMac) {
				$('#gratzImage').attr('src', '/sites/' + SIGNUP.brandName + '/signup/styles/congratsMac.png');
			} else if (SIGNUP.isWow) {
				$('#gratzImage').attr('src', '/images/congratsWow.png');
            } else if (SIGNUP.isAEVC) {
                $('#gratzImage').attr('src', '/conventions/aevc/image/congratsAEVC.png');
            }

		}
	}

	tabs.data("validated", response.ok);
	if (!response.ok) {
		// registration step
		if (response.currentIndex == 2) {
			if (response.showcaptcha) {
				$('#recaptcha').show();
				Recaptcha.reload();
			} else {
				$('#recaptcha').slideUp();
			}
		}

		var index;

		if (!response.sessionAlive) {
			index = 0;
			tabs.tabs('select', index);
		}
		else
			index = response.currentIndex;

		for (var i = index + 1; i < tabs.tabs('length'); i++)
			tabs.tabs('disable', i);

		for (var i = 0; i < response.messages.length; i++) {
			var message = response.messages[i];

			var parent = $("#" + message.target).parent();
			var errorMsgElement = $("<div></div>").html(message.message).addClass("error");

			$(errorMsgElement).ajaxStart(function () {
				$(this).remove();
			});

			$(parent).after(errorMsgElement);
			$(errorMsgElement).slideDown('fast', function () {
				// Focus on the first error
				if (i == 0)
					$("#" + message.target).focus();
			});
		}
	}
	else {
		var nextIndex = response.nextIndex;
		tabs.tabs('enable', nextIndex);
		tabs.tabs('select', nextIndex);
	}
}

function createError(message) {
	var StyledError = "<div class=\"ui-state-error ui-corner-all\" style=\"margin: 0px auto 5px auto; width: 275px;\">";
	StyledError += "<p><span class=\"ui-icon ui-icon-alert\" style=\"float: left; margin-right: .3em;\">";
	StyledError += "</span><strong>Alert:</strong>";
	StyledError += message;
	StyledError += "</p></div>";

	return StyledError;
}

function getJSON(data) {
	modelString = data;
	$("#tabs").tabs('enable', 1);
	$("#tabs").tabs('select', 1);
}

function loadThankYou() {
	$('#importcontacts').attr('src', '/Inline_ThankYou.aspx');
}

function proceed() {
	// start download
	window.location.replace(getDownload());
	// redirect if provided
	if (redirectUrl !== undefined)
		addMessage("<h3 style='text-align:center'>Congratulations!</h3>" + 
						"<p>Your account has been created.</p><p>3D client download should start automatically.</p>" +
						"<div class='notificationcontent ui-corner-all'><a href='/GetDownload.aspx?did=2'>RESTART DOWNLOAD</a>" +
						"<br/>OR<br/><a href='" + redirectUrl + "'>CONTINUE</a></div>");
	hideSignUp(true);
}

function getDownload() {
	var did = 1;
	var domain = document.domain;

	if (SIGNUP.isMac) {
		if (domain.indexOf("redlightcenter") != -1)
			return "http://cdn.redlightcenter.com/SetupFiles/UtherverseRLC.dmg";
		else
			return "http://cdn.utherverse.com/SetupFiles/Utherverse.dmg";
	} else {
	    if (domain.indexOf("redlightcenter") != -1)
	        did = 2;
	    else if (domain.indexOf("3dtunes") != -1)
	        did = 48472;
	    else if (domain.indexOf("ivegas") != -1)
	        did = 44407;
	    else if (domain.indexOf("rude") != -1)
	        did = 4;
	    else if (domain.indexOf("afcvirtual") != -1)
	        did = 38147;
	    else if (SIGNUP.isAEVC)
	        did = 2;

		return "/GetDownload.aspx?did=" + did;
	}
}

function resizeIframe(newWidth, newHeight, text) {
	$('#importcontacts').animate({
		"width": parseInt(newWidth) + 30 + 'px',
		"height": parseInt(newHeight) + 30 + 'px'
	}, {
		"duration": 250
	});

	$('.proceedButton:first').css("padding", "1em 2em");
	$('.proceedButton:first').val(text);
	$('.proceedButton:first').click(function () {
		proceed();
	});
}

// Show form
function showSignUp(url) {
	if (videoPlayer !== undefined && typeof videoPlayer.muteVideo == 'function') {
		videoPlayer.muteVideo();
	}

	if (url !== undefined)
		redirectUrl = url;	

	if (SIGNUP.isLgbt) {
		$('.lgbt').show();
	}
	// Temp fix for IE7:
	//if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
	//    window.location.replace("/signup.aspx");


	// init tabs
	$('#tabs').tabs({
		disabled: [1, 2, 3],
		//fx: { opacity: 'toggle' },
		show: function (event, ui) {
			$(this).center();
			// FU Firefox (http://dev.jqueryui.com/ticket/4549)
			$(".ui-tabs-nav:first > li").removeClass("ui-state-focus");
			$("#tabs input:visible:first").focus();

			// Last step, hide active tabs
			if ($("#tabs").tabs('option', 'selected') == 3) {
				$(this).tabs('disable', 0);
				$(this).tabs('disable', 1);
				$(this).tabs('disable', 2);
			}
		},
		select: function (event, ui) {
			var currentIndex = $(this).tabs('option', 'selected');
			var selectedIndex = ui.index;

			if (selectedIndex < currentIndex || $(this).data("validated")) {
				$(this).data("validated", false);
				// IE7 bug fix (buttons from the previous form don't get hidden)
				if (!($.browser.msie && $.browser.version.substr(0, 1) <= 7)) {
					$(this).hide();
					$(this).fadeIn('normal');
				}
				return true;
			}
			// Invalidate current tab in case it was validated before and then modified
			$(this).data("validated", false);
			validate(currentIndex, selectedIndex);
			return false;
		}
	}).addClass('verticalTabs ui-helper-clearfix').center();

	var $mask = $('<div></div>').attr('id', 'signUpMask').insertBefore('#tabs');
	var maskHeight = $(document).height();
	var maskWidth = $(document).width();
	$mask.css({ 'width': maskWidth, 'height': maskHeight });

	$mask.fadeTo("fuIE8", 0.7, function () {
		$("#tabs").show("fast");
	});
}

function hideSignUp(isSuccess) {
	$("#tabs").fadeOut("please");
	$("#signUpMask").fadeOut("normal", function () {
		$("#signUpMask").remove();
		if (isSuccess && SIGNUP.isMac) {
			if (document.domain.indexOf("redlightcenter") != -1)
				window.location.replace("/mac/specs/");
		}

		// removed as per NicoleA, Dec 15 2010 by MikeB
		//if (isSuccess) {
		//	if (isIE) {
		//		$('#mainContent').hide();
		//	}
		//	$('#disclaimerBlock').hide();
		//	$('#mainContent').fadeOut("fast", function () {
		//		$(isEligible ? '.mainDivVIP' : '.mainDiv').fadeIn("slow");
		//	});
		//
		//	//addMessage("Congratulations!<br/>Your account has been created.<br/>3D client download should start automatically.<div class='notificationcontent'><a href='/GetDownload.aspx?did=2'>RESTART DOWNLOAD</a><br/>OR<br/><a href='/net/home.aspx'>CONTINUE</a></div>");
		//}		
	});

	if (videoPlayer !== undefined && typeof videoPlayer.unMuteVideo == 'function') {
		videoPlayer.unMuteVideo();
	}
}

// Success message and redirect
function addMessage(text) {
	var notification = $('<div/>').addClass('notification ui-corner-all').html(text)
	$('body').append(notification);
	//$(notification).fadeTo("slow", 0.9);
	$(notification).show("slide", { direction: "up" }, 1000);
	setTimeout(
		function () {
			$(notification).hide("slide", { direction: "up" }, 1000, function () {
				$(this).remove();
				window.location.replace(redirectUrl);
				//window.location.replace("/welcometour/");
			});
		},
		15000
	);
}

function getUnresized(source) {
	var addString = "unresized/";
	var index = source.lastIndexOf("/") + 1;
	return source.substr(0, index) + addString + source.substr(index);
}

function initDOB() {
	date_arr = [
		{ month:"January", maxDays: 31 },
		{ month:"February", maxDays: 28 },
		{ month:"March", maxDays: 31 },
		{ month:"April", maxDays: 30 },
		{ month:"May", maxDays: 31 },
		{ month:"June", maxDays: 30 },
		{ month:"July", maxDays: 31 },
		{ month:"August", maxDays: 30 },
		{ month:"September", maxDays: 30 },
		{ month:"October", maxDays: 31 },
		{ month:"November", maxDays: 30 },
		{ month: "December", maxDays: 31 }
	];

	var $monthSelect = $('#monthSelect');
	var $yearSelect = $('#yearSelect');
	var $daySelect = $('#daySelect');

	for (i = 0; i < 12; i++)
		$monthSelect.append('<option value="' + (i + 1) + '">' + date_arr[i]["month"] + '</option>');

	$monthSelect.bind('change', function () {
		// clear previous month results
		$daySelect.find("option").not($daySelect.find("option:first")).remove();

		var selectedMonth = $monthSelect.val();
		if (selectedMonth > 0) {
			var maxDays = date_arr[selectedMonth - 1].maxDays;
			if (maxDays === 28) {
				var year = $yearSelect.val();
				if (isLeapYear(year))
					maxDays++;
			}

			for (i = 1; i <= maxDays; i++) {
				$daySelect.append('<option value="' + i + '">' + i + '</option>');
			}
		}
	});

	var currentYear = new Date().getFullYear();
	for(i = 100; i >= 0; i--)
		$yearSelect.append('<option value="' + (currentYear - i) + '">' + (currentYear - i) + '</option>');

	$yearSelect.bind('change', function () {
		var year = $yearSelect.val();
		var month = $monthSelect.val();
		var maxDays = date_arr[month - 1].maxDays;

		if (isLeapYear(year) && maxDays === 28) {
			if ($daySelect.find('option[value="29"]').length === 0) {
				$daySelect.append('<option value="29">29</option>')
			}
		} else if (!isLeapYear(year) && maxDays === 28) {
			$daySelect.find('option[value="29"]').remove();
		}
	});
}

function isLeapYear(year) {
	return (year % 400 == 0 || year % 4 == 0);
}

function getBirthDate() {
	var month = $('#monthSelect').val();
	var year = $('#yearSelect').val();
	var day = $('#daySelect').val();

	return month + "/" + day + "/" + year;
}

function getFlashMovie(movieName) 
{
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}
