/* A GLOBAL VARIABLE. YUK */
var COOKIENAME = "dcssecurelogin";

var DCSSecurePage = false; 	// This var is set to true if the make-page-secure.js file which is loaded. This JS file is loaded for protected pages only

/* Preload graphics */
$.preloadImages("/workspace/assets/ui/login.bottom.png", "/workspace/assets/ui/login.top.png",
"/workspace/assets/ui/login.back.repeat.png","/workspace/assets/ui/opacity70.png","/workspace/assets/ui/opacity50.png");

/* CLASS: DCSSecureAreaController 
 *
 * This class manages access to the DCS secure area. Users have to login in order
 * to view the projects section of the website. 
 * Whether a user is logged in or not is determined by a cookie
 *
 ********************************************************************************/
 
var DCSSecureAreaController = function(dataObj) {
	this.domProtectedLinks = dataObj.domProtectedLinks;
	this.domProjectLoginHolder = dataObj.domProjectLoginHolder;
	this.domLoginBox = $(this.domProjectLoginHolder).find(".plb-panel-client-login").get()[0];  
	this.domRegistrationBox = $(this.domProjectLoginHolder).find(".plb-panel-registration-request").get()[0];  
	this.cookieName = dataObj.cookieName;
	this.loginBoxController = "";
	this.registrationBoxController = "";
	this.loginVerificationUrl = "/protected-pages-user-details/";
	this.mailToUrl = "/registration-mailto/";
	this.isPageSecure = dataObj.isPageSecure;
	this.isFireFoxMac2 = false;
}

DCSSecureAreaController.prototype = {
	init: function() {
		var self = this;
		// Here, we want to check if the user is already logged in, ie the cookie has been set
		// If so, we simply return
		if (self.isLoggedIn()) {
			return;
		}	
				
		if (navigator.userAgent.indexOf("Mac")!=-1 && navigator.userAgent.indexOf("Firefox/2")!=-1) {
			self.isFireFoxMac2=true;
		}

		// Let's initialise af form controller for each of both the login and reg boxes 
		this.loginBoxController = new DCSFormController({
			domHolder: this.domLoginBox,
			ajaxWaitingMessage: "Please wait while we verify your details",
			ajaxErrorMessage: "We could not find a user matching these details. Please check and try again",
			submitFunction: function(dataObj) {
				var fieldData = dataObj.fieldData;
				var successCallbackFunc = dataObj.successCallbackFunc;
				var failureCallbackFunc = dataObj.failureCallbackFunc;
				
				var ajaxUrl = self.loginVerificationUrl+fieldData["username"]+"/"+fieldData["password"]+"/";
				$.ajax({
					url: ajaxUrl,
					cache: false,
					success: function(xmlstr) {
						var xml = $('user-found', xmlstr);
						if (xml.text() == 'true') {
							successCallbackFunc();
						}
						else {
							failureCallbackFunc();
						}
					}
				});
			}			
		});
		this.loginBoxController.init();
		
		this.registrationBoxController = new DCSFormController({
			domHolder: this.domRegistrationBox,		
			ajaxWaitingMessage: "Submitting your request...",
			ajaxErrorMessage: "There was a problem sending your email. Please check your details and try again",
			submitFunction: function(dataObj) {
				var fieldData = dataObj.fieldData;
				var successCallbackFunc = dataObj.successCallbackFunc;
				var failureCallbackFunc = dataObj.failureCallbackFunc;
				
				var ajaxUrl = self.mailToUrl+fieldData["name"]+"/"+fieldData["email"]+"/"+fieldData["company"]+"/"+fieldData["telephone"]+"/";
				$.ajax({
					url: ajaxUrl,
					cache: false,
					success: function(xmlstr) {
						var xml = $('success', xmlstr);
						if (xml.text() == 'true') {
							successCallbackFunc();
						}
						else {
							failureCallbackFunc();
						}
					}
				});
			}			
		});
		this.registrationBoxController.init();

		// Close the login/reg stuff when user clicks on the faded out area but only if not a secure page
		$(this.domProjectLoginHolder).click( function() {
			if (!self.isPageSecure) {
				self.hideEverything();
			}
		});

		// Cancel the click event on the actual domLoginBox and domRegistrationBox
		// to prevent the event bubbling ip the the domProjectLoginHolder and causing
		// the stuff to be hidden
		$(this.domLoginBox).click( function() {
			return false;
		});
		$(this.domRegistrationBox).click( function() {
			return false;
		});

		// If on a secure page, hide the panel close buttons
		if (self.isPageSecure) {
			$(self.domProjectLoginHolder).find("a.plb-close").css({display:"none"});
		}
		else {
			$(self.domProjectLoginHolder).find("a.plb-close").click( function() {
				self.hideEverything();
				return false;
			});
		}

		// User is not logged in, so we need to provide protection 
		// Firstly, by protecting links to secure areas
		$(this.domProtectedLinks).click( function() {
			
			// Need to check if person is logged in at this point in safari
			if (self.isLoggedIn()) {
				return true;	
			}
			
			var thisUrl = $(this).attr("href");
			self.displayLoginBox({
				successFunction: function() {
  					Set_Cookie(self.cookieName, "userVerified", 0, '/', '', '' );
  					self.hideEverything();
					window.location = thisUrl;
				},
				cancelFunction: function() {
					// do nothing
				}
			});
			return false;
		});
		
		// And secondly, if someone has entered a protect page url directly in the browser
		// we need to hide the content, and immediately popup the login box

		if (self.isPageSecure && !self.isLoggedIn()) {
			$(self.domProjectLoginHolder).addClass("project-login-box-opaque");		
			self.displayLoginBox({
				successFunction: function() {
  					Set_Cookie(self.cookieName, "userVerified", 0, '/', '', '' );
					window.location.reload(true);
				},
				cancelFunction: function() {
					// do nothing
				}
			});
		}
		
		// Finally, lets activae the link on the login box that takes the user to the registration form
		$(this.domLoginBox).find("a.open-registration-panel").click( function() {
			self.displayRegistrationBox({
				successFunction: function() {
					self.registrationBoxController.showFeedBackConfirmationMessage({ message: "David Collins Studio will contact you shortly." });
				},
				cancelFunction: function() {
				}
			});
			return false;	
		});

		$(this.domRegistrationBox).find("a.open-login-panel").click( function() {
			$(self.domRegistrationBox).css({display:"none"});
			$(self.domLoginBox).css({display:"block"});
			return false;
		});

	},
	displayRegistrationBox: function(dataObj) {
		var self = this;
		self.registrationBoxController.successFunction = dataObj.successFunction;
		self.registrationBoxController.cancelFunction = dataObj.cancelFunction;
		$(self.domRegistrationBox).css({display:"block"});
		$(self.domLoginBox).css({display:"none"});
	},
	displayLoginBox: function(dataObj) {
		var self = this;
		self.loginBoxController.successFunction = dataObj.successFunction;
		self.loginBoxController.cancelFunction = dataObj.cancelFunction;
		self.displayEverything();
		$(self.domRegistrationBox).css({display:"none"});
		$(self.domLoginBox).css({display:"block"});
	},
	displayEverything: function() {
		if (!this.isFireFoxMac2) { 
			$(this.domProjectLoginHolder)
			.css({opacity: 0, display:"block"})
			.animate( { opacity: 1}, 500, function() {
				
			});
		}
		else {
			$(this.domProjectLoginHolder).css({ display: "block" });
		}
		if ($.browser.msie) $('embed, object').hide();
	},
	hideEverything: function() {
		if (!this.isFireFoxMac2) { 
			$(this.domProjectLoginHolder)
			.animate( {opacity: 0}, 500, function() {
				$(this).css({display:"none"});
				if ($.browser.msie) $('embed, object').show();
			});
		}
		else {
			$(this.domProjectLoginHolder).css({ display: "none" });
			if ($.browser.msie) $('embed, object').show();
		}
		
	},
	isLoggedIn: function() {
		var isLoggedIn = Get_Cookie(this.cookieName);
		if (isLoggedIn && isLoggedIn == "userVerified") {
			return true;	
		}
		else {
			return false;
		}
	}

}


/* CLASS: DCSFormController 
 *
 * This class manages a simple form, ensuring that necessary fields are filled in
 * displaying error messages if they are not, and calling a supplied callback function
 * when the form is due to be submitted
 *****************************************************************************************/
var DCSFormController = function(dataObj) {
	this.domHolder = dataObj.domHolder;
	this.domForm = $(this.domHolder).find("form").get()[0];
	this.domFields = $(this.domHolder).find("input").get();
	this.domFeedbackMessage = $(this.domHolder).find("p.feedback-message").get()[0];
	this.domSubmitButton = $(this.domHolder).find("button").get()[0];
	this.submitFunction = dataObj.submitFunction;
	this.fieldData = new Array();
	this.fieldErrorClass = "plb-field-error";
	this.successFunction = "";
	this.cancelFunction = "";
	this.ajaxWaitingMessage = dataObj.ajaxWaitingMessage;
	this.ajaxErrorMessage = dataObj.ajaxErrorMessage;
	this.currentlySubmitting = false;
}

DCSFormController.prototype = {
	init: function() {
		var self = this;
		$(this.domForm).submit( function() {
			return false;
		});
		$(this.domSubmitButton).click( function() {
			self.submitForm();
		});
		
		$(this.domFields).focus( function() {
			$(this).parents("li").removeClass(this.fieldErrorClass);
			$(self.domFeedbackMessage).css({display:"none"});
		});
		
	},
	submitForm: function() {
		var self = this;
		if (this.checkFields() && !this.currentlySubmitting) {
			self.showFeedBackWaitingMessage();
			this.storeFieldData();
			this.currentlySubmitting = true;
			this.submitFunction({
				fieldData: this.fieldData,
				successCallbackFunc: function() {
					self.successFunction();
					self.currentlySubmitting = false;
				},
				failureCallbackFunc: function() {
					self.showFeedBackErrorMessage({ message: self.ajaxErrorMessage });
					self.currentlySubmitting = false;
				}
			});
		}
	},
	checkFields: function() {
		var self = this;
		var allFieldsFilled = true;
		$(this.domFields).each( function() {
			if (!$(this).val()) {
				allFieldsFilled = false;
				$(this).parents("li").addClass(self.fieldErrorClass);	
				self.showFeedBackErrorMessage({ message: "Please fill in all fields"});
			}
		});
		return allFieldsFilled;
	},
	storeFieldData: function() {
		var self = this;
		this.fieldData = new Array();
		$(this.domFields).each( function() {
			self.fieldData[$(this).attr("name")] = $(this).val();
		});	
	},
	showFeedBackWaitingMessage: function() {
		$(this.domFeedbackMessage)
		.removeClass("feedback-message-error")
		.removeClass("feedback-message-confirmation")
		.css({display:"block"})
		.text(this.ajaxWaitingMessage);
	},
	showFeedBackErrorMessage: function(dataObj) {
		$(this.domFeedbackMessage)
		.removeClass("feedback-message-confirmation")
		.addClass("feedback-message-error")
		.css({display:"block"})
		.text(dataObj.message);
	},
	showFeedBackConfirmationMessage: function(dataObj) {
		$(this.domFeedbackMessage)
		.addClass("feedback-message-error")
		.addClass("feedback-message-confirmation")
		.css({display:"block"})
		.text(dataObj.message);
	}
}
	

$(document).ready( function() {
	// Wait until document has loaded before we initialise the
	// controller. This ensures that the protected links will have loaded.
	var isPageSecure = (DCSSecurePage) ? true : false; 
	var secureAreaController = new DCSSecureAreaController({
		domProtectedLinks: $("a.dcs-protected-projects").get(),
		domProjectLoginHolder: $("#project-login-box").get()[0],
		cookieName: COOKIENAME,
		isPageSecure: DCSSecurePage
	});
	secureAreaController.init();
	
});