/**
 * Custom JQuery dialog plugin.
 *
 */
(function ($) {
	
	/**
	 * current is the dialog to close, undefined means the last created
	 * count is how many dialogs to close at once, undefined means 1
	 */
    function _close(current, count) {
    	if (typeof current == 'undefined')
    	{
    		current = $('.dialog-container:last');
    	}
		if (! current.length > 0)
		{
			return;
		}
		if (typeof count == 'undefined')
		{
			count = 1;
		}
		var matchedObj = current.data('dialog_master');
		if (typeof matchedObj == 'undefined')
		{
			return; //this is to fix a bug that arises when a timer is waiting to close a dialog that got manually closed
		}
		var settings = matchedObj.data('dialog_settings');
		if($.isFunction(settings.onClose)) 
		{
        	settings.onClose(current);
        }
		current.fadeOut('fast', function () {
			current.remove();
			_unobscureIds(matchedObj);
			var previous = $('.dialog-container:last');
			if (previous.length == 0)
			{
				$('#dialog-overlay').fadeOut('fast', function () {
		            $('#dialog-overlay').remove();
		            $('embed, object, select').css({'visibility' : 'visible'});
		        });
				return;
			}
			if (count > 1)
			{
				previous.show('fast', function() {
					$.dialog.close(undefined, count - 1);
				});
				return;
			}
			previous.show();
        });
    }
    
    function _open(element) 
    {
    	if(element.length == 0) 
		{
            return false;
        }
		element = element.first(); //default
		
		var settings = element.data('dialog_settings');
	    var arrPageSizes = _getPageSize();
		
		var previous = $('.dialog-container:last');
		if (previous.length > 0)
		{
			previous.hide();
		}
		else
		{
	    	var overlay = _addOverlay(settings, arrPageSizes);
			overlay.fadeIn();
			// Hide some elements to avoid conflict with overlay in IE. 
	        // These elements appear above the overlay.
			$('embed, object, select').css({'visibility' : 'hidden'});
		}
		var current = _addCurrent(settings, arrPageSizes);
		current.data('dialog_master', element).fadeIn();
        
        //$(element).hide();
		var clone = $(element).clone(true);
        _obscureIds(element);
		current.find('.dialog-content')
        	.append(clone.show()); 
        if(settings.onOpen && $.isFunction(settings.onOpen)) {
            settings.onOpen(current);
        }
    }

    function _obscureIds(el) {
        if(el == null) return false;
        var $el = $(el);
        $el.html($el.html().replace(/( id=["']?)/gi, '$1_dialog_obscured_'));
        return $el;
    }
    
    function _unobscureIds(el) {
        if(el == null) return false;
        var $el = $(el);
        $el.html($el.html().replace(/( id=["']?)_dialog_obscured_/gi, '$1'));
        return $el;
    }
    
    /**
	 * getPageSize() by quirksmode.com
	 * @return Array Return an array with page width, height and window width, height
	 */
	function _getPageSize() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};
	
	function _addOverlay(settings, arrPageSizes)
	{
		var arrPageSizes = _getPageSize();
		var result = $('<div id="dialog-overlay" />')
		.appendTo('body')
		.css({
			backgroundColor:	settings.overlayBgColor,
			opacity:			settings.overlayOpacity,
            filter:             'alpha(opacity=' + (settings.overlayOpacity * 100) + ')',
			width:				arrPageSizes[0],
			height:				arrPageSizes[1]
		});

        if(settings.closeOnOverlayClick) {
            result.bind('click', function (evt) {
                evt.preventDefault();
                $.dialog.close();
            });
        }

		return result;
	}
	
	function _addCurrent(settings, arrPageSizes)
	{
		var position = {
			top:  Math.max((arrPageSizes[3] - settings.height) / 2, 0),
			left: Math.max((arrPageSizes[2] - settings.width)  / 2, 0)
        };
        var result = $('<div class="dialog-container"><div class="dialog-dragbar"><img class="dialog-close" /><div class="cl" /></div><div class="dialog-content"/></div>')
        .appendTo('body')
		.hide()
    	.css(position)
        .width(settings.width)
        .height(settings.height);
        
        if(settings.imageBtnClose.length > 0) 
        {
        	result
    		.find('.dialog-close')
    			.attr('src', settings.imageBtnClose)
    			.bind('click', function (evt) {
                    evt.preventDefault();
                    _close();
                });
        }
        else 
        {
        	result
    		.find('.dialog-dragbar')
    			.hide();
        }
        return result;
	}

    $.dialog = {
        close: function (element, count) {
            _close(element, count);
        }
    };

    $.fn.dialog = function (settings) {
		this.data('dialog_settings', $.extend({
			maxWidth:       null,
			maxHeight:      null,
            width:          250,
            height:         150,
            modal:          true,
			overlayBgColor: '#000',
			overlayOpacity: 0.2,
            onClose:        null,
            onOpen:         null,
			imageBtnClose:  '/img/lightbox-btn-close.gif',
            closeOnOverlayClick: true
		}, settings));
        
    	_open(this);
    }

})(jQuery);

