;(function( $, undefined ) {
	var containerId = '.rps-promo-modal';
	var promoWidth = 0;
	var promoHeight = 0;
	
	$( document ).ready(
		function() {
			var hash = $( containerId ).data( 'hash' );
			
			if ( getCookie( hash ) === null ) {
				
				promoWidth = $( containerId ).data( 'width' );
				promoHeight = $( containerId ).data( 'height' );
				
				$( containerId ).dialog({
					dialogClass: "rps-promo-manager-dialog",
					modal: true,
					show: { effect: "fade", duration: 800 },
					hide: { effect: "fade", duration: 800 },
					autoOpen: false,
					close: function( event, ui ) {
						setCookie( hash );
					},
					draggable: false,
					resizable: false
				});
				
				setTimeout( function() {
					$( containerId ).dialog( 'open' );
					calculateDimensions();
				}, 500)
			} else {
				$( containerId ).hide();
			}
			
			
		}
	);
	
	$( window ).resize(function() {
		calculateDimensions();
	});
	
	
	function calculateDimensions() {
		var windowWidth = $( window ).width() - 20;
		var windowHeight = $( window ).height() - 40;
		
		var coeff = 1;
		if ( ( windowWidth < promoWidth ) || ( windowHeight < promoHeight ) ) {
			coeff = windowWidth / promoWidth;
			if (windowHeight < promoHeight * coeff) {
				coeff = windowHeight / promoHeight;
			}
		}
		
		$( containerId ).dialog("option", "width", promoWidth * coeff);
		$( containerId ).dialog("option", "height", promoHeight * coeff);		
		$( containerId ).position({ my: "center", at: "center", of: window });
	}
	
	function setCookie(key) {
		if ( replacements.dismiss_hours > 0 ) {
	        var expires = new Date();
	        expires.setTime( expires.getTime() + ( replacements.dismiss_hours * 60 * 60 * 1000 ) );
	        document.cookie = key + '=0;expires=' + expires.toUTCString();
		}
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }
	
})( jQuery );