/* Abstract dialog class for ajax Google Closure dialogs powered by jQuery */

(function($) {

    $.dialog = function(options) {
        $.extend(this, {}, $.dialog.defaults, options);
        
        // Create a general ajax-loader, if not already in DOM
        this.ajaxloader = $('#dialog_ajaxloader');

        if (!this.ajaxloader.length)
        {
            $('body').append('<img src="' + this.loader_img_url + '" id="dialog_ajaxloader" style="display: none" />');
            this.ajaxloader = $('#dialog_ajaxloader');
        }
        
        this.google_dialog = new goog.ui.Dialog();
        this.google_buttons = {}
        this.is_showing = false;
        
        // Default dialog button events
        this.google_dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK_CANCEL);
        this.google_dialog_default_event = function(e) {
            if (e.key == 'ok') { this.default_submit_action(this); } // If button is ok
            else { this.default_cancel_action(this); } // If button cancel
            return false;
        }
    };
    
    $.dialog.defaults = {
        title          : '',
        content_url    : '',
        content_data   : {},
        content        : '',
        show_callback  : function (dialog) {},
        hide_callback  : function (dialog) {},
        loader_img_url : '/images/general/ajax-loader.gif',
        default_submit_action : function (dialog) { },
        default_cancel_action : function (dialog) { },
        buttons        : {}
    };
    
    $.dialog.prototype = {
        show_loader : function() {
            this.ajaxloader.show();
        },
        
        hide_loader : function() {
            this.ajaxloader.hide();
        },

        show : function() {
            this.refresh();
        },
    
        run_dialog : function(data) {
            dialog = this
            
            dialog.google_dialog.setContent(data);
   		    
   		    // Remove loader
   		    dialog.hide_loader();

            dialog.google_dialog.setVisible(true);

            // Hide buttons
   		    $('.modal-dialog-buttons').hide(); //each(function () { $(this).hide(); });
   		    
            dialog.show_callback(dialog);
            
            
            //dialog.setButtonSet(null);
            
            // Remove existing events
            goog.events.unlisten(dialog.google_dialog, goog.ui.Dialog.EventType.SELECT, dialog.google_dialog_default_event, false, dialog);
        
            for (button_id in dialog.google_buttons)
            {
                goog.events.unlisten(dialog.google_buttons[button_id].control, goog.ui.Component.EventType.ACTION, dialog.google_buttons[button_id]);
            }
			
            // Listen to default button events
            goog.events.listen(dialog.google_dialog, goog.ui.Dialog.EventType.SELECT, dialog.google_dialog_default_event, false, dialog);

            // Custom buttons - Render and add events
            dialog.google_buttons = {}
            for (button_id in dialog.buttons) {
                dialog.google_buttons[button_id] = new Object();
                dialog.google_buttons[button_id].id = button_id;
                dialog.google_buttons[button_id].control = goog.ui.decorate(goog.dom.getElement(button_id));
                dialog.google_buttons[button_id].control.addClassName(button_id);
                //alert(dialog.google_buttons[button_id].control.getExtraClassNames());
                dialog.google_buttons[button_id].handleEvent = function(e) { dialog.buttons[e.target.getExtraClassNames()](dialog); } //
                //goog.events.unlisten(dialog.google_buttons[button_id], goog.ui.Component.EventType.ACTION);
                goog.events.listen(dialog.google_buttons[button_id].control, goog.ui.Component.EventType.ACTION, dialog.google_buttons[button_id]);
			}
        },
    
        refresh : function() {
            // Shortcut to dialog to make it work in ajax functions
            dialog = this

            // Display loader
            dialog.show_loader();
            
            dialog.google_dialog.setTitle(dialog.title);
            //dialog.google_dialog.setDisposeOnHide(true);
            //dialog.google_dialog.setBackgroundElementOpacity('inherit');
            //dialog.google_dialog.setModal(false);
            //dialog.google_dialog.setDraggable(false);
            //dialog.google_dialog.setContent('');
            //dialog.google_dialog.setVisible(true);
            
            if (dialog.content_url != '')
            {
                // Do ajax get-call to login url to get form-contents
                dialog.ajaxLoader = $.ajax({
               		type    : "GET",
               		async   : false,
               		url		: dialog.content_url,
               		data    : dialog.content_data,
               		success : function(data) {
               		    dialog.run_dialog(data);
               	    },
               	    error : function(data) {
               	        dialog.hide_loader();
               	        alert('Ett okänt fel har inträffat. Rapportera felet till en administratör.'); 
               	    }
               	});
            }
            else
            {
                dialog.run_dialog(dialog.content);
            }
        },
    
        hide : function() {
            if (this.google_dialog)
            {
                /*if (this.ajaxLoader) {
    				this.ajaxLoader.abort();
    			}*/

                this.is_showing = false;
                this.google_dialog.setVisible(false);
                
                
                
                //alert(this.google_events.length);
                //this.google_dialog.dispose();
                /*if (this.event)
                {
                    alert(this.event);
                    this.event.removeAll();
                }*/
                
                /*for (var i = 0; i < this.google_events.length; i++) {
                    this.google_events[i].removeAll();
                }
                this.google_events = []*/
                
                /*
                if (this.google_events > 0)
                {
                    this.google_events[0].dispose();
                }*/
                
                
                
                /*for (i in this.google_events) {
                    this.google_events[i].dispose();
       			}*/
                
                
                this.hide_callback(this);
                
            }
            this.hide_loader();
        },
        
        reposition : function() {
            this.google_dialog.reposition();
        }
    };
    
    
    
	/*$.fn.fancybox = function(options) {
		$(this)
			.data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
			.unbind('click.fb').bind('click.fb', function(e) {
				e.preventDefault();

				if (busy) {
					return;
				}

				busy = true;

				$(this).blur();

				selectedArray	= [];
				selectedIndex	= 0;

				var rel = $(this).attr('rel') || '';

				if (!rel || rel == '' || rel === 'nofollow') {
					selectedArray.push(this);

				} else {
					selectedArray	= $("a[rel=" + rel + "], area[rel=" + rel + "]");
					selectedIndex	= selectedArray.index( this );
				}

				fancybox_start();

				return false;
			});

		return this;
	};

	$.fancybox = function(obj) {
		if (busy) {
			return;
		}

		busy = true;

		var opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};

		selectedArray	= [];
		selectedIndex	= opts.index || 0;

		if ($.isArray(obj)) {
			for (var i = 0, j = obj.length; i < j; i++) {
				if (typeof obj[i] == 'object') {
					$(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
				} else {
					obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts));
				}
			}

			selectedArray = jQuery.merge(selectedArray, obj);

		} else {
			if (typeof obj == 'object') {
				$(obj).data('fancybox', $.extend({}, opts, obj));
			} else {
				obj = $({}).data('fancybox', $.extend({content : obj}, opts));
			}

			selectedArray.push(obj);
		}

		if (selectedIndex > selectedArray.length || selectedIndex < 0) {
			selectedIndex = 0;
		}

		fancybox_start();
	};

	$.fancybox.prev = function() {
		return $.fancybox.pos( currentIndex - 1);
	};*/

	/*$.fn.fancybox.defaults = {
		padding				:	10,
		margin				:	20,
		opacity				:	false,
		modal				:	false,
		cyclic				:	false,
		scrolling			:	'auto',	// 'auto', 'yes' or 'no'

		width				:	560,
		height				:	340,

		autoScale			:	true,
		autoDimensions		:	true,
		centerOnScroll		:	false,

		ajax				:	{},
		swf					:	{ wmode: 'transparent' },

		hideOnOverlayClick	:	true,
		hideOnContentClick	:	false,

		overlayShow			:	true,
		overlayOpacity		:	0.3,
		overlayColor		:	'#666',

		titleShow			:	true,
		titlePosition		:	'outside',	// 'outside', 'inside' or 'over'
		titleFormat			:	null,

		transitionIn		:	'fade',	// 'elastic', 'fade' or 'none'
		transitionOut		:	'fade',	// 'elastic', 'fade' or 'none'

		speedIn				:	300,
		speedOut			:	300,

		changeSpeed			:	300,
		changeFade			:	'fast',

		easingIn			:	'swing',
		easingOut			:	'swing',

		showCloseButton		:	true,
		showNavArrows		:	true,
		enableEscapeButton	:	true,

		onStart				:	null,
		onCancel			:	null,
		onComplete			:	null,
		onCleanup			:	null,
		onClosed			:	null
	};*/

	//$(document).ready(function() {
	//	fancybox_init();
	//});

})(jQuery);
