﻿/// <reference path="intellisense/jquery.intellisense.js" />
/// <reference path="intellisense/jquery.ajaxdotnet.intellisense.js" />

function buildLoginForm()
{
	//load form through AJAX
	$("#overlay").load("/membership/log-in.aspx #dialogHolder",null, function(responseText, textStatus, XMLHttpRequest){
		//prepare validation
		buildLoginValidator();
	});
}

function buildFPForm()
{
	//load form through AJAX
	$("#overlay").load("/membership/forgot-password.aspx #dialogHolder" ,null, function(responseText, textStatus, XMLHttpRequest){
		//prepare validation
		buildFPValidator();
	});
}

function buildRegForm()
{
	//load reg form through AJAX
	$("#overlay").load("/membership/register.aspx #dialogHolder",null, function(responseText, textStatus, XMLHttpRequest){
		//prepare validation
		buildRegValidator();

		//Form Field preparation
		$(".row span").css("display", "none");
		$(".row span:first-child").css("display", "block");
		$(".radio label:first-child").css("display", "block");
				
		$("#linkedDates").datepicker({ 
			minDate: new Date(1900, 1 - 1, 1), 
			maxDate: new Date(2008, 12 - 1, 31), 
			beforeShow: readLinked, 
			onSelect: updateLinked, 
			showOn: ""
		});
		$("#selectMonth, #selectYear").change(checkLinkedDays);
		$(".date select").val(""); //Reset to default value	
	});
}
function buildUpdateForm()
{
	//load reg form through AJAX
	$("#overlay").load("/membership/update-profile.aspx #dialogHolder",null, function(responseText, textStatus, XMLHttpRequest){
		//prepare validation
		buildUpdateValidator();
		
		//populate form
		beginPopulateCall($("#memberEmail").val());

		//Form Field preparation
		$(".row span").css("display", "none");
		$(".row span:first-child").css("display", "block");
		$(".radio label:first-child").css("display", "block");
				
		$("#linkedDates").datepicker({ 
			minDate: new Date(1900, 1 - 1, 1), 
			maxDate: new Date(2008, 12 - 1, 31), 
			beforeShow: readLinked, 
			onSelect: updateLinked, 
			showOn: ""
		});
		$("#selectMonth, #selectYear").change(checkLinkedDays);
		$(".date select").val(""); //Reset to default value	
	});
}

function buildLoginValidator()
{
	$("#loginForm").validate({
		onfocusout:false,
		onkeyup:false,
		onsubmit:false,
		errorclass: "error",
		errorElement: "span",
		errorLabelContainer:"#summary",
		wrapper:"li",
		showErrors: function(errorMap, errorList){
				$("#summaryBlock").show();
				this.defaultShowErrors();
		},
		messages:{
			email: $("#emailMessage").val(),
			password: $("#passwordMessage").val()
		}
	});
}

function buildFPValidator()
{
	$("#loginForm").validate({
		onfocusout:false,
		onkeyup:false,
		onsubmit:false,
		errorclass: "error",
		errorElement: "span",
		errorLabelContainer:"#summary",
		wrapper:"li",
		showErrors: function(errorMap, errorList){
				$("#summaryBlock").show();
				this.defaultShowErrors();
		},
		messages:{
			email: $("#emailMessage").val()
		}
	});
}

function buildRegValidator() {
	$("#registrationForm").validate({
		onfocusout:true,
		onkeyup:true,
		onsubmit:false,
		errorclass: "error",
		errorElement: "span",
		errorLabelContainer:"#summary",
		wrapper:"li",
		showErrors: function(errorMap, errorList){
				$("#summaryBlock").show();
				this.defaultShowErrors();
		},
		rules: {
			confirmEmail: {
				equalTo: "#m_email"
			},
			confirmPassword: {
				equalTo: "#m_password"
			}
		},
		messages:{
			firstName: $("#firstNameMessage").val(),
			lastName: $("#lastNameMessage").val(),
			email: $("#emailMessage").val(),
			confirmEmail: $("#confirmEmailMessage").val(),
			password: $("#passwordMessage").val(),
			confirmPassword: $("#confirmPasswordMessage").val(),
			address: $("#addressMessage").val(),
			city: $("#cityMessage").val(),
			zip: $("#zipMessage").val(),
			country: $("#countryMessage").val(),
			tAndC: $("#tAndCMessage").val(),
			privacy: $("#privacyMessage").val()
		}
	});
}

function buildUpdateValidator()
{
	$("#updateForm").validate({
		onfocusout:false,
		onkeyup:false,
		onsubmit:false,
		errorclass: "error",
		errorElement: "span",
		errorLabelContainer:"#summary",
		wrapper:"li",
		showErrors: function(errorMap, errorList){
				$("#summaryBlock").show();
				this.defaultShowErrors();
		},
		rules: {
			confirmEmail: {
				equalTo: "#m_email"
			},
			confirmPassword: {
				equalTo: "#m_password"
			}
		},
		messages:{		
			firstName: $("#firstNameMessage").val(),
			lastName: $("#lastNameMessage").val(),
			password: $("#passwordMessage").val(),
			confirmPassword: $("#confirmPasswordMessage").val(),
			address: $("#addressMessage").val(),
			city: $("#cityMessage").val(),
			zip: $("#zipMessage").val(),
			country: $("#countryMessage").val(),
			tAndC: $("#tAndCMessage").val(),
			privacy: $("#privacyMessage").val()
		}
	});
}

function submitForm()
{
	//reset summary area
	
	$("#errorSummaryHeader p").html('Please complete or correct the following fields:');
	$("#registrationForm").validate().resetForm();
	
	
	if ($("#registrationForm").valid())
	{
		$("#summaryBlock").hide();
		beginRegCall();
	}
}

function submitForgotPasswordForm()
{
	if ($("#loginForm").valid())
	{
		$("#summaryBlock").hide();
		beginFPCall();
	}
}

function submitUpdateForm()
{
	if ($("#updateForm").valid())
	{
		$("#summaryBlock").hide();
		beginUpdateCall();
	}
}

function submitLoginForm()
{
	if ($("#loginForm").valid())
	{
		$("#summaryBlock").hide();
		beginLoginCall();
	}
}

function makeServiceCall(formObject, serviceUrl, postData, successCallback, failureCallback)
{
	//disable formfields
	formObject.find("input").attr("disabled", "disabled");
	formObject.find("select").attr("disabled", "disabled");	
	
	//show spinner
	$("#m_spinner").show();
	
	$.ajaxDotNet(serviceUrl, {
		verb : 'POST',
		data : postData,
		success : successCallback,
		other : failureCallback
	});
}

function setAgeCookie(countryCodeVal, rememberMeVal)
{
	$.ajaxDotNet("/services/loginservice.asmx/setAgeCookie", {
		verb : 'POST',
		data : {
			countryCode : countryCodeVal,
			rememberMe : rememberMeVal
		},
		success : function(obj){
			alert("success");
		}
		,
		other : function(obj){
			alert("other");
		}
	});
}

function beginLoginCall()
{
	makeServiceCall(
		$("#loginForm"),
		"/services/loginservice.asmx/login",
		{
			username : $("#m_email").val(),
			password : $("#m_password").val()
		},
		function(obj){ 
			loginCallBackComplete(obj);
		},
		function(obj){
			loginCallBackError(obj);
		}
	);
}

function beginFPCall()
{
	makeServiceCall(
		$("#loginForm"),
		"/services/loginservice.asmx/SendPasswordReminder",
		{
			email : $("#m_email").val()
		},
		function(obj)
		{
			fPCallBackComplete(obj);
		},
		function(obj)
		{
			fPCallBackComplete(obj);
		}
	);
}

function beginRegCall()
{

	makeServiceCall(
		$("#registrationForm"),
		"/services/loginservice.asmx/Register",
		{
			firstName : $("#m_firstName").val(),
			lastName : $("#m_lastName").val(),
			email : $("#m_email").val(),
			password : $("#m_password").val(),
			address : $("#m_address").val(),
			address2 : $("#m_address2").val(),
			city : $("#m_city").val(),
			zip : $("#m_zip").val(),
			country : $("#m_country").val(),
			mobile : $("#m_mobile").val(),
			dob : readLinked(),
			gender : getGender(),
			updates : document.getElementById('m_updates').checked
		},
		function(obj){ 
			regCallBackComplete(obj);
		},
		function(obj){
			regCallBackError(obj);
		}
	);
}

function beginUpdateCall()
{
	makeServiceCall(
		$("#updateForm"),
		"/services/loginservice.asmx/Update",
		{
			firstName : $("#m_firstName").val(),
			lastName : $("#m_lastName").val(),
			password : $("#m_password").val(),
			address : $("#m_address").val(),
			city : $("#m_city").val(),
			zip : $("#m_zip").val(),
			country : $("#m_country").val(),
			mobile : $("#m_mobile").val(),
			dob : readLinked(),
			gender : getGender(),
			updates : document.getElementById('m_updates').checked
		},
		function(obj){ 
			updateCallBackComplete(obj);
		},
		function(obj){
			alert('other');
		}
	);
}

function beginPopulateCall(emailAddress)
{
	$("#m_email").val(emailAddress);
	$.ajaxDotNet("/services/loginservice.asmx/GetUserData", {
		verb : 'POST',
		success : function(mem){
			$("#m_firstName").val(mem.d[0].Value);
			$("#m_lastName").val(mem.d[1].Value);
			$("#m_address").val(mem.d[2].Value);
			$("#m_address").val(mem.d[2].Value);
			$("#m_city").val(mem.d[3].Value);
			$("#m_zip").val(mem.d[4].Value);
			$("#m_country").val(mem.d[5].Value);
			$("#m_mobile").val(mem.d[6].Value);
			setDoB(mem.d[7].Value);
			setGender(mem.d[8].Value);
			if (Boolean(parseInt(mem.d[9].Value)))
			{
				$("#m_updates").attr("checked", "checked");
			}
		},
		other : function(obj){
			alert('other');
			alert(obj.d);
		}
	});
}

function getGender()
{
	var gender = "";
	if ($("input[@name='gender']:checked").val())
	{
		gender = $("input[@name='gender']:checked").val();
	}
	return gender;
}

function setGender(gen)
{
	if (gen != '')
	{
		if (gen == 'male')
		{
			$("input[@name='gender']:nth(0)").attr("checked", "checked");
		}
		else if (gen == 'female')
		{
			$("input[@name='gender']:nth(1)").attr("checked", "checked");
		}
	}
}

function setDoB(date)
{
	if (date.length==9)
	{
		//needs preceeding 0
		date = "0"+date;
	}
	$("#selectDay").val(date.substring(0, 2));
	$("#selectMonth").val(date.substring(3, 5));
	$("#selectYear").val(date.substring(6, 10)); 
	
}

function loginCallBackComplete(obj)
{
	var status = obj.d;
	
	//hide spinner
	$("#m_spinner").hide();
	
	if (status == true)
	{
		//hide form
		$("#loginForm fieldset").hide();
		$("#buttons").hide();
		//perform post login stuff
		//alert("redirect!");
		
	}
	else 
	{
		$("#loginForm input").attr("disabled", "");
		$("#loginForm select").attr("disabled", "");
		
		$("#errorSummaryHeader").show();
		$(".errorSummary").show();
		
		$("#errorSummaryHeader p").html("This email and password do not match.");
		$(".errorSummary").html("");
	}
}

function fPCallBackComplete(obj)
{
	var status = obj.d;
	
	//hide spinner
	$("#m_spinner").hide();
	
	if (status == '##Success##')
	{
		//hide form
		$("#loginForm fieldset").hide();
		$("#buttons").hide();
		
		//hide copy except for title
		$("#copy p").hide();
		
		//show success div
		$("#feedback").show();
	}
	else if (status == '##MemberUnknown##')
	{
		$("#loginForm input").attr("disabled", "");
		$("#loginForm select").attr("disabled", "");
		
		$("#summaryBlock").show();
		
		$("#errorSummaryHeader p").html("Sorry, we do not a record of that e-mail address.  Please try again.")
		$(".errorSummary").html("");
	}
	else 
	{
		$("#loginForm input").attr("disabled", "");
		$("#loginForm select").attr("disabled", "");
		
		$("#summaryBlock").show();
		
		$("#errorSummaryHeader p").html("This email and password do not match.");
		$(".errorSummary").html("");
	}
}

function regCallBackComplete(obj)
{
	var status = obj.d;
	
	//hide spinner
	$("#m_spinner").hide();
	
	if (status == '##Success##')
	{
		//hide form
		$("#registrationForm fieldset").hide();
		
		$("#buttons").hide();
		//show success div
		$("#feedback").show();
		//make sure existing member message is hidden
		$("#m_existingMember").hide();
		//refresh login status message
		//alert("TODO: refresh login status message")
	}
	else if (status == '##MemberExists##')
	{
		//reneable form fields
		$("#registrationForm input").attr("disabled", "");
		$("#registrationForm select").attr("disabled", "");
		
		$("#summaryBlock").show();
		
		$("#errorSummaryHeader p").html("This Email Address has already been registered. Click <a href='#' onclick='buildFPForm();'>here</a> to request a password reminder.");
		$(".errorSummary").html("<ul id=\"summary\" />");
	}
}

function updateCallBackComplete(obj)
{
	var status = obj.d;
	
	//hide spinner
	$("#m_spinner").hide();
	
	if (status == '##Success##')
	{
		//hide form
		$("#updateForm fieldset").hide();
		$("#buttons").hide();
		//show success div
		$("#m_successfulUpdate").show();
	}
	else 
	{
		updateCallBackError(obj);
	}
}

function loginCallBackError(obj)
{
	//hide spinner
	$("#m_spinner").hide();
	
	$("#errorSummaryHeader p").html("An error has occured while communicating with the server. Please try again.");
	$(".errorSummary").html("");
	
	//reneable form fields
	$("#loginForm input").attr("disabled", "");
	$("#loginForm select").attr("disabled", "");
	
	$("#summaryBlock").show();
}

function regCallBackError(obj)
{
	//hide spinner
	$("#m_spinner").hide();
	
	$("#errorSummaryHeader p").html("An error has occured while communicating with the server. Please try again.");
	$(".errorSummary").html("");
	
	//reneable form fields
	$("#registrationForm input").attr("disabled", "");
	$("#registrationForm select").attr("disabled", "");
	
	$("#summaryBlock").show();
}

function updateCallBackError(obj)
{
	//hide spinner
	$("#m_spinner").hide();
	
	$("#errorSummaryHeader p").html("An error has occured while communicating with the server. Please try again.");
	$(".errorSummary").html("");
	
	//reneable form fields
	$("#updateForm input").attr("disabled", "");
	$("#updateForm select").attr("disabled", "");
	
	$("#summaryBlock").show();
}

// Prepare to show a date picker linked to three select controls 
function readLinked() { 
    $("#linkedDates").val($("#selectYear").val() + "/" + 
        $("#selectMonth").val() + "/" + $("#selectDay").val()); 
    //return {}; 
    return $("#linkedDates").val();
} 
 
// Update three select controls to match a date picker selection 
function updateLinked(date) { 
	$("#selectDay").val(date.substring(0, 2));
	$("#selectMonth").val(date.substring(3, 5));
	$("#selectYear").val(date.substring(6, 10)); 
} 
 
// Prevent selection of invalid dates through the select controls 
function checkLinkedDays() { 
    var daysInMonth = 32 - new Date($("#selectYear").val(), 
        $("#selectMonth").val() - 1, 32).getDate(); 
    $("#selectDay option").attr("disabled", ""); 
	//$("#selectDay option:gt(" + (daysInMonth - 1) +")").attr("disabled", "disabled"); 
	$("#selectDay option:gt(" + (daysInMonth) +")").attr("disabled", "disabled"); 
    if ($("#selectDay").val() > daysInMonth) { 
        $("#selectDay").val(daysInMonth); 
    } 
} 

