jQuery.popup = {};

jQuery.popup.defaultOptions = {
	appendTo		: 'body',
	popupHtml		: '<div class="popup"><p class="paragraphClose"><span class="closePopup">Cerrar</span></p></div>',
	shadowHtml		: '<div class="popupShadow"></div>',
	iframe			: '<iframe class="hideSelects"></iframe>'
};

jQuery.popup.methods = {
	margin : '',
	padding : '',
	
	setMargin : function(obj) {
		jQuery.popup.methods.margin = obj.css('margin');
	},
	
	getMargin : function() {
		return jQuery.popup.methods.margin;
	},
	
	setPadding : function(obj) {
		jQuery.popup.methods.padding = obj.css('padding');
	},
	
	getPadding : function() {
		return jQuery.popup.methods.padding;
	}
};

jQuery.closePopup = function() {
	$('.popup').hide();
	
	$('.popupShadow').hide();
		
	$('.popup, .popupShadow, .hideSelects').remove();

	if (typeof document.body.style.maxHeight == 'undefined') {
		$('body','html').css({height: 'auto', width: 'auto'});
		//$('html').css('overflow','');
		
		$('body').css({
			margin : jQuery.popup.methods.getMargin(),
			padding : jQuery.popup.methods.getPadding()
		});
	}
};

jQuery.openPopup = function(selector, options) {
	var options = jQuery.extend(jQuery.popup.defaultOptions, options);
	selector = selector==null?'.popupContent':selector;
	
	if (typeof document.body.style.maxHeight === 'undefined') {
		$('body', 'html').css({height: '100%', width: '100%'});
		//$('html').css('overflow','hidden');
		jQuery.popup.methods.setMargin($('body'));
		jQuery.popup.methods.setPadding($('body'));
		$('body').css({
			margin : '0',
			padding : '0'
		});
		
		if (!$('iframe.hideSelects').length) {
			$('body').prepend(options.iframe);
		}
	}
	
	$('body').prepend(options.shadowHtml).find('.popupShadow').css('display', 'none').show();

		$(options.popupHtml).appendTo(options.appendTo).append($(selector).html());
		
		$('.popup').css({
			top : $(document).scrollTop() + 10 + 'px'
		}).show();
		
		$('.closePopup').css('cursor', 'pointer').bind('click', function() {
			$.closePopup();
		});

};

jQuery.fn.popup = function(selector, options) {
	var options = jQuery.extend(jQuery.popup.defaultOptions, options);
	selector = typeof selector!='String'?'.popupContent':selector;
	
	return this.each(function(){
		var element = $(this);
		
		(function($) {
			element.bind('click', function(e) {
				$.openPopup(selector, options);
				e.preventDefault();
			});
		})(jQuery);
	});
};
