

















(function($) {
$.ti.login = {

	loginHTML:	$([ '<div id="swapableContent">',
						'<h2><img src="/shared/resource/images/itinerary_planner/au/text/log-in-trip-planner.png" width="301" height="28" alt="Save your Trip Planner. If you have already saved, please log in."/></h2>',
						'<p>If you have already saved your Trip Planner, please log in</p>',
						'<form method="" action="" id="loginForm">',
							'<fieldset class="login">',
                    '<h3 id="loginHeading" style="display: none"></h3>',
								'<input type="text" id="loginUsername" value="Username (Your email address)"/>',
								'<div class="passwordOverlay">',
									'<label class="password" for="loginPassword">Enter Password</label>',
									'<input type="password" id="loginPassword" />',
								'</div>',
							'</fieldset>',
							'<input type="image" id="logInButton" class="button" src="/shared/resource/images/itinerary_planner/au/buttons/login.png" alt="Log in" />',
                    '<img id="becomeMember" class="button" src="/shared/resource/images/itinerary_planner/au/buttons/sign_up_now.png" alt="Save your Trip on Discover Ireland" />',
							'<div><a href="#" class="call-to-action" id="forgotPassword">I&#039;ve forgotten my password</a></div>',
						'</form>',
						'<h3></h3>',
						'<p></p>',
					'</div>'
				].join('')),

	registerHTML:	$([	'<div id="swapableContent">',
						'<h2><img src="/shared/resource/images/itinerary_planner/au/text/overlay-headings/save-your-trip.png" alt="Save your Trip Planner on Discover Ireland" height="23" /></h2>',
						'<p id="registerInstructions">Hi there, to save your Trip to allow you to revisit, simply insert your email address and choose a password. Once you&#039;ve done that, you are able to rename your Trip, plan other Trips, share with friends and family and inspire others. </p>',
						'<form method="" action="" id="registerForm">',
							'<fieldset class="login section">',
								'<h3></h3>',
								'<select id="registerTitle" class="select">',
									'<option selected="selected">Title</option>',


									'<option>Mr</option>',



									'<option>Mrs</option>',



									'<option>Ms</option>',



									'<option>Miss</option>',



									'<option>Dr</option>',



									'<option>Reverend</option>',



									'<option>Sir</option>',


								'</select>',
								'<input type="text" id="registerFirstName" value="First name" />',
								'<input type="text" id="registerLastName" value="Last name" />',
							'</fieldset>',
							'<fieldset class="login">',
								'<h3>Your Trip Planner details</h3>',
								'<input type="text" id="registerEmail" value="Your email address (this will be your username)" />',
								'<input type="text" id="registerEmailConfirm" value="Please confirm your email address" />',
								'<div class="passwordOverlay">',
									'<label class="password" for="registerPassword">Password</label>',
									'<input type="password" id="registerPassword" value="" />',
								'</div>',
								'<div class="passwordOverlay">',
									'<label class="password" for="registerPasswordConfirm">Confirm password</label>',
									'<input type="password" id="registerPasswordConfirm" value="" />',
								'</div>',

									'<input type="checkbox" class="checkbox" path="marketing" id="marketing" />',
									'<label for="marketing"><span style="font-size : 8pt;line-height:14pt">I would like to receive information and special offers from Tourism Ireland via e-mail.</span></label>',
								
							'</fieldset>',
						'<input type="image" id="registerButton" class="button" src="/shared/resource/images/itinerary_planner/au/buttons/save-now.png" alt="Save your Trip Planner on Discover Ireland" style="float: right" />',
                        '<img class="button" id="transitionToLogin" src="/shared/resource/images/itinerary_planner/au/buttons/already_signed_up.png" alt="Log in" />',
						'</form>',
						'</div>'
					].join('')),

	forgotHTML: $([ '<div id="swapableContent">',
						'<h2>Get new password</h2>',
						'<p>Your password will be sent to your email address</p>',
						'<form method="" action="" id="forgotForm">',
							'<fieldset class="login">',
								'<h3>Please enter your email address:</h3>',
								'<input type="text" id="forgotEmail" value="Email Address" />',
							'</fieldset>',
								'<input type="image" class="button" value="submit" id="forgotButton" src="/shared/resource/images/itinerary_planner/au/buttons/submit.png" height="22" />',
						'</form>',
					'</div>'
				].join('')),

	emailSentHTML: $([
						'<div id="swapableContent">',
							'<h2>Confirmation</h2>',
							'<p>Your password has been sent to the email address you provided</p>',
							'<p>Thank you.</p>',
							'<input type="image" class="button" value="close" id="closeButton" src="/shared/resource/images/itinerary_planner/au/buttons/close.png" height"22" />',
						'</div>'
					].join('')),

    init: function() {
		// Is user logged in?
        if($.ti.tripData.trip.login) {
			$.ti.login.loggedIn = true;
        }
		this.setUserStatus();
	},

	loggedIn: false,

	afterLogin: function() {$.ti.popup.close();},

    openDialogue: function()
    {
        $.ti.login.openDialogueWithMode("register");
    },

    openDialogueWithMode: function(mode)
    {
        var content = $.ti.login.registerHTML;
        var events = $.ti.login.registerEvents;

        if (mode === "login")
        {
            content = $.ti.login.loginHTML;
            events = $.ti.login.events;
        }

        $.ti.popup.init({
            content: content,
            callback: events,
            width: '360px'
        });
    },


/*
    openDialogue: function() {
		$.ti.popup.init({
			content: $.ti.login.loginHTML,
			callback: $.ti.login.events,
			width:'360px'
		});
	},
    */

	events: function() {
		$('#loginForm').bind('submit.submitLogin', function(event){
			event.preventDefault();
			$.ti.validate.check('#loginForm', {
				rules: {
					loginUsername: {
						"required" : 'This field is required'
					},
					loginPassword: {
						"required" : 'This field is required',
						"minLength": ["6", 'Password must be at least 6 characters']
					}
				},
				success: $.ti.login.submitLogin,
				failure: $.ti.login.throwError
				});
		});

		$('#forgotPassword').click(function(){
			$.ti.popup.swapContent($.ti.login.forgotHTML, "360px", $.ti.login.forgotEvents);
		});

		$('#becomeMember').click(function(){
			$.ti.popup.swapContent($.ti.login.registerHTML,"360px", $.ti.login.registerEvents);
		});
	},

	registerEvents: function() {
		$('#registerButton').click(function(event){
			event.preventDefault();
			$.ti.validate.check('#registerForm', {
				rules: {
					registerFirstName: {
						"required"	: 'This field is required'
					},
					registerLastName: {
						"required"	: 'This field is required'
					},
					registerEmail: {
						"required"	: 'This field is required',
						"email"		: 'Email address is invalid'
					},
					registerEmailConfirm: {
						"required"	: 'This field is required',
						"matchVal"	: ['#registerEmail', 'Email addresses must match']
					},
					registerPassword: {
						"required"	: 'This field is required',
						"minLength"	: ["6", 'Password must be at least 6 characters'],
						"matchVal"	: ['#registerPasswordConfirm', 'Sorry, your passwords do not match to access your Trip Planner, please try again or click &#039;forgotten password&#039;']
					},
					registerPasswordConfirm: {
						"required"	: 'This field is required',
						"minLength"	: ["6", 'Password must be at least 6 characters']
					}
				},

				success: $.ti.login.submitRegister
				});
		});

        $("#transitionToLogin").unbind("click");
        $("#transitionToLogin").click(function(event) {
            event.preventDefault();
            $.ti.popup.swapContent($.ti.login.loginHTML, "360px", $.ti.login.events);
        });
	},

	submitRegister: function() {
		var login = {
			username: $('#registerEmail').val(),
			title: $('#registerTitle').val(),
			firstname: $('#registerFirstName').val(),
			lastname: $('#registerLastName').val(),
			password: $('#registerPassword').val(),
                                                marketing: false
		};

                                if ($('#marketing').is(':checked'))
                                     login.marketing = true;

		$.ti.tripData.trip.login = login;
		$.ti.ajax.postData('/au/trip/', $.ti.tripData, $.ti.login.registerResponse);
	},

	registerResponse: function(response) {
        if (response === 20)
        {
            // Already registered...
            $('#registerInstructions').text(



				'This email address has already been registered'


				).css('color', 'red');
        } else if(response !== 0) {
			$.ti.popup.close();
			$.ti.login.loggedIn = true;
			$.ti.login.setUserStatus();
		} else {
			// ToDo - need to represent this to user
			$.ti.console.log('failed login');
		}
	},

	forgotEvents: function() {
		$('#forgotButton').click(function(event){
			event.preventDefault();
			$.ti.validate.check('#forgotForm', {
				rules: {
					forgotEmail: {
						"required" : 'This field is required',
						"email" : 'Please enter a valid email address'
					}
				},
				success: $.ti.login.submitForgot
			});
		});
	},

	submitForgot: function() {
		var forgot = {
				login: {
					username: $('#forgotEmail').val()
				}
			};
		$.ti.ajax.postData('/au/trip/', forgot, $.ti.login.forgotResponse);
	},

	forgotResponse: function(response) {
		if(response !== 0) {
			$.ti.popup.swapContent($.ti.login.emailSentHTML, "360px", $.ti.login.emailSentEvents);
		} else {
			var errorLabel = $('<label for="forgotEmail" class="error">This email address has not been registered</label>').hide();
            $('#forgotEmail').before(errorLabel);
            errorLabel.fadeIn(500);
		}
	},

	emailSentEvents: function() {
		$('#closeButton').click(function(){
			$.ti.popup.close();
		});
	},

	submitLogin: function() {
		var login = {
			login: {
				username: $('#loginUsername').val(),
				password: $('#loginPassword').val()
			}
		};

		$.ti.tripData.trip.login = login.login;
		if($.ti.tripData.trip.tripActivities) {
			$.ti.ajax.postData('/au/trip/?tripId=' + $.ti.tripData.trip.id, $.ti.tripData, $.ti.login.checkLoginResponse);
		} else {
			$.ti.ajax.postData('/au/trip/?tripId=', $.ti.tripData, $.ti.login.checkLoginResponse);
		}
	},

	checkLoginResponse: function(data) {
		if(data !== 0) {
			$('#loginForm').unbind('submit.submitLogin');
			// run the temporary after login function
			$.ti.login.afterLogin();
			// reset the after login function to it's normal close popup behaviour
			$.ti.login.afterLogin = function() {$.ti.popup.close();};
			// Todo - stop using this item - work from main trip object
			$.ti.login.loggedIn = true;
			$.ti.panel.saveTripAndPromos(data, $.ti.panel.useTripData);
		} else {
			var error = $('<label for="loginUsername" class="error">Sorry, your username and password do not match our records</label>');
			$('#loginHeading').html(error).show();
		}
	},

	checkLogoutResponse: function(data) {
		if(data !== 0) {
			$.ti.login.loggedIn = false;
			$.ti.login.setUserStatus();
			$.ti.recalculateCalendarGrid.clearGrid();
            $('.day', '#calendarDays').remove();
			$.ti.panel.saveTripAndPromos(data, $.ti.panel.useTripData);
		}
	},

	setUserStatus: function() {
		if($.ti.login.loggedIn === true) {
			// Set username and account management event
			$('#userName').empty()
						  .append('Hi there:&nbsp;<a id="userName">'



							  + $.ti.tripData.trip.login.firstname


							  + '</a>')
						  .click(function(){
							$.ti.account.init();
						  });
			// Clear click events
			$('#logIn').unbind('click');
			// Add log out event
			$('#logIn').text('Log out')
					   .bind('click.logout', function(event) {
							event.stopPropagation();
							$.ti.login.logOut();
						});

		} else {
			$('#userName').text('View your saved trips');
			// Clear click events
			$('#logIn').unbind('click');
			$('#logIn').text('Log in')
					   .bind('click.login', function(event){
							event.stopPropagation();
							$.ti.login.openDialogueWithMode("login");
						});
		}
	},

	logOut: function() {
		var logout = {
			username: ''
		};
		$.ti.tripData.trip.login = logout;
		$.ti.ajax.postData('/au/trip/?tripId=-1', $.ti.tripData, $.ti.login.checkLogoutResponse);
	}
};
})(jQuery);
