
var Ctrl_Dialog = Ctrl_Class.extend({
    
    init: function(options) {
        this.options = jQuery.extend({
            'autoOpen' : false,
            'contents' : null
        }, options);
    
        this.options.dialogClass = 'ctrl-dialog ' + this.options.dialogClass;
        
        var id = 'ctrl-dialog' + new Date().getTime();
        this.elem = $('<div id="'+id+'"></div>');
        $('body').append(this.elem);
        
        if(null !== this.options.contents) {
            if(!(this.options.contents instanceof jQuery))
                    this.options.contents = $(this.options.contents);
            
            this.elem.append(this.options.contents.show());
        }
        
        this.elem.dialog(this.options);
        this.window = this.elem.closest('.ui-dialog');
        
    },
    
    open: function(){ this.elem.dialog('open'); return this; },
    close: function(){ this.elem.dialog('close'); return this; },
    
    destroy: function() {
        this.elem.dialog('destroy').remove();
    }
    
});

/*
 * Static methods for custom confirmation dialogs.
 */
Ctrl_Dialog._confirmDialog = null;
Ctrl_Dialog._getConfirmDialog = function() {
    if(null == Ctrl_Dialog._confirmDialog) {
        Ctrl_Dialog._confirmDialog = new Ctrl_Dialog({
            title: 'Please Confirm',
            dialogClass: 'ctrl-dialog-confirm',
            resizable: false,
            draggable: false
        });
    }
    
    return Ctrl_Dialog._confirmDialog;
};

Ctrl_Dialog.confirm = function(message, callback, modal) {
	var o = {
		message: 'Are you sure you want to do that?',
		no: function() {},
		yes: function() {},
		modal: false
	};
	if(typeof message == 'object') {
		o = $.extend(o, message);
	} else {
		o = $.extend(o, { message: message, yes: callback, modal: !!modal });
	}
	
	
    var d = Ctrl_Dialog._getConfirmDialog();
    d.elem.dialog('option', 'buttons', {
        'No' : function() { o.no.apply(d); $(this).dialog('close'); },
        'Yes' : function() { o.yes.apply(d); $(this).dialog('close'); }
    }).dialog('option', 'modal', o.modal);
    d.elem.empty().append($('<p>').text(o.message));
    d.open();
};


Ctrl_Dialog._alertDialog = null;
Ctrl_Dialog._getAlertDialog = function() {
    if(null == Ctrl_Dialog._alertDialog) {
        Ctrl_Dialog._alertDialog = new Ctrl_Dialog({
            title: '',
            dialogClass: 'ctrl-dialog-alert',
            resizable: false,
            draggable: false
        });
    }
    
    return Ctrl_Dialog._alertDialog;
};

Ctrl_Dialog.alert = function(message, callback, modal) {
	var o = {
		message: 'Are you sure you want to do that?',
		modal: false
	};
	if(typeof message == 'object') {
		o = $.extend(o, message);
	} else {
		o = $.extend(o, { message: message, yes: callback, modal: !!modal });
	}
	
    var d = Ctrl_Dialog._getAlertDialog();
    d.elem.dialog('option', 'buttons', {
        'Ok' : function() { $(this).dialog('close'); }
    }).dialog('option', 'modal', o.modal);
    d.elem.empty().append($('<p>').text(o.message));
    d.open();
};


var Ctrl_Dialog_Image = Ctrl_Dialog.extend({
    init: function(image, options) {
        options = jQuery.extend({
            width: 760,
            height: 580,
            crop: false,
            resizable: false,
            draggable: false,
            dialogClass: 'ctrl-dialog-image'
        }, options);

        this._super(options);

        if(image !== null)
        	this.setImage(image);
        
        this.elem.append('<div class="ctrl-dialog-image-image"></div><div class="ctrl-dialog-image-caption"></div>');
    },
    
    setImage: function(image, caption) {
        var url = this._getThumbnailUrl(image);

        var that = this;
        
        var i = new Image();
        i.src = url;
        i.onload = function(){
            that.elem.dialog('option', 'width', this.width).dialog('option', 'height', this.height);
            that.window.position({ my: 'center center', at: 'center center', of: window });
            that.trigger('load');
        };
        
        this.elem.children('.ctrl-dialog-image-image').empty().append(i);
        
        if(caption)
    		this.setCaption(caption);
        
        return this;
    },
    
    setCaption: function(text) {
    	var e = this.elem.children('.ctrl-dialog-image-caption');
    	
    	if(text)
    		e.text(text).show();
    	else
    		e.hide();
    	
    	return this;
    },
    
    _getThumbnailUrl: function(image) {
        if(typeof image == 'object' && image.ID) {
            image = image.ID;
            return Ctrl.Config.baseUrl + '/media/thumbnail/id/' + image + '/width/' + this.options.width + '/height/' + this.options.height + '/crop/' + this.options.crop;
        } else if(typeof image == 'string' && /^http:\/\//.test(image)) {
        	return image;
        }
    }
});

var Ctrl_Dialog_Gallery = Ctrl_Dialog_Image.extend({
    init: function(images, options) {
        options = jQuery.extend({
            type: null,
            dialogClass: 'ctrl-dialog-gallery',
            slideshow: { autostart: false }
        }, options);

        this._super(null, options);
        
        this.slideshow = null;
        
        if(images !== null)
        	this.setImages(images);
    },
    
    setImage: function(image) { },
    
    setImages: function(images) {
        var that = this;
        
        var urls = [];
        
        // Handle the JSON response from below.
        if(typeof images == 'object' && images.items)
            images = images.items;
        
        if($.isArray(images)) {
            for(var i in images) {
                urls.push(this._getThumbnailUrl(images[i]));
            }
        } else {
            $.getJSON(Ctrl.Config.baseUrl + '/media/index/resource/' + images + (this.options.type == null? '' : '/type/' + this.options.type), function(resp) {
                that.setImages(resp);
            });
            
            return;
        }
        
        this.elem.empty();
        
        var ss, $images, $controls;
        $images = $('<div class="ctrl-dialog-gallery-images"></div>')
        for(var u in urls) {
            var i = new Image();
            i.src = urls[u];
            if(u == 0) {
                i.onload = function(){
                    that.elem.dialog('option', 'width', this.width).dialog('option', 'height', this.height);
                    that.window.position({ my: 'center center', at: 'center center', of: window });
                    that.trigger('load');
                };
            }
            
            $images.append(i);
        }
        
        this.slideshow = $images.children('img').slideshow(this.options.slideshow);
        this.slideshow.elem.bind('slideshow-pre-in', function(){
        	// img == this
        	var iw = $(this).width(), ih = $(this).height();
        	that.window.animate({
        		width: iw,
        		height: ih,
        		left: ($(window).width() - iw) / 2
        	}, 400, 'easeInOutQuad', function() { that.elem.dialog('option', 'width', iw).dialog('option', 'height', ih); });
        });
        
        $controls = $('<div class="ctrl-dialog-gallery-controls"></div>');
        $controls.append( $('<a class="ctrl-dialog-gallery-controls-prev" href="#">Previous</a>').click(function(){ that.slideshow.stop().prev(); return false; }) );
        $controls.append( $('<a class="ctrl-dialog-gallery-controls-next" href="#">Next</a>').click(function(){ that.slideshow.stop().next(); return false; }) );
        
        this.elem.append($images).append($controls);
        
        return this;
    },
    
    getSlideshow: function() { return this.slideshow; }
    
});

/**
 * @event load|contentsloaded Fires when, guess what, the contents is loaded.
 */
var Ctrl_Dialog_Ajax = Ctrl_Dialog.extend({
    init: function(options, src) {
        this.src = src;
        this._isLoaded = false;
        
        options = jQuery.extend({
            'autoLoad': true
        }, options);
        options.dialogClass = options.dialogClass? 'ctrl-dialog-ajax ' + options.dialogClass : 'ctrl-dialog-ajax';
        
        this._super(options);
      
        if(this.options.autoLoad && this.src)
            this.load();
    },
    
    load: function(callback, force) {
        var that = this;

        if(!this._isLoaded || force) {
            this.elem.empty().load(this.src, function(){ 
            	that.trigger('contentsloaded').trigger('load');
            	
                if(typeof callback == 'function') {
                    that._isLoaded = true;
                    callback.call(that);
                }
            });        
        }
    },
    
    setSrc: function(src) {
        this.src = src;
		this._isLoaded = false;

        return this;
    },
    
    open: function() {
    	var that = this;
    	if(!this._isLoaded) {
    		this.load(function(){
    			this.elem.dialog('open');
    		});
    	} else {
    		this.elem.dialog('open');
    	}
    	
    	return this;
    }
    
});

var Ctrl_Dialog_Iframe = Ctrl_Dialog.extend({
    
    init: function(options, src) {
        options = options || {};
        options.dialogClass = options.dialogClass? 'ctrl-dialog-iframe ' + options.dialogClass : 'ctrl-dialog-iframe';
        this._super(options);
        
        if(src != undefined)
            this.setSrc(src);
        
        this.iframe = null;
    },
    
    getIframe: function() {
        if(this.iframe == null) {
            this.iframe = this.elem.find('iframe');
            if(this.iframe.length == 0) {
                this.iframe = $('<iframe frameborder="0"></iframe>');
                this.elem.append(this.iframe);
                var that = this;
                this.iframe.load(function(){ that.trigger('load'); });
            }
        }
        
        return this.iframe;
    },
    
    getIframeWindow: function() {
    	var i = this.getIframe().get(0);
    	return i.contentWindow;
    },
    
    getIframeDOMDocument: function() {
    	var i = this.getIframe().get(0);
    	return i.contentDocument? i.contentDocument : i.contentWindow.document;
    },
    
    setSrc: function(src, forceRefresh) {

        if(src != this.getIframe().attr('src') || forceRefresh === true)
            this.getIframe().attr('src', src);
        
        return this;
    },
    
    refresh: function() { var ifm = this.getIframe(); ifm.attr('src', ifm.attr('src')); return this; }
    
});


