window.addEvent('domready', function(){
	myXtt = new Xtt();
});

var Xtt = new Class({

	initialDelayInMs:7000
	
	, waitForDataDelayInMs:10000
	, nextXttDelayInMs:11000
	, xttAnchor:false
	, dataAcquired:false
	, xttBlurb:false
	, xttDetailUrl:false

	, initialize: function() {
		// If the page does not contain an anchor, do no more.	
		if( '' == $$('.xttAnchor') ) {
			return;
		}

		this.initializeXtt();
	}

    , initializeXtt : function() {

        var delay;

		if( this.dataAcquired ) {
		    delay = this.nextXttDelayInMs;
		} else {
	    	delay = this.initialDelayInMs;
		}
		
		this.dataAcquired = false;
		this.xttBlurb = '';
   		this.xttDetailUrl = '';
		
   		var latitude = $$('.geo .latitude');
  		var longitude = $$('.geo .longitude');
  		if( !latitude[0] || !longitude[0] ) {
  			return;
		}
   		var page_from = $('location_city_form').page_from.value;
   		var queryString = 'latitude=' + latitude[0].innerHTML + '&longitude=' + longitude[0].innerHTML + '&page_from=' + page_from;

        new Ajax( "/xtt/getXtt.php"
        	, {
            	method: 'post'
            	, data: queryString
            	, onComplete: this.nextXttLoaded.bind(this)
        	}
        ).request();

		this.xttTimeoutId = this.xttTriggered.bind( this ).delay( delay );
    }
    
    , nextXttLoaded : function(response) {
    	var xtt = Json.evaluate( response );

        this.xttBlurb = xtt.blurb;

		this.xttDetailUrl = xtt.url;

		this.dataAcquired = true;
    }

    , xttTriggered : function() {
    	// If the Ajax request has not finished do nothing but setup another trigger first.
		if( !this.dataAcquired ) {
	    	xttTimeoutId = this.xttTriggered.bind( this ).delay( this.nextXttDelayInMs );
	    	return;
		}

		// If we don't have complete data start over.
		if( '' == this.xttBlurb || '' == this.xttDetailUrl ) {
	    	this.initializeXtt();
	    	return;		
		}		

		// Setup the container div.
		var xttContainer = $('xttContainer');
		if( null == xttContainer ) {
		    xttContainer = new Element( 'div', 
				{ 
				    'class':'xttContainer', 
				    'id':'xttContainer' 
				}
		    );
		} else {
			xttContainer.empty();
		}

		// Setup the blurb text and inject it into the container.
		var xttBlurbContainer = new Element( 'span' );
		xttBlurbContainer.setHTML( this.xttBlurb );		
		xttBlurbContainer.injectInside( xttContainer );
		
		// Setup the details link and inject it.
		var xttDetailLink;
		xttDetailLink = new Element( 'a',
	            {
			'href' : this.xttDetailUrl
			, 'title' : 'View Details'
		    }
		);
		xttDetailLink.appendText( 'View Details' );
		xttDetailLink.injectInside( xttContainer );
    	
    	// Swap out the anchor div with the loaded container.
    	var xttAnchor = $$('.xttAnchor');

    	if( '' != xttAnchor ) {
			xttAnchor.replaceWith( xttContainer );
			
			// Create the slide hidden and toggle it out.
			var mySlide = new Fx.Slide( 'xttContainer', {duration:1000}  ).hide().toggle();
		} 
	 	
		this.initializeXtt()
	}
});

