﻿;(function(){
	/*
	 * Диалоговое окно для подтверждения смены значения в поле
	 */
	$.fn.selectConfirm = function(options, args) {
		return this.each(function() {
			if (typeof options == "string") {
				var elem = $.data(this, "ui-selectConfirm");
				if (elem) {
					if (args) {
						elem[options].apply(elem, args);
					}
					else {
						elem[options].apply(elem);
					}
				}
			}
			else {
				return $.data(this, "ui-selectConfirm", new $.selectConfirm(this, options)); 
			}
		});
	};
	
	$.selectConfirm = function(container, options) {
		this.element = container;
		this.target = $(this.element);
		this.options = $.extend({}, $.selectConfirm.defaults, options || {});
		
		// Текущее выбранное значение.
		this.prevTargetValue = this.target.val();

		// отвязываем все события от элемента
		var events = $.data(this.element, "events");
		
		for (var type in events) {
			Utils.debug("Event " + type);
			
			if (type == "change") {
				for ( var handler in events[ type ] ) {
					var h = events[ type ][ handler ];
					var data = events[ type ][ handler ].data;
					
					$.event.remove(this.element, type, h);
					$.event.add(this.element, "changeItem", h, data);
				}
			}
		}
		
		var self = this;
		this.target.bind("change", function(ev) { self.showDialog() } );
	};
	
	$.selectConfirm.prototype = {
		
		confirmCallback: function() {
			this.prevTargetValue = this.target.val();
			this.target.trigger("changeItem");
			
		},
		
		cancelCalback: function() {
			this.target.val(this.prevTargetValue);
		},
		
		showDialog: function() {
			var args = new ConfirmationEventArgs(this, this.confirmCallback, this.cancelCalback);
			if (this.options.confirmCallBack) {
				var handler = this.options.confirmCallBack;
				if ($.isFunction(handler)) {
					handler.call(this, args);
				}
			}
			else {
				this.confirmCalback();
			}
		}
	};
	
	$.selectConfirm.defaults = {
		confirmCallBack: null
	};
	
})(jQuery); 
