﻿Object.extend(Avenet.Utilities, {
	doPasswordReset: function() {
		if (!Avenet.Utilities.inPasswordReset) {
			Avenet.Utilities.inPasswordReset = true;
			setTimeout("Avenet.Forms.showModalForm('PasswordReset')", 1000);
		}
	},
	
	checkForPasswordReset: function() {
		if (Avenet.Utilities.needPasswordChange || forcePasswordChangeNecessary == "true") {
			Avenet.Utilities.doPasswordReset();
		}
	},
	
	reAuthenticate: function(onReauthCallback) {
		var cleanup = function() {
			var authForm = $('Authentication');
			authForm.reauth = true;
			authForm.onReauthCallback = onReauthCallback;
		};

		Ajax.awaitingReauthenticate = true;
		Avenet.Forms.showModalForm('Authentication', cleanup.bind(this));
	}
});

function ticketRequest() {
	if (!Avenet.Forms.isFormValid('Authentication')) {
		return false;
	}
	
	Avenet.Forms.showLoadingGraphic( $('Authentication') );
	$('Authentication_submitButton').disabled = true;
	
	var authForm = $('Authentication');
	authForm.reauth = authForm.reauth || false;
	authForm.onReauthCallback = authForm.onReauthCallback || null;
	
	var hash = $('Authentication').serialize(true);
	if(authForm.reauth == true) {
		hash.push({'Key': 'userTypeValue', 'Value': 'owner'})
	}
	
	if(requireSSL && baseUrl.substring(8, 0) != 'https://') {
		new Ajax.Request(basePath + 'Services/SecurityService.svc/GetSecureRequest',{
			asynchronous: false,
			allowRequestOnAwaitingForReauthenticate: true,
			onSuccess: function (transport) {
				var response = transport.responseText.evalJSON(true);
				if(response.Status == true) {
					var url = window.location.host;
					new Ajax.Request(secureUrl + 'Scripts/SecureRequest.js',{
						method: 'get',
						crossSite: true,
						allowRequestOnAwaitingForReauthenticate: true,
						parameters: {r: response.ResponseObject, url: url, Action: 'Authenticate', Hash: Object.toJSON(hash)},
						onSuccess: function (transport) {
							// set ui cookie to "mouse"
							createCookie("ui", "mouse", 100);
							Avenet.Forms.destroyLoadingGraphic();
							if(secureResponse.Status == true) {
								if(authForm.reauth == true) {
									Ajax.awaitingReauthenticate = false;
								
									Avenet.Forms.clearModalForm();
									if(typeof(authForm.onReauthCallback) != 'undefined' && Object.isFunction(authForm.onReauthCallback)) {
										new Ajax.Request(basePath + 'Services/SecurityService.svc/FinishSecureRequest',{
											asynchronous: false,
											allowRequestOnAwaitingForReauthenticate: true,
											postBody: Object.toJSON({action: 'Authenticate'}),
											onSuccess: function (transport) {
												authForm.onReauthCallback();
											}.bind(this)
										});
									}
								} else {
									if(secureResponse.SuccessMessage.length > 0)
										window.location = secureResponse.SuccessMessage;
									else
										window.location = baseUrl.replace('https://', 'http://') + document.getElementById('requestedPageValue').value;
								}
							} else {
								$('Authentication_submitButton').disabled = false;
							}
						},
						onFailure: function() {
							$('Authentication_submitButton').disabled = false;
							if(secureResponse.Status != null && !secureResponse.Status) //handle display errors here.
							{
								var errors = unpackDictionary(secureResponse.ErrorMessages);
								
								if ($H(errors).keys().length) {
									var message = ""
									$H(errors).each(function (err) {
										message += ('*' + err[0] + ': ' + err[1] + '<br />');
									});
									
									if( Avenet && Avenet.Forms ) Avenet.Forms.Validation.displayServerSideErrors( errors, 'Authentication' );
									else if($("formErrors")) $("formErrors").update( message );
								}
							}
						},
						passwordChangeCallback: function() {
							// Pick up the password change in the onLoad of wherever we're heading.
							Avenet.Utilities.needPasswordChange = true;
						}
					});
				}
			}.bind(this)
		});
	} else {
		new Ajax.Request(basePath + 'Services/SecurityService.svc/Authenticate',{
			postBody: Object.toJSON({hash: hash}),
			allowRequestOnAwaitingForReauthenticate: true,
			onSuccess: function ( transport ) {
				createCookie("ui", "mouse", 100);
				Avenet.Forms.destroyLoadingGraphic();
				response = transport.responseText.evalJSON(true);
				if(response.Status == true) {
					if(authForm.reauth == true) {
						Ajax.awaitingReauthenticate = false;
					
						Avenet.Forms.clearModalForm();
						if(typeof(authForm.onReauthCallback) != 'undefined' && Object.isFunction(authForm.onReauthCallback)) {
							authForm.onReauthCallback();
						}
					} else {
						if(response.SuccessMessage.length > 0)
							window.location = response.SuccessMessage;
						else
							window.location = baseUrl.replace('https://', 'http://') + document.getElementById('requestedPageValue').value;
					}
				} else {
					$('Authentication_submitButton').disabled = false;
				}
			},
			passwordChangeCallback: function() {
				// Pick up the password change in the onLoad of wherever we're heading.
				Avenet.Utilities.needPasswordChange = true;
			}
		});
	}
}

function resetPassword() {
	var hash = $('Authentication').serialize(true);
	if(!$('userTypeValue')) {
		hash.push({'Key': 'userTypeValue', 'Value': 'owner'})
	}

	new Ajax.Request(basePath + 'Services/SecurityService.svc/ResetPassword', {
	    postBody: Object.toJSON({ hash: hash }),
	    onSuccess: function(transport) {
	        response = transport.responseText.evalJSON(true);
	        if (response.Status == true) {
	            $('resetPasswordMessage').update(response.SuccessMessage);
	            $('Authentication_resetPassword').hide();
	            Avenet.Utilities.inPasswordReset = false;
	        }
	    }
	});
}

function validateUnder18() {
	if(this.e.value == '') 
		return true;
	var d = new Date(this.e.value);
	if(d == "NaN" || d == "Invalid Date") return true;
				
	var dt = new Date();
	return new Date(this.e.value) > new Date(dt.getYear()-18,dt.getMonth(),dt.getDate());
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
