var formChangeLoggerSvc = angular.module('formChangeLoggerSvc', []);

formChangeLoggerSvc.factory('formChangeLoggerSvc', function($cookies, $rootScope, $http, $q,$window,
		$mdDialog, $mdToast) {

	var formChangeLoggerSvc = {};
	formChangeLoggerSvc.currentFieldName=null;
	formChangeLoggerSvc.currentFieldOldValue=null;
	formChangeLoggerSvc.currentFieldNewValue=null;
	formChangeLoggerSvc.listOfChanges = new Array();		
	
	
	formChangeLoggerSvc.init = function() {
		formChangeLoggerSvc.currentFieldName=null;
		formChangeLoggerSvc.currentFieldOldValue=null;
		formChangeLoggerSvc.currentFieldNewValue=null;
		formChangeLoggerSvc.listOfChanges = new Array();		
	}
	
	formChangeLoggerSvc.enterField = function(fieldName, fieldValue) {
		formChangeLoggerSvc.currentFieldName = fieldName;
		formChangeLoggerSvc.currentFieldOldValue = fieldValue;		
	}
	
	formChangeLoggerSvc.exitField = function(fieldValue) {
		formChangeLoggerSvc.currentFieldNewValue = fieldValue;		
		if (formChangeLoggerSvc.currentFieldNewValue != formChangeLoggerSvc.currentFieldOldValue) {
			
		console.log(formChangeLoggerSvc.currentFieldName + ": " + formChangeLoggerSvc.currentFieldOldValue + " -> " + formChangeLoggerSvc.currentFieldNewValue);
		formChangeLoggerSvc.listOfChanges.push(
					{
						fieldName: formChangeLoggerSvc.currentFieldName, 
						oldValue: formChangeLoggerSvc.currentFieldOldValue,
						newValue: formChangeLoggerSvc.currentFieldNewValue,
						timestamp: new Date()
					})
		}
	}
	
	formChangeLoggerSvc.getChanges = function(){
		return formChangeLoggerSvc.listOfChanges;
	}

	
	formChangeLoggerSvc.onFocus = function(scope, event) {
		
		if (typeof event != "undefined") {
			var dataField;

			//datepicker workaround
			if (event.target)
			 	dataField = event.target;
			 else
			 	dataField = event;

			var fieldName = dataField.getAttribute("ng-model");
			fieldName = fieldName.substring(fieldName.indexOf(".") + 1);
			
			var value = scope.$eval( dataField.getAttribute("ng-model"));
			
			//datepicker workaround
//			var value;
//			if (dataField.value)
//				value = dataField.value;
//			else
//				value = dataField.getElementsByTagName('input')[0].value
			
			formChangeLoggerSvc.enterField(fieldName, value);
		}
	}
	
	formChangeLoggerSvc.onBlur = function(scope, event) {
		if (typeof event != "undefined") {
			var dataField;
			
			if (event.target)
			 	dataField = event.target;
			 else
			 	dataField = event;

			var value = scope.$eval( dataField.getAttribute("ng-model"));
			
			//datepicker workaround
//			var value;
//			if (dataField.value)
//				value = dataField.value;
//			else
//				value = dataField.getElementsByTagName('input')[0].value

			
			formChangeLoggerSvc.exitField(value);		
		}
	}

	
	
	return formChangeLoggerSvc;
});
