// todo: keep responses to the closest parent..   either a tab, or the dialog itself.. 
// todo: test callbacks!
(function($){
     $.fn.modalAjax = function(options) {
        // SETUP private variabls;
    	var el = this;
    	var thisDialog = '';
    	var editor = '';
    		
        // setup options
    	var defaultOptions = {
    		title: '',
    		width: '',
			height: '',
			initFunction: function(){},
			destroyFunction: function(){},
			initTabs: false,
			initAjaxForm: false, 
			autoOpen: false,
			ajaxFormTarget: '',
			ajaxFormSuccess: function(){},
			ajaxFormClose: false,
			validateData: {}
         };
    	
         var options = $.extend( defaultOptions, options);
         // SETUP private functions;
         var initialize = function() {
        	 var opts = options
    			$(el).livequery('click', function(e){ 	
    				el.show(this); 
    			});	
    			if (opts.autoOpen == true){ 
    				$(document).ready(function(){
    					el.show();
    				});
    			}
    			return el;
         };
        
         var create = function(e){ 
        	 var dialogOpts = {
  					modal: false,
  					bgiframe: false,
  					draggable: true,
  					autoOpen: true,
  					autoResize: true,
  					resizable: false,
  					position: 'center center',
  					title: options.title,
  					open: function(event, ui){	populate(e);	},
  					beforeClose: function(event,ui){ options.destroyFunction();	},
  					close: function(event,ui){	destroy();  }
  			};
  			
  			thisDialog =  $('<div></div>').dialog(dialogOpts);	 
  			$(thisDialog).html('<div align="center"><img src="/images/progress.gif"><br>Loading...</div>');
  			

  		// load "ajax" links in the current element
			$(thisDialog).find('a.ajax').livequery('click', function() {
         		$(thisDialog).load(this.href,'',function(){	});
         		return false;
     		});
		// start tabs!	
			$(thisDialog).find('.tabs').livequery( function(){
				$(thisDialog).find('.tabs').tabs(); 
			});
		
		// init ajaxForm plugin, validate plugin and ckeditor 
			if (options.initAjaxForm == true) {
				
				if (options.ajaxFormTarget == ''){
					ajaxFormTarget = $(thisDialog);
				} else { 
					ajaxFormTarget = options.ajaxFormTarget;
					ajaxFormTarget = ajaxFormTarget.replace("!alt!", $(e).attr('alt'));		
					ajaxFormTarget = ajaxFormTarget.replace("!rel!", $(e).attr('rel'));
				}
				$(thisDialog).find('.ajaxform').livequery( function(){
					var formoptions = { 
							beforeSubmit: function(arr, form, options){
						 		return $(form).valid();
							},
					        success:	function(responseText, statusText, xhr, $form)  { 
								$(ajaxFormTarget).html(responseText)
								options.ajaxFormSuccess(responseText, statusText, xhr, $form);
								if (options.ajaxFormClose == true){
									destroy();
								}
							}, 
					        type:      'post'
					}; 
					$(thisDialog).find('.ajaxform').ajaxForm(formoptions);
					
					var localValidateData = {
							//errorLabelContainer : $(thisDialog).find('.messageBox'), 
							//wrapper: 'li',
							//showErrors: function(){
							//	$(thisDialog).find('.messageBoxContainer').show();
							//	this.defaultShowErrors();
							//}
					};
					var validateData  = $.extend( localValidateData, options.validateData);
					$(thisDialog).find('.ajaxform').validate( validateData );	
				});
				
				$(thisDialog).find('.ckeditor').livequery( function(){
					$(thisDialog).find('.ckeditor').ckeditor( function() { 
		 				 editor = $(thisDialog).find('.ckeditor').ckeditorGet(); 
		 		 	},{
						filebrowserBrowseUrl : '/cffm/cffm.cfm?editorType=cke&EDITOR_RESOURCE_TYPE=file',
						filebrowserImageBrowseUrl : '/cffm/cffm.cfm?editorType=cke&EDITOR_RESOURCE_TYPE=image',
						filebrowserFlashBrowseUrl : '/cffm/cffm.cfm?editorType=cke&EDITOR_RESOURCE_TYPE=flash',
						filebrowserUploadUrl : '/cffm/cffm.cfm?action=QuickUpload&editorType=cke&EDITOR_RESOURCE_TYPE=file',
						filebrowserImageUploadUrl : '/cffm/cffm.cfm?action=QuickUpload&editorType=cke&EDITOR_RESOURCE_TYPE=image',
						filebrowserFlashUploadUrl : '/cffm/cffm.cfm?action=QuickUpload&editorType=cke&EDITOR_RESOURCE_TYPE=flash'
					 });
				});
			}
         };
         
         var populate = function(e){
        	 var opts = options;
        	 var url = '';
        	 var title = '';
        	
        		 url = opts.url.replace("!rel!", $(e).attr('rel'));
            	 url = url.replace("!alt!", $(e).attr('alt'));
            	 url = url.replace("!title!", $(e).attr('title'));
				title = opts.title.replace("!alt!", $(e).attr('alt'));
            	 title = title.replace("!rel!", $(e).attr('rel'));
            	 title = title.replace("!title!", $(e).attr('title'));
			
        	 $.get(url,function(data){  
        		
        		 //$(thisDialog).html('<div class="messageBoxContainer ui-state-error ui-corner-all"><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span><b>Warning:</b> Your form has the following errors:<br><ul class="messageBox"></ul></div>' + data);	    // TODO: handle errors
        		 $(thisDialog).html( data);	    // TODO: handle errors
        		 
				if ( opts.height != 'undefined' && opts.height != ''){	$(thisDialog).dialog( "option", "height", opts.height ); }
				if ( opts.width != 'undefined' && opts.width != ''){	$(thisDialog).dialog( "option", "width", opts.width );  } 
				$(thisDialog).dialog('option', 'position', 'center');	
				$(thisDialog).dialog('option', 'title', title);	
				
				opts.initFunction();

        	 });
         }
         
        var destroy = function(){ 
        	options.destroyFunction();
        	if (options.initTabs == true){			$(thisDialog).find('.tabs' ).tabs('destroy');	}
			if (options.initAjaxForm == true){		
				try { 
					editor = $(thisDialog).find('textarea.ckeditor');
					if (editor.length){
						$.each( editor, function(index, value){
							var editorID = $(this).attr("id");
							$('#'+editorID).ckeditorGet().destroy();
				            
						}); 
					}
				} catch(err) { }  
				
			}
			
			$(thisDialog).html(''); 
			$(thisDialog).dialog("destroy");
			
        };
        
         // PUBLIC functions
         this.show = function(e) {
        	try{ destroy(); }   catch(err) {	}
        	create(e);
        	
         };
        
         this.close = function() {
        	 alert('close called programatically'); // TODO: close the dialog! 
         };

         this.update = function(data){
        	 $(thisDialog).html(data);	 
         };
         
         this.getOptions = function() {  return options;   };

         return initialize();
     }
 })(jQuery);
