/*
|	Modal plugin
|	Add class="modal" on a link and these paramters
|	
|	Required :
|		url  = path of content to load (string) == href
|		type = [image|ajax|iframe|html] (string) == rel
|	Optional (default values) :
|		width  = 500 == rel
|		height = 500 == rel
|		title  = ''  == title
|		params = ''  == querystring in href
|
|	Ex:
|	<a class="modal" href="/medias/photos/photo.jpg?login=john&age=28" rel="type=image&width=800&height=600" title="Modal window">This link will open a modal window.</a>
|
-------------------------------------------- */
(function($){
	/* Settings
	---------------------------------------- */
	var __ = {
		doc: {
			width: $('#overall').outerWidth(),
			height: $('#overall').outerHeight()
		},
		win: {
			width: $(window).width(),
			height: $(window).height()
		}
	};
	// Update dimensions when resizing
	$(window).resize(function(){
		__.win = {
			width: $(window).width(),
			height: $(window).height()
		}
	});
	var modaLayout = '\
		<div id="modal">\
			<div id="modal-mask"></div>\
			<div id="modal-wrapper">\
				<div id="modal-shadow"></div>\
				<div id="modal-box">\
					<div id="modal-inner">\
						<div id="modal-header">\
							<img id="modal-close" class="ico i-close" src="/blank.gif">\
							<h2>{TITLE}</h2>\
							<div class="clear"></div>\
						</div>\
						<div id="modal-content"></div>\
						<div id="modal-footer"></div>\
					</div>\
				</div>\
			</div>\
		</div>\
	';
	
	/* Functions
	---------------------------------------- */
	var _getParams = function(o){ // get all parameters for modal window
		var r = {}, couple = $(o).attr('rel').split('&'), i = couple.length;
		while(i--){
			var single = couple[i].split('=');
			if( (single[0] == 'width' || single[0] == 'height') && single[1] != 'auto' )
				single[1] = parseInt(single[1]);
			if( single[0] == 'pos' ) single[1] = true;
			if( single[0] == 'mask' ) single[1] = false;
			r[single[0]] = single[1];
		}
		r.params = o.search.substring(1,o.search.length);
		//r.title = o.title;
		r.url = o.href.substring(0,o.href.indexOf('?')) || o.href;
		return r;
	};
	var _setInterface = function(o){
		// Mask dimensions
		var __resizeMask = function(){
			var w = ( __.win.width < __.doc.width ) ? __.doc.width : __.win.width ;
			var h = ( __.win.height < __.doc.height ) ? __.doc.height : __.win.height ;
			$('#modal-mask').css({ width: w, height: h });
		};
		var __resizeInterface = function(){
			__resizeMask();
			// Modal wrapper position
			if( !o.pos ){
				$('#modal-wrapper').css({
					top: __.top + __.win.height / 2,
					left: '50%',
					marginTop : - $('#modal-wrapper').outerHeight() / 2,
					marginLeft: - $('#modal-wrapper').outerWidth() / 2
				});
				if( $('#modal-wrapper').outerWidth() >= __.win.width ){
					$('#modal-wrapper').css({
						left: 0,
						marginLeft: 0
					});
				}
				if( $('#modal-wrapper').outerHeight() >= __.win.height ){
					$('#modal-wrapper').css({
						top: 15 + __.top,
						marginTop: 0
					});
				}
			}
			__resizeMask();
		};
		// Resize modalwrapper
		var __resizeModalWrapper = function(){
			var modalWidth = $('#modal-wrapper').outerWidth();
			if( modalWidth + o.x > o.max && modalWidth < $('#overall').outerWidth() ){
				var limitLeft = $('#overall').offset().left;
				$('#modal-wrapper').css({ left : limitLeft + 'px'  });
			}
		};
		// Close
		var __close = function(){
			$(window).unbind('keyup');
			$('#modal').remove();
			if( o.type == 'image' ){ image.src = ''; }
			if( o.mask ){ $('#overall embed, #overall object, #overall select').css({ visibility: 'visible' }); }
		};
		// Create inteface
		if( !$('#modal').length ){
			
			// Insert modal
			var layout = modaLayout.replace(/{TITLE}/, o.title);
			$(layout).appendTo('body');
			$('#modal-content').css({ width: o.width, height: o.height }); // Set dimensions #modal-content
			
			// Optional stuff
			if($.isIE)  $('#modal-wrapper').css({ width: $('#modal-content').width() + 24 }); // 24 === Add padding + border outer #modal-content
			if(o.pos)   $('#modal-wrapper').css({ left: o.x, top: o.y }); // If needed set the position
			//if(!o.mask) $('#modal-mask').css({ background: 'none' });
			if(!o.mask) $('#modal-mask').remove();
			
			// Show modal
			$('#modal').css({ visibility: 'visible' });
			
			// Resize elements
			__resizeInterface();
			__resizeModalWrapper();
			$(window).resize(__resizeInterface);
			
			// Close events
			$('#modal-close, #modal-mask').click(__close);
			$(window).click(function(e){
				if( !$(e.target).parents('#modal').length && !o.el[0].id == 'modalHandler' ) __close();
			});
			
			// IMAGE
			if(o.type == 'image'){
				var image = new Image();
				image.onload = function(){
					$('#modal-content').append(this).css({ background: 'none' });
				};
				image.src = o.url;
				$(image).css({
					width: o.width,
					height: o.height,
					cursor: 'pointer'
				}).click(function(){ __close(); });
			}
			// AJAX
			if(o.type == 'ajax'){
				$('#modal-content').css({ minHeight: 50 });
				$.ajax({
					url: o.url,
					cache: false,
					processData: false,
					data: o.params,
					success: function(html){
						$('#modal-content').append(html).css({ background: 'none' });
						$('#modal').css({ visibility: 'visible' });
						__resizeInterface();
						if(o.cb) o.cb();
					},
					error: function(){
						$('#modal-content').append('Erreur de chargement.').css({ background: 'none' });
						$('#modal').css({ visibility: 'visible' });
						__resizeInterface();
					}
				});
			}
			// IFRAME
			if(o.type == 'iframe'){
				var iframe = '<iframe src="' + o.url + '?' + o.params + '" width="' + o.width + 'px" height="' + o.height + 'px" marginwidth="0" marginheight="0" leftmargin="0" topmargin="0" hspace="0" vspace="0" frameborder="0" height="0" scrolling="auto"></iframe>';
				$('#modal-content').append(iframe).css({ background: 'none' });
				$(iframe).focus();
			}
			// SELECTOR
			if(o.type == 'selector'){
				var selected = $(o.selector,o.el).clone();
				if( o.nocontext ){ selected = $(o.selector).clone(); }

				$('#modal-content').append(selected).css({ background: 'none' });
				if( o.selector == '#form-login-wrapper' ){
					$.attachEventsFields();
					$('#login-pseudo').focus();
					$('.popup-login').loginForm();
				}
				else if( o.selector == '#form-forgetpass' ){
					$.attachEventsFields();
					selected.forgetpassForm();
				}
				
				__resizeInterface();
				__resizeModalWrapper(); 
				$(window).resize(__resizeInterface);
			}
			// Hide some buggy elements
			if( o.mask ){ $('#overall embed, #overall object, #overall select').css({ visibility: 'hidden' }); }
			
			// IF tabs()
			if( $('#modal-content .tab').length ){
				$('#modal-content .tab').tabs();
			}
		}
	};
	/* Core
	---------------------------------------- */
	$.fn.modal = function(e,cb){
		var _this = this[0];
		var set = {
			el: $(this),
			type: false,
			url: false,
			selector: '',
			nocontext: false,
			title: '',
			params: '',
			width: 500,
			height: 500,
			pos: false,
			mask: true,
			x: 0,
			y: 0,
			cb: cb || false
		};
		// Is it an anchor tag?
		if(_this.tagName == 'A'){
			if( $('#modal').length ) $('#modal').remove();
			var o = $.extend(set,_getParams(_this));
			// type and url ok?
			if( o.type && o.url ){
				// Set 'this' postion
				if( o.pos ){
					o.x = e.pageX + 10;
					o.y = e.pageY + 10;
					o.max = $('#overall').offset().left + $('#overall').outerWidth();
				}
				__.top = $('body').scrollTop() || $('html').scrollTop();
				_setInterface(o);
				return false;
			}
			else{ // type or/and url ko
				console.log('Params KO :(');
				return false;
			}
		}
		else{ // It's not an anchor tag or #modal exist
			console.log('This is not an anchor tag or #modal exist :(');
			return false;
		}
		return false;
	};
	$('.modal').live('click',function(e){
		$(this).modal(e,function(){});
		return false;
	});
})(jQuery);

var closeModal = function(options){
	var defaults = {
		delay: 2000,
		refresh: false
	};
	var opts = $.extend(defaults, options);
	setTimeout(function(){
		$('#modal').remove();
		$('#overall embed, #overall object, #overall select').css({ visibility: 'visible' });
		if( opts.refresh ){ location.reload(true); }
	},opts.delay);
}