/***
 * A special GIUI control for managing final validation and saving of the model. 
 * @param {Object} pmodel
 * @param {Object} name, the name used to refer to this object when sending validation messages  
 * @param {Object} refInHTML
 * @param {Object} label - label of button, not used
 * @param {Object} validationSettings, special validation settings needed for this save button
 * @param {Object} redirectUrl
 * @param {Object} secure - true = use SSL with jsonp 
 * 
 */  
function guiControlSaveButton(pmodel, name, refInHTML, label, validationSettings, redirectUrl, secure){
	
	console.log("save button created");
	
	var model;
	var refInHTML;
	var button;
	var uiControl;
	var myName;		// Message name for the save button. Used by the validation.
	var clicked;	// Is true if the user clicked the save button. Used by the validation.
	var myLabel;
	var myValidationSettings;
	var myRedirectUrl; 
	var me;
	
	// Init
	me = this;
	model = pmodel;
	refInHTML = refInHTML;
	myName = name;
	clicked = false;
	myLabel = typeof(label) === "undefined" ? "Save" : label;
	if(validationSettings !== null){
		myValidationSettings =  validationSettings;	
	}
	myRedirectUrl = redirectUrl;
	
	// Create button
	// button = $("<div class='buttonBig'>"+myLabel+"</div>");	
	
	// $(refInHTML).append(button);
	button = $(refInHTML);
	
	// TODO: remove line below when all the pages have gotten the new CSS. It only exists so that the old paged display something. 
	button.addClass("saveButton");
	
	uiControl = $(refInHTML).hasClass("UI_control") ? $(refInHTML) : $(refInHTML).parents(".UI_control");
	// Add model validation callback
	model.addValidationListeners(validated, this);
	// Add model update callback to determine whan to disable/enable the save button
	model.addUpdateListers(manageSaveButtonStatus, this);
	
	// Set the saved status to true	
	model.saved = true; 
	
	// Add click evenhandler	
	button.click((function(evt){				
		
		clicked = true;		
		
		// Validate data in model
		var inputIsValid = model.validate(myValidationSettings);
		
		
		if(inputIsValid){
			// Change button background to "saving.." image
			button.addClass('saving');
			// Call model to save. manageSaveResult is the callback function and me is the context of this object.
			if(secure){
				model.saveSecure(manageSaveResult, me);
			}
			else{
				model.save(manageSaveResult, me);
			}
		}
		
			
	}));
	
	

	/***
	 *  Function called each time something is updated in the model. 
	 *  From this function we can determine if we should hide/show endable/disable the button.
	 * @param {Object} message
	 */
	function manageSaveButtonStatus(message){		
				
		// Listen to all messages
		if(this.enableButton(model.getData())){
			$(refInHTML).show();
		}
		else $(refInHTML).hide();		
		
	}
	
	// This function can/should be overwritten with object augmentation from the 
	// controller object in order to do any usefull stuff. 
	this.onSuccessfulSave = function(resultMessage){
		
	}


	// This function can/should be overwritten with object augmentatino from the 
	// controller object in order to do any usefull stuff. Default is to always enable.
	this.enableButton = function(modelData){
		return true;
	}
	
	// If the conditions for validation should change after the save button has been created 
	// we can add the new settings with this function. (e.g. if user logs in)
	this.updateValidationSettings = function(settings){
		myValidationSettings = settings;
	} 
	
	this.updateRedirectUrl = function(newUrl){
		myRedirectUrl = newUrl;
	}
		
	/***
	 *  
	 * @param {Object} message
	 */
	function validated(message){	
		
		if(message.Reciever === myName){
						
			// If the page is validated it means that something has changed so we must remove
			// any previous save messages.
			if($(uiControl).find(".saveMessage").length > 0){
				$(uiControl).find(".saveMessage").html("");
			} 
			
			
			if(message.Error && clicked){
				// If there was an error message present it is updated. We use .next() since any error div 
				// is added as a next sibling to the control that had the error.
				
				console.log("savebutton ERROR");
	 			var mainErrorMessage = "Not all mandatory fields are correctly filled in.";
				if ($("#saveError").length > 0) {
					$("#saveError").html(mainErrorMessage);
				}
				else {
					$(uiControl).after("<div id='saveError' class='validationError'>" +mainErrorMessage+ "</div>");
				}
					
			}
			else {
				$("#saveError").html("");
				
			}
			clicked = false;
		}
	}
	
	/***
	 * Used as callback when the model has saved the data
	 * @param {Object} resultMessage
	 */
	
	function manageSaveResult(resultMessage){
		var uiControl = $(refInHTML).hasClass("UI_control") ? $(refInHTML) : $(refInHTML).parents(".UI_control");
		var msgToUser = ""; 
				
		// Change button background to initial image
		button.removeClass('saving');	
			
		// Define message to give to user
		// Saving went fine
		if(resultMessage.status === 'ok'){ 
			// console.info(myRedirectUrl);
			this.onSuccessfulSave(resultMessage);
			
			if(myRedirectUrl){												
				window.location.href=myRedirectUrl;
				return;
			}
				
			msgToUser = "";
		}
		else{
			// Saving was unsuccessful
			// User not authenticated
			if(resultMessage.status === 'authentication_failed'){ 
				msgToUser = "Sorry. Your " + model.getName() +
				" could not be saved since your identity could not be verified. Most likely you have been logged out. Try logging in again.";
			}
			// Validation showed incorrect input and failed
			else if(resultMessage.status === 'validation_failed'){ 
				msgToUser = "Sorry, please change marked input and try again."
			}
			// Validation showed incorrect input and failed
			else if(resultMessage.status === 'validation_error'){ 
				msgToUser = "Sorry. Your " + model.getName() +" could not be saved. The validation of your input caused a problem. Please try again."
				console.error(resultMessage.status +" >> " + resultMessage.messages.errmsg.toString());	
			}		
			
			// Validation showed incorrect input and failed
			else if(resultMessage.status === 'save_error'){ 
				msgToUser = "Sorry. Your " + model.getName() +" could not be saved. Someything went wrong during saving." 
				console.log("ERROR: "+resultMessage.messages.toString());
			}		
			
			// Recover successfull. An email was sent to the user with 
			else if(resultMessage.status === 'password_recovered'){ 
				this.onSuccessfulSave(resultMessage.status);			 			
			}		
	
			
			// Something unexpected happened and the message status could not be read	
			else{ 
				msgToUser = "Sorry. The server returned an unknown message. Your " + model.getName() +"  could not be processed. " 
				console.error(resultMessage);
			}
			
			
			// If there was an error message present it is updated.  
			if ($("#saveError").length > 0) {
					$("#saveError").html(msgToUser);
			}
			else {
				$(uiControl).after("<div id='saveError' class='validationError'>" +msgToUser+ "</div>");
			}						
		}
		

			
	}

}
