/*
	Copyright (c) 2006-2007, ePages GmbH
	All Rights Reserved.
*/
dojo.provide("epages.widget.Validateinput");
dojo.require('epages.io.translation');
dojo.require("epages.uimessagehandler");
dojo.require("epages.validate.css");
dojo.require("epages.validate.number");
dojo.require("epages.validate.date");
dojo.require("epages.html.element");
dojo.require("epages.widget.FormElement");
dojo.require("dijit._Widget");

(function(dj){

	var handleID = 0;
	
	var _validateInput = {
		/**
		* public properties
		*/
		validationType  : "",
		errorBox        : null,
		inputError      : false,
		undoWidgetId    : 'undoWidget',
		dictionary      : epages.io.dictionary,
		allowEmpty      : '0',
		/**
		 * settings: String 
		 * comma seperated parameters will be passed to the validate function
		 * as hash object (processed from string e.g. settings="min:10,max:100" becomes
		 * { min: 10, max: 100 } [Object])
		 */
		settings        : '',

		postCreate: function() {
			this.validationType = this.domNode.getAttribute('validationType') || this.validationType;
			this.undoWidgetId   = this.domNode.getAttribute('undoWidgetId') || this.undoWidgetId;
			this.settings       = this.domNode.getAttribute('settings') || this.settings;
			this.allowEmpty     = this.domNode.getAttribute('allowEmpty') || this.allowEmpty;
		
			//this.inherited("postCreate", arguments);
			this.allowEmpty = epages.string.toBoolean(this.allowEmpty);

			dojo.addOnLoad(this, "_appendEvent");

			//create Error-Attribute
			var atr = document.createAttribute("ep_error");
			atr.nodeValue = "0";
			this.domNode.setAttributeNode(atr);
			if (dojo.isString(this.settings) && this.settings.length > 0) {
			  this.settings = dojo.fromJson('{' + this.settings + '}');
			}
		},
		
		connect: function( node, event, fn ){
			handleID++;
			this.addHandle( 'validateInput.handle_'+handleID , node, event, fn );
			this.connectHandle( 'validateInput.handle_'+handleID );
		},

		_appendEvent: function() {
			if(this.validationType != "") {
				this.connect(this.domNode, 'onkeyup', '_keyupValidation');
				this.connect(this.domNode, 'onclick', '_keyupValidation');
				this.connect(this.domNode, 'onchange', '_onChange');
				this.connect(this.domNode, 'onkeyup', '_onChange');
				this.connect(this.domNode, 'onclick', '_onChange');
			}
		},

		_validate: function() {
			var value = this.domNode.value;
			if (value !== undefined) {
  			if (this.allowEmpty && value == ''){
  				return true;
  			}
				switch (this.validationType.toLowerCase()) {
					case 'integer':
						var result = epages.validate.number.isInteger(value, this.settings);
						break;
					case 'size':
						var result = epages.validate.css.isSize(value, this.settings);
						break;
					case 'color':
						// comment.translate:NO_COLOR_VALUE
						var result = epages.validate.css.isColor(value, this.settings) ? true : "NO_COLOR_VALUE";
						break;
					case 'date':
						var result = epages.validate.date.isDate(value, this.settings);
						break;
					case 'time':
						var result = epages.validate.date.isTime(value, this.settings);
						break;
					case 'datetime':
						var result = epages.validate.date.isDateTime(value, this.settings);
						break;
					default:
						console.warn("Unknown validationType " + this.validationType + " for widget " + this.id);
						break;
				}
				return result;
			}
		},

		_keyupValidation: function() {
			var result = this._validate();
			if(result == true){
				//remove Error
				this._removeError();
			} else {
				//add Css-Error-Class
				this._setError();
			}

			if (this.undoWidgetId !== undefined) {
				if ($$(this.undoWidgetId) !== undefined) {
					$$(this.undoWidgetId).undoObject.validateInput(this.domNode);
				} else {
					console.warn('undoWidget "' + this.undoWidgetId + '" does not exist. ('+this.declaredClass+')');
					this.undoWidgetId = undefined;
				}
			}
		},

		_setError: function() {
			dojo.addClass(this.domNode, "DialogError");
			//set Error-Attribute
			this.domNode.setAttribute("ep_error", "1");
			dojo.publish(this.id+'/Error',[{ id: this.id, errorState: true }]);
		},

		_removeError: function() {
			dojo.removeClass(this.domNode, "DialogError");
			//remove Error-Box
			if(this.domNode.getAttribute("ep_error") == "1") {
				dojo.publish("uimessage/hide", []);
			}
			//reset Error-Attribute
			this.domNode.setAttribute("ep_error", "0");
			dojo.publish(this.id+'/Error',[{ id: this.id, errorState: false }]);
		},

		_onChange: function() {
			//set 'px' as default-unit
			var result = this._validate();
			if (result != true) {
				//display Error-Box-Widget
				var position = $E(this.domNode).getAbsolutePosition();

				dojo.publish("uimessage/show", ["", this.dictionary.get(result, this.settings), "Bubble", {
					typeClass: "Warning",
					sizeClass: "Small",
					x: position.x,
					y: (position.y + this.domNode.clientHeight + 4)
				}]);
			}
			else {
				//hide Error-Box
				// dojo.publish("uimessage/hide", []);
			}
			this._keyupValidation();
		}
	};

	epages.widget.Validateinput = function( options, domNode ){
		this.destroy();
		
		var widget = new epages.widget.FormText( options, domNode );
		
			widget = dj.mixin( widget, _validateInput );
			
			widget.postCreate();

		return widget;
	};
	epages.widget.Validateinput.prototype = new dijit._Widget();

})(dojo);