

$(document).ready(function() {	

	function gup( name , _url)
	{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( _url );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}
	//select all the a tag with name equal to modal
	function openModal(e) {
		//Cancel the link behavior
		e.preventDefault();
		
		////
    var fm = gup('form', $(this).attr('rel'));
    var pars = {};
    if(''!=fm) {
    	pars = $('#'+fm).serialize();	
    	
	    var valid = false;
	    eval('valid = '+fm+'_validate()');
	    if(!valid) {
	    	return;
	    }    	
    }
    
		////
		
		//Get the A tag
		var id = $(this).attr('href');
	
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(200);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
        
    $.post($(this).attr('rel'), pars, function(data) {
			//Set the popup window to center
			//alert(data);
			$(id).html(data);
			$(id).css('top',  winH/2-$(id).height()/2);
			$(id).css('left', winW/2-$(id).width()/2);
			//transition effect
			$(id).fadeIn(100);     	
    }, 'html');          		
	}
	
	$('a[name=modal]').bind("click", openModal);
	
	//if close button is clicked
	function closeModal (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		$('.window').hide();
	}
	
	$('.window .close').bind("click", closeModal);	
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			

	$(window).bind('resize.DOMWindow',function(){
		//Get the screen height and width
		if($('#mask').css('display')=='block') {
			var maskHeight = $(document).height();
			var maskWidth = $(document).width();
		
			//Set heigth and width to mask to fill up the whole screen
			$('#mask').css({'width':maskWidth,'height':maskHeight});
			
			//transition effect		
			$('#mask').fadeIn(200);	
			$('#mask').fadeTo("slow",0.8);	
			
		}
	});


	
});

function md_close() {
		$('#mask').hide();
		$('.window').hide();	
}
