
activatePdfCatchForm = function(downloadFile){

	$('pdf_download').value = downloadFile;

	$('pdf_catch_form').observe('submit', function(event){
		
		var s_email = $('email').value;

		if ( s_email != "" ){
			if ( echeck(s_email) ){

				var formValues = $('pdf_catch_form').serialize();

				new Ajax.Request('/cm/data/bridge2aid/scripts/ajax_catch_pdf_download.php', {
					method: 'get',
					parameters: formValues,
					onComplete: function(response){
						window.location = downloadFile;
						modal.close();
					}
				});

			} else {
				alert("Please enter a valid email address");
			}

		} else {
			window.location = downloadFile;
			modal.close();
		}
		event.stop();

	});
}

function echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	     return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	     return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	     return false
	 }

	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}
	
	if (str.indexOf(" ")!=-1){
		return false
	}

	return true					
}

// Globalise the downloadFile variable
var downloadFile;

document.observe("dom:loaded", function() {

	// Create one modal box for all modal content
	modal = new Control.Modal('empty_modal',{
		fade: true,
		overlayOpacity: 0.25,
		fadeDuration: 0.25,
		width: 580,
		className: 'modal_window',
		afterClose: function(){
			modal.remoteContentLoaded=false;
			modal.container.update('');
		}
	});

	$$('a').each( function(element){

		if ( element.readAttribute('href') != null && element.readAttribute('href').endsWith(".pdf")){
			
			
			element.writeAttribute('onclick', '');
			
			element.observe('click', function(event){

				downloadFile = element.readAttribute('href');

				new Ajax.Updater(modal.container, '/cm/data/bridge2aid/scripts/ajax_catch_pdf_download.php', {
					method: 'get',
					onComplete: function(){
						modal.open('empty_modal');
						activatePdfCatchForm(downloadFile);
					}
				});
	
				Event.stop(event);
			});

		}

	});

});