(function($) {

	state = {}
	dynforms = {}

	/*
	 * Dear Person Shaking Head,
	 * Have fun :P
	 * - Artur
	 */
		
	$.fn.dynform = function(container, preview_state, form_state) {		
		
		this.each(function() {			
			var $this = $(this);
						
			if(!state) {
				state = {}
			}
						
			if(!state[$this.attr('id')]) {
				//fix state if form is opened already
				state[$this.attr('id')] = 'close'
			}
			
			//MMF.ajax.fetch_inline($this, preview_state)
			
			// Toggles States
			$('#'+container).bind('click', function(e) {
				toggle_container($this, this, preview_state, form_state)
			})
			
			
			bind_open_form($this, $('#'+container), preview_state, form_state)
			// Make List...
			dynforms[$this.attr('id')] = {'preview': preview_state}
		})
		
		function toggle_container(container, trigger, preview_state, form_state)
		{					
			// Closing Dynform
			if(state[container.attr('id')] == 'open') {	
				toggle_close(container, trigger, preview_state)
			// Openning Dynform
			} else if (state[container.attr('id')] == 'close') {
				/*
				// Why would we close the other forms? How is that even a desired feature?
				for (dynform in state) {
					if(dynform != container.attr('id')) {
						if(state[dynform] == 'open') {
							toggle_close($('#'+dynform), $('#'+dynform).parent().find('.dyn_edit'), dynforms[dynform]['preview'])
						}
					}
				}
				*/
				toggle_open(container, trigger, form_state, preview_state)
			}
		}
		
		function wire_open_form(container, trigger, preview_state, form_state) {
			/*
			 * This function should run after an 'internal' form is loaded either
			 * on page load or via AJAX. It makes sure that the submit functionality
			 * and cancel button work properly, as well as loading any tooltips.
			 */
			var internal_form = container.find('form').first()
			if (internal_form.length) {
				//this form is open and actually exists
				
				MMF.validation.load_tooltips()
				internal_form_id = internal_form.attr('id')
				//validator currently out of commission here.
				//validator_id = 'validator_'+internal_form_id.replace('form_', '')
				//validator = MMF.validation.validators[validator_id]
				                                      				
				internal_form.find('.form_cancel').bind('click', function(e) {
					toggle_close(container, trigger, preview_state, form_state)
				})
				
				internal_form.bind('submit', function(e) {
					//if(MMF.validation.presubmit_validate(internal_form, validator) == false) {
					//	return false
					//}
					
					callback_submit = function (data) {
						
						if(data == 'success') {
							//special case: form submitted successfully, so close it
							toggle_close(container, trigger, preview_state)
							return false // This is Important!
						} else {
							container.html(data)
							wire_open_form(container, trigger, preview_state, form_state)
						}
					}
					
					MMF.ajax.fetch_inline(container, form_state, callback_submit, undefined,  internal_form.serialize(), 'POST')
					return false // This is Extra Important!
				})
				$(trigger).text('Hide')
				state[container.attr('id')] = 'open'
			}
		}
		
		function bind_open_form(container, trigger, preview_state, form_state) {
			return wire_open_form(container, trigger, preview_state, form_state)
		}
		
		function toggle_open(container, trigger, form_state, preview_state) {

                        callback = function(data) {
				container.html(data)
				return wire_open_form(container, trigger, preview_state, form_state)
			}
			
			MMF.ajax.fetch_inline(container, form_state, callback)
			//MMF.validation.load_tooltips()
			//state[container.attr('id')] = 'open'			
		}
		
		function toggle_close(container, trigger, preview_state) {
			$(trigger).text('Edit')
			MMF.ajax.fetch_inline(container, preview_state)
			
			state[container.attr('id')] = 'close'
			return false
		}
	}
})(jQuery);

(function($) {
	state = {}
	
	/*
	 * Dear Person Shaking Head,
	 * Have fun :P
	 * - Artur
	 */
		
	$.fn.dynform_modal = function(container, preview_state, form_state) {		

		this.each(function() {			
			var $this = $(this);
                        
                        $('#'+container).closest('.module').bind('mouseover', function(e){
                            $('#'+container).show();
                        })

                        $('#'+container).closest('.module').bind('mouseout', function(e){
                            $('#'+container).hide();
                        })

			// Toggles States
			$('#'+container).bind('click', function(e) {
				//console.log('KLICK!', this)
				toggle_modal($this, this, preview_state, form_state)
			})
		})
		
		function toggle_modal(container, trigger, preview_state, form_state)
		{	
			original_container = container			
			form_container = container.find('.dynform_form_container')
			preview_container = container.find('.dynform_preview_container')
			
			callback_open = function(data) {				
				form_container.html(data)
				
				form_title = form_container.find('.form_rule_title')
								
				if(form_title.text().length > 1) {
					form_title_text = form_title.text()
					form_title.remove()
				} else {
					form_title_text = ''
				}
								
				form_container.dialog({draggable:false, modal: true, resizable: false, width: 725, title: form_title_text, zIndex: 9999 })
				form_container.bind('dialogclose', callback_close)
				form_container.dialog('open')
				
				// Le Form Magic
				MMF.validation.load_tooltips()
				internal_form = form_container.find('form')
				
				// I'm honestly surprised this can even work...
				if(internal_form.val().len == 0) {
					internal_form = form_container;
				} else {
					internal_form_id = internal_form.attr('id');
					validator_id = 'validator_'+internal_form_id.replace('form_', '');
					validator = MMF.validation.validators[validator_id];
				}
				
				internal_form.find('.form_cancel').bind('click', function(e){
					form_container.dialog('close')
				})
				
				internal_form.bind('submit', function(e) {
					//if(MMF.validation.presubmit_validate(internal_form, validator) == false) {
					//	return false
					//}

					callback_submit = function (data) {						

						if(data == 'success') {
							form_container.dialog('close');
                                                        form_container.remove();
                                                        return false; // This is Important!
						} else if (data[0] == '_') {
							separator = data.indexOf('_', 1);
							action = data.substring(1, separator);
							parameter = data.substring(separator+1);
							
							if(action == 'redirect') {
								window.location = parameter;
							}
														
						} else {
							form_container.html(data);
							MMF.validation.load_tooltips();
						}
					}
										
					MMF.ajax.fetch_inline(form_container, form_state, callback_submit, undefined,  internal_form.serialize(), 'POST')
					return false // This is Extra Important!
				})
				// 
				
			}
			
			callback_close = function(data) {
				form_container.dialog('destroy')
                                form_container.remove();
				original_container.parent().unbind()
								
				MMF.ajax.fetch_inline(original_container.parent(), preview_state, undefined, undefined, undefined, 'GET', true)
				
				//form_container = container.find('.dynform_form_container')
				//console.log('form_container', form_container)
			}
			
			MMF.ajax.fetch_inline(form_container, form_state, callback_open)
		}
	}
})(jQuery);



/*
 * This is the one function that should be used for modals, and subsequently 
 * inline editing when refactored for supporting that. 
 */

(function($) {
	state = {};

	$.fn.modal = function(invoker, cancel, title, inline_state, modal_state, options) {		
		
		var container = $(this);



		var modal_container = container.find('.modal_modal');
		var inline_container = container.find('.modal_inline');
		
		this.each(function() {	
			initialize();			
		});
		
		function initialize() {
			trigger = container.find('.'+invoker);
			
			if(trigger.length) {

                            if ($(container).find('.'+invoker).hasClass("donothide")) {
                                
                            } else {
                                $(container).bind('mouseover', function(e){
                                    $(container).find('.'+invoker).show();
                                })

                                $(container).bind('mouseout', function(e){
                                    $(container).find('.'+invoker).hide();
                                })
                            }

                            $(trigger).bind('click', function(e) {
                                    toggle_modal(container, trigger, cancel, title, inline_state, modal_state, options);
                                    return false;
                            });
			}
		}
		
		function toggle_modal(container, trigger, cancel, title, inline_state, modal_state, options) {	
			callback_open = function(data) {
				// Kill it with fire...
				if (options !== undefined) {
					if (options.invoke_pre_callback) {
						options.invoke_pre_callback();
					}
					
					if (options.invoke_pre_unset_vars) {
						for (i in options.invoke_pre_unset_vars) {
							//console.log("delete "+options.invoke_unset_vars[i]);
							eval("delete "+options.invoke_pre_unset_vars[i]);
						}
					}			
				}
				
				// Load data into container if provided externally
				if(data.length > 0) {
					modal_container.html(data);
				}
				
				// Determine Title if not provided (and displaying a FormBuilder form)...
				if(title === false) {
					inline_modal_title = modal_container.find('.form_rule_title:first');
									
					if(inline_modal_title.length) {
						title = inline_modal_title.text();
						inline_modal_title.text('');
					} else {
						title = '';
					}
				}
				
				modal_width = 725;
				modal_height = 'auto';
				modal_class = '';
				modal_close_on_escape = false;
				
				// This is an ugly associative expansion but it works...
				if (options !== undefined) {
					if (options.width) {
						modal_width = options.width;
					}
					
					if (options.height) {
						modal_height = options.height;
					}
					
					if (options.css_class) {
						modal_class = options.css_class;
					}
					
					if (options.close_on_escape) {
						modal_close_on_escape = options.close_on_escape;
					}
					
					if (options.unset_contents) {
						inline_container.html('');
					}
				}
				
				// Set modal properties, and trigger so we know if a form 
				// is closed...
				modal_container.dialog({draggable:false, modal: true, resizable: false, width: modal_width, height:modal_height, dialogClass: modal_class, title: title, closeOnEscape: modal_close_on_escape});
				
				/*
				for (var key in options) {
					modal_container.dialog('option', key, options[key]);
					console.log(key, options[key]);
				}
				*/
				
				modal_container.bind('dialogclose', callback_close);
				modal_container.dialog('open');
				
				// Run Post Initialize Hooks...
				if (options !== undefined) {
					if (options.invoke_post_callback) {
						options.invoke_post_callback();
					}
				}
				
				// Fetch Modal's Form
				form = modal_container.find('form');
				
				if(!form.length) {
					// This makes presence tests slightly easier...
					form = false;
				} else {
					// Otherwise do some minor housekeeping tasks for forms...
					MMF.validation.load_tooltips();
					form_id = form.attr('id');
					validator_id = 'validator_'+form_id.replace('form_', '');
					validator = MMF.validation.validators[validator_id];
				}
				
				// Close on "cancel" click...
				modal_container.find('.'+cancel).bind('click', function(e){
					modal_container.dialog('close');
				});
				
				if(!form){
					return;
				}
				
				// Run a submission validator if the form is present and 
				// submitted..
				form.bind('submit', function(e) {

					if(MMF.validation.presubmit_validate(form, validator) === false) {

						return false;
					}
									
					callback_submit = function (data) {		
						if(data == 'success') {
							// Close modal if plain successful response
							modal_container.dialog('close');
							return false; // This is Important!
						} else if (data[0] == '_') {
							// Otherwise do some special tasks, e.g. redirect
							separator = data.indexOf('_', 1);
							action = data.substring(1, separator);
							parameter = data.substring(separator+1);
							
							if(action == 'redirect') {
								window.location = parameter;
							}
														
						} else {
							// Otherwise an error postpack, so display it... 
							form.html(data);
							MMF.validation.load_tooltips();
						}
					};
					
					// Do the actual request...
					MMF.ajax.fetch_inline(modal_container, modal_state, callback_submit, undefined, form.serialize(), 'POST');
					return false; // This is Extra Important!
				});	
			};
			
			callback_close = function(data) {
				if (options !== undefined) {
					if (options.destroy_callback) {
						options.destroy_callback();
					}
					
					if (options.destroy_unset_vars) {
						for (i in options.destroy_unset_vars) {
							eval("if("+options.destroy_unset_vars[i]+" !== undefined) { delete "+options.destroy_unset_vars[i]+"; }");
						}
					}
				}
				
				modal_container.dialog('destroy');
			
				if(modal_state) {
					//modal_container.html('');
				}
				
				if(inline_state) {					
					callback_inline_reset = function(data) {
						modal_container.unbind();
						inline_container.html(data);
						initialize();
					};
					
					MMF.ajax.fetch_inline(inline_container, inline_state, callback_inline_reset, undefined, undefined, 'GET', true);
				}				
			};
			
			
			if(modal_state) {
				// Fancy AJAX View Modal
				MMF.ajax.fetch_inline(modal_container, modal_state, callback_open);
			} else {
				callback_open();
			}
		}
	};
})(jQuery);
