// Form Field
$.ui.component.subclass('ui.form_field', {
	_init: function() {this.create();},
	getFormFieldWidgetObject: function() {return this.element.find(this.options.formFieldWidget.selector);},
	callFormFieldWidget: function(method, params) {
		$.plugin(this.getFormFieldWidgetObject(), this.options.formFieldWidget.widget, method, params);
	},
	createFormFieldWidget: function() {this.callFormFieldWidget()},
	destroyFormFieldWidget: function() {this.callFormFieldWidget('destroy')},
	create: function() {this.createFormFieldWidget();},
	destroy: function() {this.destroyFormFieldWidget();}
});
$.ui.form_field.defaults.extend({
	widget: 'form_set', 
	formFieldWidget: {widget: 'form_field_widget', selector: '.form-field-widget'}
});
// Form Field Widget
$.ui.component.subclass('ui.form_field_widget', {
	_init: function() {this.create();},
	getHeaderObject: function() {return this.element.find(this.options.selector.header);},
	getBodyObject: function() {return this.element.find(this.options.selector.body);},
	getFooterObject: function() {return this.element.find(this.options.selector.footer);},
	// Header
	createHeader: function() {}, destroyHeader: function() {},
	// Body
	createBody: function() {}, destroyBody: function() {},
	// Footer
	createFooter: function() {}, destroyFooter: function() {},
	create: function() {this.createHeader();this.createBody();this.createFooter();},
	destroy: function() {this.destroyHeader();this.destroyBody();this.destroyFooter();}
});
$.ui.form_field_widget.defaults.extend({
	widget: 'form_field_widget',
	selector: {
		header: '.form-field-widget-header',
		body: '.form-field-widget-body',
		footer: '.form-field-widget-footer'
	}
});
// Advanced Multiple Checkbox Input Form Field
$.ui.form_field.subclass('ui.advanced_multiple_checkbox_input_form_field', {});
$.ui.advanced_multiple_checkbox_input_form_field.defaults.extend({
	widget: 'advanced_multiple_checkbox_input_form_field',
	formFieldWidget: {widget: 'advanced_multiple_checkbox_input_form_field_widget', selector: '.form-field-widget'}
});
// Advanced Multiple Checkbox Input Form Field Widget
$.ui.form_field_widget.subclass('ui.advanced_multiple_checkbox_input_form_field_widget', {
	// Header
	getCheckAllButtonObject: function() {return this.getHeaderObject().find('.check-all-button');},
	getUnCheckAllButtonObject: function() {return this.getHeaderObject().find('.uncheck-all-button');},
	createHeader: function() {
		this._super();
		var self = this;
		this.getCheckAllButtonObject().each(function() {
			$(this).unbind('click');$(this).bind('click', function () {self.checkAll();});
		});
		this.getUnCheckAllButtonObject().each(function() {
			$(this).unbind('click');$(this).bind('click', function () {self.uncheckAll();});
		});
	},
	destroyHeader: function() {
		this._super();
		this.getCheckAllButtonObject().each(function() {$(this).unbind('click');});
		this.getUnCheckAllButtonObject().each(function() {$(this).unbind('click');});
	},
	// Body
	createBody: function() {this._super();},
	destroyBody: function() {this._super();},
	checkAll: function() {this.getBodyObject().find('ul').find('li').find('input').attr('checked', 'checked');},
	uncheckAll: function() {this.getBodyObject().find('ul').find('li').find('input').attr('checked', '');}
});

// Form
$.ui.component.subclass('ui.form', {

	_init: function() {
		var self = this,
			options = this.options,
			form = this.form = self.element,
			formHeader = this.formHeader = form.find(options.headerSelector),
			formBody = this.formBody = form.find(options.bodySelector),
			formFooter = this.formFooter = form.find(options.footerSelector),
			formFieldSet = this.formFieldSet = formBody.find(' > form').find(options.fieldSetSelector),
			formButtonSet = this.formButtonSet = formBody.find(options.buttonSetSelector);
		this.create();
	},
	hide: function(event) {this.form.hide();},
	show: function(event) {this.form.show();},
	close: function() {this.hide();},
	reset_: function() {return this.form.find('form').clearForm();},
	reset: function() {
		if (confirm('Clear all entered information?')) return this.reset_(); else return false;
	},
	create: function(event) {
		this.createHeader();
		this.createBody();
		this.createFooter();
	},
	destroy: function(event) {
		this.destroyHeader();
		this.destroyBody();
		this.destroyFooter();
	},
	getBodyObject: function(selector) {return this.formBody.find(selector);},
	// Header
	createHeader: function() {
		var self = this;
		this.formHeader.find('.close').each(function() {
			$(this).unbind('click');
			$(this).bind('click', function() {self.close();});
		});
	},
	destroyHeader: function() {
		this.formHeader.find('.close').each(function() {$(this).unbind('click');});
	},
	// Body
	createBody: function() {
		this.createFieldSet();
		this.createButtonSet();
	},
	destroyBody: function() {
		this.destroyButtonSet();
		this.destroyFieldSet();
	},
	// Footer
	createFooter: function() {},
	destroyFooter: function() {},
	createAutoCompleteField: function() {
		this.formFieldSet.find('.auto-complete-text-input-form-field,.auto-complete-multiple-checkbox-input-form-field').each(function () {
			var inputObject = $(this).find('.auto-complete-input');
			inputObject.bind('focusin', function () {
				$(this).removeClass('auto-complete-default-input');
			});
			inputObject.bind('focusout', function () {
				if (!$(this).val()) $(this).removeClass('auto-complete-default-input').addClass('auto-complete-default-input');
				else $(this).removeClass('auto-complete-default-input');
			});
			if (!inputObject.val()) {
				inputObject.addClass('auto-complete-default-input');
			}else{
				inputObject.removeClass('auto-complete-default-input');
			}
		});
	},
	// FieldSet
	createFieldSet: function() {
		var self = this;
		this.formFieldSet.find('.help').tooltip();
		this.formFieldSet.find('.error').each(function() {
			$(this).unbind();
			$(this).bind('click', function() {$(this).fadeOut(500);});
		});
		this.formFieldSet.find('.messager').each(function() {
			var object = $(this);
			object.unbind();
			object.bind('click', function() {$(this).slideUp('slow');});
		});
		this.formFieldSet.find('.date-pop-up-form-field').each(function () {
			$(this).find('input').attr('id', $(this).find('input').attr('id') + Math.floor(Math.random() * 1000000));
			$(this).find('input').datepicker({changeMonth: true, changeYear: true});
		});
		this.formFieldSet.find('.advanced-multiple-checkbox-input-form-field').advanced_multiple_checkbox_input_form_field();
		this.createAutoCompleteField();
		this.formFieldSet.find('.auto-complete-text-input-form-field').each(function () {
			var inputObject = $(this).find('.auto-complete-input');
			inputObject.autocomplete(
				inputObject.attr('url_'),
				{maxItemsToShow: 10, minChars: 1, extraParams: {autocomplete: '1'},
				onFindValue: function (li) {
					self.formFieldSet.find('#' + inputObject.attr('id') + '_hidden').val(li.extra[0])
					if(li.extra[1]){
						inputObject.val(li.extra[1]);
 					}
				},
				onItemSelect: function (li) {
					this.onFindValue(li);
					inputObject.focus();
				},
				formatItem: function (row, i, num) {return row[0];}
			});
		});
		this.formFieldSet.find('.auto-complete-multiple-text-input-form-field').each(function () {
			var inputObject = $(this).find('.auto-complete-input');
			inputObject.autocomplete(
				inputObject.attr('url_'),
				{multiple: true, matchContains: true, maxItemsToShow: 10, minChars: 1, extraParams: {autocomplete: '1'},
				onFindValue: function (li) {
					self.formFieldSet.find('#' + inputObject.attr('id') + '_hidden').val(li.extra[0])
					if(li.extra[1]){
						inputObject.val(li.extra[1]);
 					}
				},
				onItemSelect: function (li) {
					this.onFindValue(li);
					inputObject.focus();
				},
				formatItem: function (row, i, num) {return row[0];}
			});
		});
		this.initAutoComplete();
		this.initMultiFile();
		this.form.find('form').unbind('keypress');
		this.form.find('form').bind('keypress', function (event) {
			if (event.keyCode == 13) {
				if (event.target && event.target.tagName && (String(event.target.tagName).toUpperCase() != 'TEXTAREA')) {
					self.submit();
					return false;
				} else return true;
			}
		});
		Cufon.replace('h1, h2, h3');
	},
	initAutoComplete: function(){
		this.formFieldSet.find('.auto-complete-multiple-checkbox-input-form-field').each(function () {
			var inputObject = $(this).find('.auto-complete-input');
			var autocompleted = [];
			var ulObject = $(this).find('ul');
			$(this).find('a.clear').bind('click', function() {
				ulObject.html('');
				inputObject.val('').focus();
				autocompleted = [];
			});
			inputObject.autocomplete(
				inputObject.attr('url_'), {
					maxItemsToShow: 10, minChars: 1, extraParams: {autocomplete: '1'},
					onItemSelect: function (li) {
						var val = '';
						if (li == null) val = 'No Item Selected!';
						if (li.extra) val = li.extra[0];
						else val = li.selectValue;
						if ($.inArray(val, autocompleted) == -1) {
							autocompleted.push(val);
							ulObject.append('<li>' +
								'<input class="checkbox" type="checkbox" checked="checked" name="' + inputObject.attr('name_') + '" value="' + val + '"/>' +
								'<label>' + val + '</label></li>');
						} else alert('Selected item already added!');
						inputObject.val('').focus();
					},
					formatItem: function (row, i, num) {return row[0];}
				}
			);
		});
	},
	initMultiFile: function(){ 
        var self = this; 
        this.formFieldSet.find('.multiple-file-input-form-field input').each(function(){ 
            var id = (self.form.hasClass('add-form')) ? 'add': 'edit'; 
            id = $(this).attr('id')+'_'+id; 
            $(this).attr('id', id); 
            $('#'+id).MultiFile(self.getMultiFileOptions(this)); 
        }); 
    },
	getMultiFileOptions: function(obj){
		var self = this;
		var options = {
				accept:self.getAllowedExt(obj),
				max:self.getMaxFile(), 
				STRING: {
					remove:'<img src="/assets/img/component/form/delete.gif">',
					selected:'Selecionado: $file',
					denied:'$ext file is not allowed',
					duplicate:'$file is already selected'
					}
				};
		return options;
	},
	getAllowedExt: function(obj){
		return $(obj).attr('ext');
	},
	getMaxFile:function(){
		return 10;
	}, 
	updateMultiFiles:function (){
		this.formFieldSet.find('.multiple-file-input-form-field').each(function(){
			var name = $(this).find('input').attr('name');
			$(this).find('input').each(function(i){
				$(this).attr('name',name+'-'+i);
				});
		});
	},
	destroyFieldSet: function() {
		this.formFieldSet.find('.error').each(function() {$(this).unbind();});
		this.formFieldSet.find('.messager').each(function() {$(this).unbind();});
		this.formFieldSet.find('.messager').remove();
		this.formFieldSet.find('.date-pop-up-form-field').each(function () {
			$(this).find('input').datepicker('destroy');
		});
		this.formFieldSet.find('.advanced-multiple-checkbox-input-form-field').advanced_multiple_checkbox_input_form_field('destroy');
	},
	recreateFieldSet: function(content) {
		this.destroyFieldSet();
		this.formFieldSet.html(content);
		this.createFieldSet();
	},
	// Button Set
	createButtonSet: function() {
		var self = this;
		this.formButtonSet.find('.submit').each(function() {
			$(this).bind('click', function() {self.submit();return false;});
		});
		this.formButtonSet.find('.reset').each(function() {
			$(this).bind('click', function() {self.reset();return false;});
		});
		this.formButtonSet.find('.close').each(function() {
			$(this).bind('click', function() {self.close();return false;});
		});
	},
	destroyButtonSet: function() {
		this.formButtonSet.find('.submit').each(function() {$(this).unbind('click');});
		this.formButtonSet.find('.reset').each(function() {$(this).unbind('click');});
		this.formButtonSet.find('.close').each(function() {$(this).unbind('click');});
	},

	getURL: function() {return this.form.find('form').attr('action');},
	getPageOptions: function() {return {page: this.options.page};},
	callPage: function(method, params) {
		var options = this.getPageOptions();
		if (options && options.page && options.page.widget && options.page.object)
			$.plugin(options.page.object, options.page.widget, method, params);
	},

	hasParentOptions: function() {
		return (this.options.parent && this.options.parent.widget && this.options.parent.object) ? true : false;
	},
	getParentOptions: function() {return this.options.parent;},
	callParent: function(method, params) {
		if (this.hasParentOptions()) {
			$.plugin(this.getParentOptions().object, this.getParentOptions().widget, method, params);
		}
	},

	submitHandler: function(responce) {
		if (responce) {
			if (responce.redirect_url) {
				if (responce.redirect_url == 'current') return window.location.reload(true);
				else return window.location = responce.redirect_url;
			}
			if (responce.html) {
				if (responce.html.fieldset) this.recreateFieldSet(responce.html.fieldset);
			}
		}
	}, 
	post: function(func, query) {
		var url = this.getURL();
		if (query) url += query;
		var container = this.form;
		$.request({url: url, type: 'post', form: this.form.find('form'), container: container, scope: this, func: func});
	}, 
	cmd: function(query, handler, container) {
		var url = this.getURL();
		if (query) url += '/' + query;
		$.request({url: url, scope: this, func: handler, container: container, arguments: {query: query}});
	}, 
	submit: function(query) {this.updateMultiFiles();this.post(this.submitHandler, query);}
});
$.ui.form.defaults.extend({
	headerSelector: ' > .form-header', 
	bodySelector: ' > .form-body', 
	footerSelector: ' > .form-footer', 
	fieldSetSelector: '.form-fieldset', 
	buttonSetSelector: ' > .form-buttonset', 
	dialog: false
});
// Page Form
$.ui.form.subclass('ui.page_form', {

	hasPageOptions: function() {
		return (this.options.page && this.options.page.widget && this.options.page.object) ? true : false;
	},
	getPageOptions: function() {return this.options.page;},
	callPage: function(method, params) {
		if (this.hasPageOptions()) {
			$.plugin(this.getPageOptions().object, this.getPageOptions().widget, method, params);
		}
	},
	submitHandler: function(responce) {
		if (this.hasPageOptions()) {
			if (responce) {
				if (responce.redirect_url) this.callPage('loadBodyContent', [responce.redirect_url]);
				if (responce.html && responce.html.fieldset) this.recreateFieldSet(responce.html.fieldset);
			}
		} else this._super(responce);
	}
});
// Rich Text Field Form
$.ui.form.subclass('ui.rich_text_field_form', {
	
	hasPageOptions: function() {
		return (this.options.page && this.options.page.widget && this.options.page.object) ? true : false;
	},
	getPageOptions: function() {return this.options.page;},
	callPage: function(method, params) {
		if (this.hasPageOptions()) {
			$.plugin(this.getPageOptions().object, this.getPageOptions().widget, method, params);
		}
	},
	submitHandler: function(responce) {
		if (this.hasPageOptions()) {
			if (responce) {
				if (responce.redirect_url) this.callPage('loadBodyContent', [responce.redirect_url]);
				if (responce.html && responce.html.fieldset) this.recreateFieldSet(responce.html.fieldset);
			}
		} else this._super(responce);
	}, 
	getEditorStyleSheet: function() {
		return this.formFieldSet.find('.richtext').attr('stylesheet_');
	},
	getEditorConfig: function() {
		var style_sheet = this.getEditorStyleSheet();
		return {
			mode : "specific_textareas",
			editor_selector : "richtext",
			theme : 'advanced',
			plugins : "noneditable,safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "charmap,emotions,iespell,media,advhr,fullscreen",
			//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			//theme_advanced_statusbar_location : "bottom",
			entity_encoding : "raw",
			content_css : style_sheet,
			theme_advanced_resizing : true,
			auto_resize: true,
			convert_urls : false, 
			valid_elements: '*[*]'
		};
	},
	// FieldSet
	toggleEditors: function() {
		this.formFieldSet.find('.richtext').each(function () {
			var id = $(this).attr('id');
			if (tinyMCE) {
				if (tinyMCE.getInstanceById(id) == null)
					tinyMCE.execCommand('mceAddControl', false, id);
				else
					tinyMCE.execCommand('mceRemoveControl', false, id);
			}
		});
	},
	// FieldSet
	createFieldSet: function() {
		this._super();
		var self = this;
		this.formFieldSet.find('.richtext').each(function () {
			if (tinyMCE) tinyMCE.init(self.getEditorConfig());
		});
		this.formFieldSet.find('.toggle-editor').each(function() {
			$(this).bind('click', function() {
				self.toggleEditors();
			});
		});
	},
	destroyFieldSet: function() {
		this._super();
		this.formFieldSet.find('.richtext').each(function () {
			if (tinyMCE) {
				var editor = tinyMCE.get($(this).attr('id'));
				if (editor) tinyMCE.remove(editor);
			}
		});
		this.formFieldSet.find('.toggle-editor').each(function() {$(this).unbind('click')});
	},
	submit: function(query) {
		this.formFieldSet.find('.richtext').each(function () {
			tinyMCE.execCommand('mceToggleEditor', true, $(this).attr('id'));
		});
		this._super(query);
	}, 
	reset_: function() {
		this.formFieldSet.find('.richtext').each(function () {
			tinyMCE.execCommand('mceToggleEditor', true, $(this).attr('id'));
		});
		this.form.find('form').clearForm();
		this.formFieldSet.find('.richtext').each(function () {
			tinyMCE.execCommand('mceToggleEditor', false, $(this).attr('id'));
		});
	}
});