jQuery(document).ready(function($)
{
    var Amp = {    
       
        entryId : '',

        attachHandlers : function() {        
           
	        $("a").each(function() {
		        if (this.rel.toLowerCase().match('amp')){
			        $(this).click(function() {
				        Amp.show(this);
				        return false;
			        });
		        }
	        });	
        }, 
        
        destroyElement : function(id) {
	        if(el = document.getElementById(id)){
		        el.parentNode.removeChild(el);
	        }
        },	      
    	
        initialize : function() {          
                        
            Amp.destroyElement('AmpOverlay'); 
	        Amp.destroyElement('AmpContainer');
    	    
	        Amp.addLightboxToPage(); 
	        
	        Amp.attachHandlers();  
    	    
	        $('#AmpValidate').bind('click', Amp.validateAnswer); 
	        $('#AmpClose').bind('click', Amp.close);
	        $('#AmpDecodeMails').bind('click', Amp.decodeEmails);
	        
	        $('#AmpAnswer').keypress(function (e) {	    
	            if (e.which == 13)
	                Amp.validateAnswer();
	        });
    	    
    	    Amp.hideElements();
	           
        },
        
        hideElements: function() {
        
            $("#AmpOverlay").hide();
	        $("#AmpContainer").hide(); 
	        $('#AmpStatus').hide(); 
	        $('#AmpError').hide();     	    
	        $('#AmpQuestionPane > p').hide();    	    
	        $("#AmpQuestionPane").hide();	      
        },
                
        addLightboxToPage : function() {
        
            var html = '';
            
            html +=     '<div id="AmpOverlay"></div>';
            html +=     '<div id="AmpContainer">';
		    html +=         '<div id="AmpWrapper">';
	        html +=             '<div id="AmpTopBar">';
		    html +=                 '<h1>AMP</h1>';
		    html += 		        '<a href="#" title="close" id="AmpClose"><span>close</span></a>';
		    html +=	            '</div><!-- AmpTopBar -->';
		    html +=	            '<div id="AmpExplanationPane">';
		    html +=		            '<h1><span>AMP :: Ajax Mail Protector</span></h1>';
		    html +=		            '<p>L\'adresse sur laquelle vous venez de cliquer est protégée (dans un souci de lutte contre le spam).</p>';			
		    html +=                 '<p>Afin de la révéler (ainsi que d\'éventuelles autres adresses protégées sur la même page), il vous suffit de répondre à la question suivante :</p>';
		    html +=	            '</div><!-- AmpExplanationPane -->';
		    html +=             '<div id="AmpStatus"></div>';		   
		    html +=	            '<div id="AmpQuestionPane">';
		    html +=		            '<p>Quelle est la somme de<br />deux et un ? (le chiffre)</p>';
		    html +=                 '<span><p id="AmpError">La réponse est erronée</p></span>';
		    html +=		            '<input id="AmpAnswer" type="text" />';
		    html +=		            '<a id="AmpValidate" href="#" title="valider"><span>valider</span></a>';
		    html +=	            '</div><!-- AmpQuestionPane -->';
		    html +=         '</div><!-- AmpWrapper -->';
	        html +=     '</div><!-- AmpContainer -->';   
            
            $("body").append(html);		
        },       
       
        
        show : function(senderLink) {
            $("select, embed, object").hide();
            
            // Stretch overlay to fill page and fade in
	        // In array we've got : pageWidth, pageHeight, windowWidth, windowHeight
	        var arrayPageSize = Amp.getPageSize();
    		
	        $("#AmpOverlay").hide().css(
	            { 
	                width : '100%', 
	                height: arrayPageSize[1] + 'px', 
	                opacity : 0.8
	            }
	        ).fadeIn();		

	        // Calculate top and left offset for the lightbox 
	        var arrayPageScroll = Amp.getPageScroll();
	        var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
	        var lightboxLeft = arrayPageScroll[0];
	        $('#AmpContainer').css(
	            {
	                top : lightboxTop + 'px', 
	                left: lightboxLeft + 'px'
	            }
            ).show();              
            
            $('#AmpStatus').show('slow');     
            
            Amp.fetchQuestion();
        },
        
        decodeEmails : function() {
        
            $("a").each(function() {
		        if (this.rel.toLowerCase().match('amp')) {
    		        
		            // Closure, to have a reference to be used in the callback
		            var $self = $(this);
		            
		            var id = $(this).attr('id');
		            
		            // Hack introduced because we use element id to hide crypted mail, and
		            // since an element id has to be unique we use three '#' to differentiate them.
		            if (id.match('###'))
		                id = id.substring(0, id.indexOf('###'));
    		        
		            $.getJSON('http://services.heig-vd.ch/Amp2/Backend.ashx?o=decode&id=' + id + '&jsoncallback=?',
                        function(decodedMail) {
                            $self.attr('href', 'mailto:' + decodedMail);                        
                            $self.unbind('click'); 
                            
                            $self.html($self.html() + ' [' + decodedMail + ']');
                        }
                    );
                }
            });
        },       
       
        fetchQuestion : function() {
        
            $('#AmpQuestionPane > p').hide();
            
            $.getJSON('http://services.heig-vd.ch/Amp2/Backend.ashx?jsoncallback=?', 
                function(data) {
                    $('#AmpStatus').hide('slow');    
                    Amp.entryId = data.EntryId;
                    $('#AmpQuestionPane').slideDown(600, function() {
                        $('#AmpQuestionPane > p').html(data.Value).fadeIn('slow');    
                        $('#AmpAnswer').attr('value', '');     
                        $('#AmpAnswer').focus();     
                    });
                }
            );            
        }, 
        
        validateAnswer : function() {           
            
            $.getJSON('http://services.heig-vd.ch/Amp2/Backend.ashx?o=validate&a=' + $('#AmpAnswer').attr('value') + '&id=' + Amp.entryId + '&jsoncallback=?',
                function(isValid) {                
                    if (isValid) {
                        Amp.decodeEmails();
                        Amp.close();
                    }
                    else {                   
                        
                        $('#AmpError').
                            fadeIn('slow').
                            animate( {opacity: 1.0}, 3000).
                            fadeOut('slow');                   
                    }
                }
            );
        },     
     
        close : function() {
            
            $("#AmpContainer").fadeOut(1000);
	        $("#AmpOverlay").fadeOut(2000, Amp.hideElements);	        
    	    
	        $("select, object, embed").show();
        },
        
        getPageSize : function(){
		    var xScroll, yScroll;

		    if (window.innerHeight && window.scrollMaxY) {	
			    xScroll = window.innerWidth + window.scrollMaxX;
			    yScroll = window.innerHeight + window.scrollMaxY;
		    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			    xScroll = document.body.scrollWidth;
			    yScroll = document.body.scrollHeight;
		    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			    xScroll = document.body.offsetWidth;
			    yScroll = document.body.offsetHeight;
		    }

		    var windowWidth, windowHeight;

		    if (self.innerHeight) {	// all except Explorer
			    if(document.documentElement.clientWidth){
				    windowWidth = document.documentElement.clientWidth; 
			    } else {
				    windowWidth = self.innerWidth;
			    }
			    windowHeight = self.innerHeight;
		    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			    windowWidth = document.documentElement.clientWidth;
			    windowHeight = document.documentElement.clientHeight;
		    } else if (document.body) { // other Explorers
			    windowWidth = document.body.clientWidth;
			    windowHeight = document.body.clientHeight;
		    }	

		    // for small pages with total height less then height of the viewport
		    if(yScroll < windowHeight){
			    pageHeight = windowHeight;
		    } else { 
			    pageHeight = yScroll;
		    }

		    // for small pages with total width less then width of the viewport
		    if(xScroll < windowWidth){	
			    pageWidth = xScroll;		
		    } else {
			    pageWidth = windowWidth;
		    }

		    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		    return arrayPageSize;
	    },
    	
	    getPageScroll : function(){
    		
		    var xScroll, yScroll;

		    if (self.pageYOffset) {
			    yScroll = self.pageYOffset;
			    xScroll = self.pageXOffset;
		    } else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
			    yScroll = document.documentElement.scrollTop;
			    xScroll = document.documentElement.scrollLeft;
		    } else if (document.body) {// all other Explorers
			    yScroll = document.body.scrollTop;
			    xScroll = document.body.scrollLeft;	
		    }

		    arrayPageScroll = new Array(xScroll,yScroll) 
		    return arrayPageScroll;
	    }
    };
    
    Amp.initialize();
});