/*jquery.login.js
*
* Copyright 2009 Padilla Technology Solutions. All rights reserved.
*
*/

(function($){
	//create class to use this plug-in as OO
	var Login = function(container, options){
		container = $(container);
		var self = this;
		var usernameCell = null;
		var passwordCell = null;
		var forgotLink = null;
		var passwordRow = null;
		var message = "";
		var buttons = null;
		var usernameText = "";
		
		//set up the options first in the settings then use opts to set up any meta tags if included
		var settings = $.extend({}, $.fn.login.defaults, options);
		var opts = $.meta ? $.extend({}, settings, self.data()) : settings;
		
		/*@function init
		*	sets up the object
		* 
		* @params none
		*
		* @return void
		*/
		function init(){
			container.append(createMarkup());
			container.dialog({ modal:false, close: function(){reset(false)}, resizable: false, title: 'logga in', autoOpen: false, hide: 'slide', show: 'slide', 'buttons' : {'logga in' : function(){getAuthorization()}, 'registrera dig': function(){window.location = "register.php"; /*$(this).dialog("close");*/}}, position: 'top'});
			//set the 'enter' key to get authorization
			container.keyup(function(e) {
			    if (e.keyCode == 13) {
			        getAuthorization();
			    }
			});
		}
		
		/*@function createMarkup
		*	creates the markup needed for the login form
		* 
		* @params takes no parameters at this time
		*
		* @return element containing all of the markup for the login window
		*/
		 function createMarkup(){
			var table = $(document.createElement('table'));
			var row = $(document.createElement('tr'));
			table.append(row);
			
			//message
			var cell = $(document.createElement('td'));
			cell.attr('colspan',2);
			row.append(cell);
			message = cell;
			
			//username
			row = $(document.createElement('tr'));
			table.append(row);
			
			cell = $(document.createElement('td'));
			cell.html("Användarnamn: ");
			usernameText = cell;
			row.append(cell);
			
			cell = $(document.createElement('td'));
			usernameCell = $(document.createElement('input'));
			usernameCell.attr({'type':'text'});
			cell.append(usernameCell);
			row.append(cell);
			
			//password
			row = $(document.createElement('tr'));
			table.append(row);
			
			cell = $(document.createElement('td'));
			cell.html("Lösenord: ");
			row.append(cell);
			
			cell = $(document.createElement('td'));
			passwordCell = $(document.createElement('input'));
			passwordCell.attr({'type':'password'});
			cell.append(passwordCell);
			row.append(cell);		
			
			passwordRow = row;
			//forgot link
			row = $(document.createElement('tr'));
			table.append(row);
			
			cell = $(document.createElement('td'));
			cell.html('&nbsp;');
			
			row.append(cell);
			cell = $(document.createElement('td'));
			cell.css('text-align','right');
			row.append(cell);
			
			forgotLink = $(document.createElement('a'));
			forgotLink.attr({'href':'#'}).click(function(){iForgot();});
			forgotLink.html('Glömt mitt lösenord');		
			cell.append(forgotLink);
			
			return table;	
		}		
		
		/*@function getAuthorization
		*	
		* 
		* @params takes no parameters
		*
		* @return void
		*/
		function getAuthorization(){
			var indicator = null;
			try{
				indicator = container.indicator().data('indicator');
			}catch(e){
				
			}
			if(indicator) indicator.start();
			if(!isValid()){ 
				if(indicator) indicator.stop(); 
				return;
			}
			
			var url = opts.authURL;
			var data = "username="+escape(usernameCell.val())+"&password="+escape(passwordCell.val())+"&action=login";
			
			$.post(url, data, function(response){
				respone = response*1;
				if(indicator) indicator.stop();
				if(response == 1){//successful authorization
					window.location = "submitobservation.php";
				}else if(response == 2){//invalid authorization
					addMessage("Ogiltigt användarnamn eller lösenord!");
					message.addClass('redtext');
				}else{//error of some kind
					addMessage("Det fanns ett problem med att logga in i systemet. Försök igen.");
					message.addClass('redtext');
				}
			});
			
		}
		
		/*@function reset
		*	resets the dialog box and closes it
		* 
		* @params keepUsername bool: if set to true, do not remove the username text from the usernameCell
		*
		* @return void
		*/
		function reset(keepUsername){
			container.dialog('option', 'buttons', {'logga in' : function(){getAuthorization()}, 'registrera dig': function(){window.location = "register.php";}});
			usernameCell.parent().parent().show();
			passwordRow.show();
			forgotLink.parent().parent().show();
			addMessage("");
			message.removeClass('redtext');
			if(!keepUsername)
				usernameCell.val("");
			usernameCell.removeClass("redborder");
			passwordCell.val("");
			passwordCell.removeClass("redborder");
			if(usernameText) usernameText.html("Användarnamn: ");
		}
		
		/*@function addMessage
		*	
		* 
		* @params text, string: The message that will be shown to the user in the message cell
		*
		* @return void
		*/
		function addMessage(text){
			if(message)
				message.text(text);
		}
		
		/*@function iForgot
		*	hides the password text field, adds text to the message area and resets 
		*	the ok button function to send the user their password
		* 
		* @params takes no parameters
		*
		* @return void
		*/
		function iForgot(){
			if(passwordRow)
				passwordRow.hide();
			if(forgotLink)	
				forgotLink.parent().parent().hide();
				
			if(usernameText)
				usernameText.html("e-post: ");
			addMessage("Skriv in din e-post och klicka på 'Skicka'.");
			container.dialog('option', 'buttons', { "skicka": function() { 
					if(!isValid()) return;
					var url = opts.forgotURL;
					var data = "email="+escape(usernameCell.val());
					$.post(url, data, function(response){
						if(!response) return
						response = response*1;
						if(response == 1){
							addMessage("Dina användaruppgifter skickas till din e-post.");
							container.dialog('option', 'buttons', { "tillbaka": function() {reset(true)}});
						}else
							addMessage("Denna e-post-adress finns inte registrerad på blommar.nu.");   
					})
					//addMessage("Your password has been sent to the email on file.");
					//container.dialog('option', 'buttons', { "sign in": function() {reset(true)}, "close": function() {container.dialog('close')}});
				} , "tillbaka": function() {reset(true)}
			}); 
		}
		
		/*@function isValid
		*	checks the form for required fields and changes the css of any field that is required and not filled in
		* 
		* @params takes no parameters
		*
		* @return boolean indicating whether all of the required fields are filled in or not
		*/
		function isValid(){
			var valid = true;
			if(passwordRow.is(":visible")){
				if(passwordCell.val() == ''){
					passwordCell.addClass("redborder");
					valid = false;
				}else{	
					passwordCell.removeClass("redborder");
				}
			}
			
			if(usernameCell.val().replace(/^\s*|\s*$/g,'') == ''){
				usernameCell.addClass("redborder");
				valid = false;
			}else{	
				usernameCell.removeClass("redborder");
			}
			
			return valid;
		}
		
		//call the init method to get this party started
		init();
	}
	//create the actual jquery plugin
	$.fn.login = function(options){
		
		return this.each(function(){
				var self = $(this);
				// build element specific options
				//none at this time
				
				//if element is already an instance of this plug-in, return 
				if(self.data('login')) return;
				
				var li = new Login(this, options);
				
				/*********************************************************
				THIS IS WHAT YOU NEED TO USE TO GET HOLD OF THE OBJECT!!!!
								var myvar = $('myaccessor').data('login')
				**********************************************************/
				//store plug-in object in this element's data ;;; 
				self.data('login', li);
		});//end this.each
	};

	$.fn.login.defaults = {authURL : "backend/indexController.php", forgotURL : "backend/sendPassword.php"};

})(jQuery);

function logMeOut(){
	$.post("backend/indexController.php", "action=logout", function(response){
		response = response*1;
		if(response == 1){
			window.location = "index.php";
		}
	});
}

