/**
 * Easy popup dialogs v2.6
 * http://www.code-masters.org
 *
 * Copyright 2011, Strong
 * 
 * Under GPL license Version 2.
 * http://www.gnu.org/licenses/gpl-2.0.html
 * 
 * Date: 10/03/2011
 *
 * @author  Strong
 * @version 2.6
 */
 
// Initialize dialogs
$(document).ready(function() {
    popup.dialog.init();					   
});

// Create new dialog object
var popup = {}, _active = null, _dialogs = [], _guid = 0, isInit = false;

/**
 * Create new dialog
 *
 * @param  object  options
 */
popup.dialog = function(options) {
    if ( ! isInit) {
        popup.dialog.init();
    }
    
    // Set default box options
    popup.defaults = {
	title          : 'Внимание',
	content        : '',
	width          : 500,
	height         : 'auto',
	loader         : false,
	progress       : false,
	imagebox       : false,
	showOverlay    : true,
        showTitle      : true,
        showButtons    : true,
	overlayColor   : '#000',
	overlayClose   : false,
	closeOnEsc     : true,
        toggleFlash    : true,
	opacity        : 0.2,
	buttons        : {},
	onShow         : false,
	onClose        : false
    };
    
    _guid++;
	
    // Get options
    popup.options = $.extend({}, popup.defaults, options || {});

    // Set params to defaults    
    popup.dialog.refresh();	
	
    // Get overlay full width & height in px
    popup.overlayWidth  = getWidth();
    popup.overlayHeight = getHeight();
	
    // If pressed ESC key, box close
    if (popup.options.closeOnEsc) {
        $(document).bind('keyup', function(e) {
	    if (e.keyCode == 27) {
	        popup.dialog.close();
	    }
        });
    }	
	
    // Set controls
    popup.boxTitle.empty().html( popup.options.title );
    popup.boxContent.empty().html( popup.options.content );
    popup.dialog.setButtons( popup.options.buttons );
	
    // Set overay params
    if (popup.options.showOverlay) {
        popup.overlay.css({
            'background-color' : popup.options.overlayColor,
	    'width' : popup.overlayWidth,
	    'height' : popup.overlayHeight,
	    'opacity' : popup.options.opacity
	});
	
	if (popup.options.overlayClose) {
	    popup.overlay.bind('click', function() {
	        popup.dialog.close();
	    });
        }
    }
	
    // Set box container width
    popup.boxContainer.css({
        'width'  : popup.options.width,
        'height' :  popup.options.height
    });
           	
    // Show popup box
    popup.dialog.show();
}

/**
 * Show popup dialog box
 *
 * @param  void
 */
popup.dialog.show = function() {
    popup.dialog.toggleFlash();
        
    // If function initialized, execute
    if ($.isFunction(popup.options.onShow)) {
	popup.options.onShow.apply();
    }
	
    // Show overlay
    if (popup.options.showOverlay) {
	popup.overlay.show();
    }
	
    if (popup.options.imagebox) {
	popup.boxTitle.hide();
	popup.boxButtons.hide(); 
    } else {
        if ( ! popup.options.showTitle) {
            popup.boxTitle.hide(); 
        }
             
        if ( ! popup.options.showButtons) {
            popup.boxButtons.hide();
        }
    }
		
    // Set trigger to open dialog
    popup.isOpen = true;
    
    // Show box container
    popup.boxContainer.show();
    
    // Align to viewport center
    popup.dialog.align();	
}

/**
 * Toggle flash elements on page
 *
 * TODO
 * @param  void
 */
popup.dialog.toggleFlash = function(trigger) {}


/**
 * Set dialog params to default
 *
 * @param  void
 */
popup.dialog.refresh = function() {
    $(window).unbind();
    $(document).unbind();
	
    popup.overlay.unbind('click');

    popup.boxTitle.empty().show();
    popup.boxButtons.empty().show(); 
    
    if (popup.options.showOverlay) {
	popup.overlay.css({
	    'background-color' : popup.defaults.overlayColor,
	    'width' : '100%',
	    'height' : '100%',
	    'opacity' : popup.defaults.opacity
	});		 		 
    }
	
    popup.boxContainer.css({
        'width'  : popup.defaults.width,
        'height' : popup.defaults.height
    });	
	   
    popup.boxContent.empty();
    popup.dialog.enableButtons();
}

/**
 * Close popup dialog
 *
 * @param  void
 */
popup.dialog.close = function() {
    if ($.isFunction(popup.options.onClose)) {
	popup.options.onClose.apply();
    }       

    popup.overlay.hide();
    popup.boxContainer.hide();

    popup.dialog.refresh();	
	
    delete popup.options;
	
    popup.isOpen = false;
    popup.dialog.toggleFlash(true);
}

/**
 * Initialize popup dialog box
 *
 * @param  void
 */
popup.dialog.init = function() {
    var
        overlay = $('<div></div>')
            .appendTo('body')
            .attr('id', 'strongBoxOverlay')
            .hide(),
            
        iframe = $('<iframe frameborder="0"></iframe>')
            .attr('id', 'boxIframe')
            .appendTo(overlay),
            
        box = $('<div></div>')
            .appendTo('body')
            .attr('id', 'strongBox')
            .hide(),

        boxLayout = $('<div></div>')
            .appendTo(box)
            .addClass('strongBoxContentWrapper'),           
            
        boxTitle = $('<div></div>')
            .appendTo(boxLayout)
            .attr('id', 'strongBoxTitle'),
            
        boxError = $('<div></div>')
            .insertAfter(boxTitle)
            .attr('id', 'strongBoxError')
            .hide(),
            
        boxContent = $('<div></div>')
            .insertAfter(boxError)
            .attr('id', 'strongBoxContent'),
            
        boxButtons = $('<div></div>')
            .insertAfter(boxContent)
            .attr('id', 'strongBoxButtons')
       		    
	// Assets overlay   
	popup.overlay        = overlay;
	// Assets box
	popup.boxContainer   = box;
	// Assets box title
	popup.boxTitle       = boxTitle;
	
	popup.boxError       = boxError;
	
	// Assets box buttons
	popup.boxButtons     = boxButtons;
	// Assets box content
	popup.boxContent     = boxContent; 
	
	popup.boxIframe      = iframe;
	
	isInit = true;	    	
}

/**
 * Align dialog box on the screen center
 *
 * @param  void
 */
popup.dialog.align = function() {
    var
        dialog = {
            width  : popup.boxContainer.width() + 20,
            height : popup.boxContainer.height() + 20
        },
        
        view = {
            width      : $(window).width(),
            height     : $(window).height(),
            scrollLeft : $(window).scrollLeft(),
            scrollTop  : $(window).scrollTop()
        },
        
        left = (view.scrollLeft + (view.width - dialog.width) / 2),
        top  = (view.scrollTop + (view.height - dialog.height) / 2.5); 
    
    popup.boxContainer.css({
        'left' : (left > 0 ? left : 0) + 'px',
        'top'  : (top > 0 ? top : 0) + 'px'    
    });
    
    popup.boxIframe.css({
        'width'  : dialog.width + 'px',
        'height' : dialog.height + 'px',
        'left'   : (left > 0 ? left : 0) + 'px',
        'top'    : (top > 0 ? top : 0) + 'px'    
    });  	
}

/**
 * Add buttons on dialog box
 *
 * @param  object  buttons
 */
popup.dialog.setButtons = function(buttons) {
    popup.boxButtons.empty();	 
    
    $.each(buttons, function(name, fn) {
	var button = $('<button type="button" class="cm-dialog-button button green"></button>')
		      .html(name)
		      .click(function() { fn.apply(); })
		      .appendTo(popup.boxButtons);				
    }); 
}

/**
 * Disable buttons on dialog box
 *
 * @param  object  void
 */
popup.dialog.disableButtons = function() {
    popup.boxButtons.find('button').attr('disabled', 'disabled');    
}

/**
 * Enable buttons on dialog box
 *
 * @param  object  void
 */
popup.dialog.enableButtons = function() {
    popup.boxButtons.find('button').removeAttr('disabled');    
}

/**
 * Dialog alert box
 *
 * @param  string  message
 * @param  function callback
 * @param  string  dialog types
 */
popup.alert = function(message, callback, type) {

        var title = 'Внимание';
                 
	popup.dialog({
	    title      : title,
	    content    : '<div class="popup_message">'+message+'</div>',
	    onClose    : callback,
	    width      : 500,
	    buttons    : {
	        'Закрыть' : function() {
	            popup.dialog.close();
	        }
	    } 
	});
	
	return false;
}

/**
 * Print error, and clear error place holder on time out
 *
 * @param  string  error message
 * @param  type  error, success, info, notice
 * @param  function 
 * @return void
 */
popup.error = function(errorText, type, onComplete, delay) {
	var _int;
	
	if ( ! type) type = 'error';
	if ( ! delay) delay = 2500;
	
	popup.boxError.empty().html('<div class="b-rounded b-'+type+'">'+errorText+'</div>').show();
	
	_int = setInterval(function() {
	         
	     popup.boxError.empty().hide();
	        
	     clearInterval(_int);
		
	     if ($.isFunction(onComplete)) {
	         onComplete.apply();
	     }
		
	}, delay);
}

popup.loading = function() {
    return true;
}

popup.imagebox = function(title, url) {
	var validUrl = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	var urlType = url.toLowerCase().match(validUrl);
    
	if(urlType == '.jpeg' || urlType == '.jpg' || urlType == '.png' || urlType == '.gif') {
		imgPreloader = new Image();

                popup.loading();

		imgPreloader.onload = function(){		
		imgPreloader.onload = null;
		
		var x = $(window).width()  - 100;
		var y = $(window).height() - 100;
		var imageWidth = imgPreloader.width;
		var imageHeight = imgPreloader.height;
		if (imageWidth > x) {
			imageHeight = imageHeight * (x / imageWidth); 
			imageWidth = x; 
			if (imageHeight > y) {
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
			}
		} else if (imageHeight > y) {
			imageWidth = imageWidth * (y / imageHeight); 
			imageHeight = y; 
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x;
			}
		}
		
		var image_container = '<div class="popup_imagebox"><img src="'+url+'" width="'+imageWidth+'" height="'+imageHeight+'" /></div><div class="popup_imagebox_credits"><a href="javascript:popup.dialog.close()" class="grey-button pcb"><span>Закрыть окно</span></a></div>';
		
		popup.dialog({
		content      : image_container,
		width        : imageWidth + 20,
		imagebox     : true,
		overlayClose : true,
		opacity : 0.3		
		});
				
		}
		
		imgPreloader.src = url;
	}
}

popup.imageboxInit = function() {
     // Stylize
     var strongboxImg = $('.strongbox img');
	 
     // Add event
     $('a.strongbox').click(function() {
	  var imageTitle = this.title || 'Просмотр изображения';
	  var imageUrl   = this.href  || null;
	  popup.imagebox(imageTitle, imageUrl);
	  this.blur();
	  return false; 
     });		
}

function getHeight() {
    // handle IE 6
    if ($.browser.msie && $.browser.version < 7) {
        var scrollHeight = Math.max(
	    document.documentElement.scrollHeight,
	    document.body.scrollHeight
	);
	var offsetHeight = Math.max(
	    document.documentElement.offsetHeight,
	    document.body.offsetHeight
	);

	if (scrollHeight < offsetHeight) {
	    return $(window).height() + 'px';
	} else {
	    return scrollHeight + 'px';
	}
    // handle "good" browsers	 
    } else {
	return $(document).height() + 'px';
    }
}

function getWidth() {
    // handle IE 6
    if ($.browser.msie && $.browser.version < 7) {
        var scrollWidth = Math.max(
	    document.documentElement.scrollWidth,
	    document.body.scrollWidth
	);
	var offsetWidth = Math.max(
	    document.documentElement.offsetWidth,
	    document.body.offsetWidth
	);

	if (scrollWidth < offsetWidth) {
	    return $(window).width() + 'px';
	} else {
	    return scrollWidth + 'px';
	}
    // handle "good" browsers
    } else {
        return $(document).width() + 'px';
    }
}

