var XApp_controls = function(xobj, options) {
	
	var plugin_name = 'controls';
	
	var plugin = function(xobj, options){
		// __construct();
		
		XApp_plugin.apply(this, arguments);
	};
	
	plugin.prototype = $.extend(new XApp_plugin.fn.onload(plugin_name), xobj, {
		
		init: function()
		{
			XApp_plugin.fn.init.apply(this, arguments);
			
			this.initInputs();
			this.initLinksButtons();
			this.initTips();
			
			return this;
		},
		
		initTips: function()
		{
			$('a, label, button, span.tip').filter(':not(.notipsy)').tipsy();
			$('img').each(function(){
				if(!$(this).parent().is('a')) {
					$(this).tipsy();
				} else {
					$(this).attr('title','');
				}
			})
		},		
		
		initInputs: function()
		{
			$('input, select, textarea', this.$el).bind('focus', function()
			{
				$(this).addClass('focus').parent('.inputOuter').addClass('focus');
			})
			.bind('blur', function()
			{
				$(this).removeClass('focus').parent('.inputOuter').removeClass('focus');
			});
			
			return this;
		},
		
		initLinksButtons: function()
		{
			
			var x = this;
			
			$("a[rel=external]", this.$el).attr('target', '_blank');
			
			$("a.dialog, button.dialog", this.$el).each(function(){
				var href = '';
				var data = [];
				
				if( $(this).is('a') ){
					href = $(this).attr('href');
				}
				
				/**
				 * Check metadata
				 */
				var meta = $(this).metadata() || {};
				if( meta.url ) {
					href = meta.url;
				}
				
				var self = this;
				
				$(this).click(function(){
					
					var showDlg = function() {
						XApp('<div />').plugin('dialog', {dlg:{modal: true}}).load(href);
					};
					
					if( meta.ask ) {
						XApp().ask(showDlg, meta.ask);
					} else {
						showDlg();
					}
					
					return false;
				});
			});
			
			$("a.ajaxed, button.ajaxed", this.$el).each(function(){
				var o = $(this).metadata();
				
				$(this).click(function(){
					
					var options = $.extend({
						url: $(this).attr('href')
					}, typeof o.ajax != 'object' ? {} : o.ajax);
					
					var sendRequest = function() {
						XApp().ajax(options);
					};
					
					var meta = $(this).metadata() || {};
					
					if( meta.ask ) {
						XApp().ask(sendRequest, meta.ask);
					} else {
						sendRequest();
					}
					
					return false;
				});
			});
			
			$("a.button, button.button", this.$el).each(function(){
				var o = $(this).metadata();
				if( o.icon ) {
					if(! o.icons) {
						o.icons = {};
					}
					
					o.icons.primary = o.icon;
				}
				$(this).button(o);
			});
			
			return this;
		}
	});
		
	return new plugin(xobj, options);
};
