
(function(){
	var defaults = {
		header             : false,
		closeLinkSelector  : '.close_link',
		closeSubmitSelector: '.close_submit',
		submitSelector	   : '',
		popupTag           : 'div',
		popupAttrs         : null,
		removeOtherPopups  : true,
		useContainer       : true,
		containerClass     : 'popup_container',
		parent             : 'body',
		cache              : false,
		onLoaded           : function(){},
		onInserted         : function(){},
		onFormSubmit       : function(){},
		onClose            : function(){},
		extraParams        : null,
		onError            : function(){},
		condition          : null,
		event              : 'click'
	};
	function generatePopup( options, extraParams ){

		/**
		 * Create the popup element.
		 */
		var $popup = $( '<'+options.popupTag+'>' );
		
		if( options.header ){
			$popup.$header = $( options.header );
			$popup.$header.find( '[@rel=popup_title]' ).html( options.title );//set the title of the header( must have an item with rel=popup_title
			$popup.prepend( $popup.$header );
		}	
		
		for( var i in options.popupAttrs )
			$popup.attr( i, options.popupAttrs[i] );
						
		function closePopup( hide ){

			try{options.onClose( $popup, !!$popup[0].parentNode/*is inserted?*/, !!hide /*will be hidden?*/);}
			catch(e){}
			if( $popup[0].parentNode ){//inserted in the DOM?
				//$window.unbind( 'resize', centerPopup ); // lo comento ya q sin lo de abajo, esto no hace falta.
				$popup[hide?'hide':'remove']();
				if( $popup.$container )
					$popup.$container[hide?'hide':'remove']();
			}
			if(!options.cache && !hide)
				$popup.empty();
			return false;
		}
		function centerPopup(){

			 var top = ( $window.height() - $popup.height() ) / 2;
			 var left = ( $window.width() - $popup.width() ) / 2;
			 $popup.css( 'top', top+'px' );
			 $popup.css( 'left', left+'px' );
		}			
		//$popup.$closeButton = $popup.find( options.closeLinkSelector ).bind( 'click', closePopup );
		$popup.close = closePopup;
		$popup.center = centerPopup;
			
		if( options.useContainer ){
			$popup.$container = $( '<div class="'+options.containerClass+'">' );
			//$popup.$container.css( 'height', Math.max( $(document).height(), $window.height() )+'px' ); //set the height of the container.
		}
		function onSubmit(event){
			var form = event.target.form || event.target, $form = $(form), c;
			if( !$form.is('form') ) return;
			if( options.onBeforeSubmit  && options.onBeforeSubmit( $popup, $form ) === false ) return false;
			if( c = form.className.match(/(ajax|self)/) ){//ajax form
				switch( c[1] ){
					case 'ajax'://ajax form
						$form.ajaxSubmit({
							success:function(response){
								try{options.onFormSubmit.call(options.triggerElement || document,$popup, response);}
								catch(err){throw 'jquery.inlinepopup.js > the given "onFormSubmit function threw this error:\n'+err;}
								finally{$popup.close(/* !!$form.find('input:file').length */);}
							},
							error:function( http ){
								$popup.close();
								throw ['jquery.inlinepopup.js > an ajax form submit failed.',
												 'Error description:',
													'***status:"'+http.status+'"',
													'***status Text:"'+http.statusText+'"',
													'***error message:"'+http.responseText+'".'].join('\n\t');	
							}
						});
						return false;
					case 'self'://ajax form which response will override the innerHTML of the popup
						$form.ajaxSubmit({success:function( r ){
							$popup.empty().append( r );
							if( options.onSelfSubmit )
								options.onSelfSubmit.call(options.triggerElement || document, $popup );
						}});
						return false;
				}
			}
		};
		function popupClick(event){
			//event.stopPropagation();
			var $target = $(event.target);
			if( $target.is(options.closeLinkSelector) )//close popup
				return closePopup();
			if( $target.is(options.closeSubmitSelector) )//regular form
				return closePopup( true );
			if( $target.is(':submit,:image') || $target.is(options.submitSelector) ){//regular form
				event.target = $target.parents('form')[0];
				return onSubmit( event );
			}
		};

		/**
		 * This function will load the header and static content, if they were given.
		 */
		function loadStatic(){		
			if( options.content ) 
				$popup.append( options.content );
			$popup.$body = $popup.find( '.popup_body' );
			$popup.unbind('click').click(popupClick);
			$popup.unbind('submit').submit(onSubmit);
			if( $popup.$container )
				$popup.$container.height( $('body').height() );
			options.onLoaded( $popup );	
		};
		
		if( typeof options.extraParams == 'string' )
			options.url+= options.extraParams;
		
		$popup.loadContent = function( callback ){
			if($popup.contentLocked) return;
			$popup.empty();
			if( options.url ){ // if an url was given, load the content by ahah ( and the rest )
				if( typeof options.extraParams == 'function'){
					options.extraParams( options.triggerElement, $options );
				}				
				$popup.load( encodeURI(options.url), options.data, function(c,status){
					if( status == 'error' ){
						$popup.close();
						options.onError.call( $popup );
					}else{
						loadStatic();
						if(callback)
							callback();
					}
				})				
			}else{// just load the rest( header and static content )
				loadStatic();	
				if(callback)
					callback();
			}
			/*$window.resize( centerPopup );*/							
			$popup.contentLocked = !!options.cache;
		};
		$popup.insert = function( parent ){
			if($popup.$container)
				$popup.$container.appendTo( 'body' );
			$popup.appendTo( parent );
			//centerPopup();		//auto centrado. lo saco porque tiene un delay que se debe arreglar
			options.onInserted( $popup );
		}
		return $popup;
	}
	function initialize($popup, parent){
		if( $popup.contentLocked ){
			$popup.insert( parent );
		}else{
			$popup.loadContent(function(){
				$popup.insert( parent );
			});
		}
	}
/***********************************************************/
$.fn.inlinePopup = function( options, extraParams ){
	if(!this.length) return this;
	options = $.extend( {}, defaults ,options);
	var $popup = generatePopup(options, extraParams);

	this[options.event](function(){
		if( options.condition && !options.condition.call(this)) return false;
		$popup.show();
		if($popup.$container)
			$popup.$container.show();
		initialize( $popup, (options.parent == 'this' ? this : options.parent) );
		return false;
	});
	return this;
};
/***********************************************************/
$.inlinePopup = function( options, extraParams ){
	options = $.extend( {}, defaults ,options);
	var $popup = generatePopup(options, extraParams);
	initialize( $popup, options.parent );
};

})();