Cufon.replace('h1', { fontFamily: 'helvetica35', ignore: {a: true} }); // Works without a selector engine

Cufon.replace('h1.twolinebold', { fontFamily: 'helvetica65' }); // Works without a selector engine
Cufon.replace('h1.twoline', { fontFamily: 'helvetica35' }); // Works without a selector engine
Cufon.replace('div.h1', { fontFamily: 'helvetica35' });
Cufon.replace('h1.bold, div.bold, h1 strong, div.h1 strong', { fontFamily: 'helvetica65' }); // Works without a selector engine


Cufon.replace('h2', { fontFamily: 'helvetica35' });
Cufon.replace('h2.bold, h2 strong, h2 a strong', { fontFamily: 'helvetica65' });
Cufon.replace('h4.non_sifr', { fontFamily: 'helvetica35' });
Cufon.replace('h4', { fontFamily: 'helvetica35' });
Cufon.replace('h3', { fontFamily: 'helvetica35', ignore: {a: true} });
//Cufon.replace('h3.sifr-ignore)', { fontFamily: 'helvetica65' });
Cufon.replace('h3.bold, h3 strong', { fontFamily: 'helvetica65' });
Cufon.replace('h3.sifr_thin', { fontFamily: 'helvetica35' });
Cufon.replace('h3.footer_credits', { fontFamily: 'helvetica35' });
Cufon.replace('TD', { fontFamily: 'helvetica45' });

Cufon.replace('.cufon-me', { fontFamily: 'helvetica45' });
Cufon.replace('.cufon-me-bold', { fontFamily: 'helvetica45' , fontWeight: 'bold' });


// JavaScript Document
var Popup = new Class({

    Implements: [Options, Events],

    options: { title: "Title", width: 200, height: 200, adoptElement: null, add_close_button: true, use_title: true },
    popupElement: null,
    mainElement: null,
    contentElement: null,
    overlay: null,
    
    initialize: function(options) {
      this.setOptions(options);     
      this.createOverlay();
      this.createPopup();
      this.adopt();
    },
    
    show: function() {
      this.blankScreen();
      this.popupElement.fade('in');
    },
    
    createOverlay: function() {
    	this.overlay = new Element('div', {
    		
    		styles: {
    			position: 'fixed',
    			width: '100%',
    			height: '100%',
    			'z-index': '1',
    			'background-color': '#000',
    			top: '0',
    			left: '0',
    			'visibility': 'hidden'
    		}
    		
    	});
    	this.overlay.inject($(document.body));
    },
    
    setTitle : function(title) {
      this.mainElement.getElement('h1').set('html', title);
    },
    
    blankScreen : function(){
    	this.overlay.fade('0.9');
    },
    
    showScreen : function() {
    	this.overlay.fade('out');
    },
    
    close: function() {
      this.popupElement.fade('out');
      this.showScreen();
    },
    
    setPosition: function(x, y) {
      this.popupElement.setStyle('left', x);
      this.popupElement.setStyle('top', y);
      
    },
    
    centre: function() {
      var x = (window.getSize().x / 2) - (this.popupElement.getSize().x / 2);
      var y = (window.getSize().y / 2) - (this.popupElement.getSize().y / 2);
      if (y < 0) { y = 100; }
      this.setPosition(x, y);
    },

    createPopup: function() {
      this.popupElement = new Element('div', 
        {'class': 'popup', 
    	  'styles': {
	          'width': this.options.width, 
	          'height': this.options.height,
	          'z-index': '2',
	          'position': 'fixed'
	        }
        });
      this.mainElement = new Element('div', 
        {'class': 'main', 'styles': { 
          'width': this.options.width - 32, 'height': this.options.height - 40
        }
        });
      this.popupElement.setStyle('opacity', 0);
      topBar = new Element('div', {'class': 'top', 'styles': {'width': this.options.width - 10}});
      bottomBar = new Element('div', {'class': 'bottom', 'styles': {'width': this.options.width - 10}});
      leftBar = new Element('div', {'class': 'left', 'styles': {'height': this.options.height - 10}});
      rightBar = new Element('div', {'class': 'right', 'styles': {'height': this.options.height - 10}});
      brCorner = new Element('div', {'class': 'bottom-right'});
      blCorner = new Element('div', {'class': 'bottom-left'});
      trCorner = new Element('div', {'class': 'top-right'});
      tlCorner = new Element('div', {'class': 'top-left'});
      this.contentElement = new Element('div', {'class': 'content'});
      
      if (this.options.add_close_button) {
	      closeEl = new Element('a', {'class': 'close', 'href': '#'});
	      closeEl.addEvent('click', function() {
	        this.close();
	        return false;
	      }.bindWithEvent(this));
	      closeEl.inject(this.popupElement);
      }
      
      title = new Element('h1');
      topBar.inject(this.popupElement);
      bottomBar.inject(this.popupElement);
      leftBar.inject(this.popupElement);
      rightBar.inject(this.popupElement);
      brCorner.inject(this.popupElement);
      blCorner.inject(this.popupElement);
      trCorner.inject(this.popupElement);
      tlCorner.inject(this.popupElement);
      if(this.options.use_title)
      {
      	title.inject(this.mainElement);
      	this.setTitle(this.options.title);
      	
      }
      this.contentElement.inject(this.mainElement);
      this.mainElement.inject(this.popupElement);
      this.popupElement.inject($(document.body), 'top');
      this.centre();
      
    },
    
    adopt: function() {
      if (this.options.adoptElement == null) {
        return;
      }
      this.options.adoptElement.inject(this.contentElement);
    }
    
});


var Twooter = new Class({

    Implements: Events,

    initialize: function () {
    },

    getTweet: function (query, amount) {
        var t = this;
        var jsonRequest = new Request.JSONP({ url: "http://search.twitter.com/search.json",
            onComplete: function (data) {
                //alert(data.data);
        	
        	    if (data.results != null) {
                    t.fireEvent('success', data);
                }
            },
            onTimeout: function () {
                t.fireEvent('timeout');
            },
            timeout: 4000
        });

        jsonRequest.send({ data: { 'q': query, 'rpp': amount} });
    }


});

linkify = function (text) {
    if (text == null) {
        return;
    }
    var regexp = /http[^\s]+/i;
    var matches = text.match(regexp);
    if (matches != null && matches.length == 1) {
        text = text.replace(regexp, '<a href="' + matches[0] + '" target="_blank">' + matches[0] + '</a>');
    }

    return text;
}


var Tweet_rotate = new Class({
	
	initialize: function (element, timeperiod) {
		
		this.count = 0;
		this.tweets = [];
		this.current_tweet = -1;
		this.tweet = null;
		this.oldtweet = null;
		this.tweet_holder = element;
		this.timeperiod = timeperiod;
		this.setup_start_stop();
	},
	
	setup_start_stop: function() {
		
		this.tweet_holder.addEvent('mouseenter', this.pause.bind(this));
		this.tweet_holder.addEvent('mouseleave', this.resume.bind(this));
	},

	add_tweet: function(text) {
		this.tweets.include(text);
		this.count = this.count + 1;
	},
	
	start: function() {
		this.rotate();
		this.timer = this.rotate.periodical(this.timeperiod, this);
	},
	
	pause: function() {
		clearInterval(this.timer);
	},
	
	resume: function() {
		this.rotate();
		this.timer = this.rotate.periodical(this.timeperiod, this);
	},
	
	rotate: function(){
		//this.tweet_holder.slide('out');
		
		if (typeOf(this.tweet) != 'null') {
			this.oldtweet = this.tweet;
			var thisInstance = this;
			old_slide = new Fx.Slide(this.oldtweet, {
				'mode': 'horizontal'
			}).slideOut().chain(function(){
				
				thisInstance.oldtweet.destroy();
				
			});
			 
		}
		
		var tweet_to_fetch = this.current_tweet + 1;
		if (tweet_to_fetch >= this.count) {
			tweet_to_fetch = 0;
		}
		this.current_tweet = tweet_to_fetch;
		
		this.tweet = new Element('div', {
			'html': this.tweets[this.current_tweet]
			
		});
		
		this.tweet.inject(this.tweet_holder);
		new_slide = new Fx.Slide(this.tweet, {
			'mode': 'horizontal'
		}).hide().slideIn();
		
	}
	
});


var RequestQuote = new Class({
    Extends: Popup,
    initialize: function(options){
    	this.parent(options);
    },
    
    createPopup: function() {
      this.parent();
      $('requestQuote').addEvent('submit', function(event) {
    	  event.stop();
    	  this.validateAndSend();
      }.bindWithEvent(this));
    },
    
    validateAndSend: function() {
    	
    	var rqp = this;
    	
    	var jSonRequest = new Request.JSON({url: 'ajax/', onSuccess: function(responseJSON, responseText) {
    		if (responseJSON.status == 'OK') {
	    		$('requestQuoteSuccess').set('html', responseJSON.message);
		        $('requestQuoteContent').setStyle('display', 'none');
		        $('requestQuoteSuccess').setStyle('display', 'block');
		        $('requestQuoteMsg').setStyle('display', 'none');
		        
		        _gaq.push(['_trackPageview', '/callback_goal']);
				
		        closeFunction.delay(1800);
			    resetFunction.delay(3800);
    		} else {
    			$('requestQuoteMsg').set('html', responseJSON.message);
    			$('requestQuoteMsg').setStyle('display', 'block');
    		}
          
        
	  }}).post({'action': 'sendQuoteRequest', 'contact_email': $('contact_email').value, 'cust_name': $('contact_name').value, 'cust_telephone': $('contact_telephone').value, 'contact_enquiry': $('contact_enquiry').value});
      
	 var closeFunction = function(){ 
   	  rqp.close(); 
     };
     
     var resetFunction = function(){
   	  $('requestQuoteContent').setStyle('display', 'block');
         $('requestQuoteSuccess').setStyle('display', 'none');
     }
    	
    }
});


var callback_popup;

window.addEvent('domready',function(){

    if (typeOf($('twitter')) != 'null') {
		var AnvicTwooter = new Twooter();
	    
	    AnvicTwooter.addEvent('success', function (data) {
	    	if (data != null) {
	    		tweet_rotator = new Tweet_rotate($('twitter'), 4000);
	    		
	    		data.results.each(function(item){
	        		
	        		var text = item.text;
	        		tweet_rotator.add_tweet(text);
	        		
	        	});
	    		
	    		tweet_rotator.start();
	        	
	        } else {
	            AnvicTwooter.fireEvent('timeout')
	        }
	    });
	    AnvicTwooter.addEvent('timeout', function () {
	        $('twitter').set('html', 'Oh no! Twitter seems to be down at the moment!');
	    });
	    AnvicTwooter.getTweet('from:AnvicNW', 5);
    }
    
    if (typeOf($('requestCallback')) != 'null') {
    
    	callback_popup = new RequestQuote({ title: "Callback form", width: 480, height: 508, adoptElement: $('callback_request_container'), add_close_button: true, use_title: false });
    	$('requestCallback').addEvent('click', function(event){
    		event.stop();
    		
    		callback_popup.show();
    		
    		
    	})
    }
    
    if (typeOf($('directions_lookup')) != 'null') {
    	$('directions_lookup').addEvent('submit', function(event){
    		event.stop();
    		
    		postcode = $('postcode').value;
    		
    		// check if a radio button was selected and use those coords
    		
    		var values = $$('input[name=directions_to]:checked').each(function(e){
    			to_lat = $('to_lat' + e.value).value;
        		to_lon = $('to_lon' + e.value).value;        		 
    			
    		});
    		

    		// or use default
    		if (typeOf(to_lat) == 'null') {
	    		to_lat = $('to_lat1').value;
	    		to_lon = $('to_lon1').value;
    		}
	    	
    		get_directions(postcode, to_lat, to_lon);
    		
    		
    	})
    }
    
    if (typeOf($('map_canvas')) != 'null') {
    	to_lat = $('to_lat1').value;
		to_lon = $('to_lon1').value;
		
    	var latlng = new google.maps.LatLng(to_lat, to_lon);
        var myOptions = {
          zoom: 15,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map($('map_canvas'),
            myOptions);
        
        var marker = new google.maps.Marker({
            position: latlng, 
            map: map, 
            title:""
        });
        
        // add parking pins
        for (i=2; i<6; i++) {
        	if (typeOf($('to_lat' + i)) != 'null') {
        		new_lat = $('to_lat' + i).value;
        		new_lon = $('to_lon' + i).value;
        		
            	var newlatlng = new google.maps.LatLng(new_lat, new_lon);
            	
            	var customIcon = "http://www.google.com/mapfiles/markerP.png";
            	
            	var newmarker = new google.maps.Marker({
                    position: newlatlng, 
                    map: map,
                    icon: customIcon,
                    title:"P"
                });
        	}
        }
        
    }
    
    
    if (typeOf($('enquiry_field')) != 'null') {
    	$('other_services').addEvent('click', function(){
    		if (this.getProperty('checked')) {
    			$('enquiry_field').slide('in');
    		} else {
    			$('enquiry_field').slide('out');
    		}
    	});
    	$('enquiry_field').slide('hide');
    }
    
	
});




function list_directions(data, directionsDisplay, result, map) {
	dir_slide = new Fx.Slide($('directions')).slideOut().chain(function(){
		
		$('directions').set('html', '');
	
		// initialize header row
		instruction_elem = new Element('div', {
			'html': 'Instructions',
			'class': 'instruction'
		});
		
		duration_elem = new Element('div', {
			'html': 'Duration',
			'class': 'duration'
		});
		
		distance_elem = new Element('div', {
			'html': 'Distance',
			'class': 'distance'
		});
		
		new_row = new Element('div');
		
		instruction_elem.inject(new_row);
		duration_elem.inject(new_row);
		distance_elem.inject(new_row);
		new_row.inject($('directions'));
		
		some_instructions = false;
		
		data.routes.each(function(route){
			
			route.legs.each(function(leg){
				
				leg.steps.each(function(step){
					
					some_instructions = true;
			
					//console.log(step);

					instruction_elem = new Element('div', {
						'html': step.instructions,
						'class': 'instruction'
					});
					
					duration_elem = new Element('div', {
						'html': step.duration.text,
						'class': 'duration'
					});
					
					distance_elem = new Element('div', {
						'html': step.distance.text,
						'class': 'distance'
					});
					
					new_row = new Element('div', {				
					});
					
					instruction_elem.inject(new_row);
					duration_elem.inject(new_row);
					distance_elem.inject(new_row);
					new_row.inject($('directions'));

				});
				
				// Add the total distance
				sum_dist = leg.distance.text;
				sum_duration = leg.duration.text;
				
				instruction_elem = new Element('div', {
					'html': 'Total',
					'class': 'instruction'
				});
				
				duration_elem = new Element('div', {
					'html': sum_duration,
					'class': 'duration'
				});
				
				distance_elem = new Element('div', {
					'html': sum_dist,
					'class': 'distance'
				});
				
				new_row = new Element('div', {				
				});
				
				instruction_elem.inject(new_row);
				duration_elem.inject(new_row);
				distance_elem.inject(new_row);
				new_row.inject($('directions'));
				
				
			});
			
			
			
		});
		
		if (some_instructions) {
			// Add print button
			instruction_elem = new Element('img', {
				'src': 'skin/anvic/images/locations/btn_print.png',
				'styles': {
					'float': 'right'
				},
				'events': {
					'click': function(){
						window.print()
					}
				},
				'id': 'print_button'
			});
			instruction_elem.inject($('directions'));
		}
		
		

		
		
		// add a print button below the directions
		/*button = new Element('IMG', {
			src: 'skin/anvic/images/locations/btn_print.png'
		})
		*/	
		
		
		$('map_canvas').tween('width', '300');
		
		$('gmap_controls').tween('width', '400');
		
		dir_slide.slideIn();
		
	}).chain(function(){
		directionsDisplay.setDirections(result);
		
	    google.maps.event.trigger(map, 'resize');
	});
}

/**
 * Fetch directions from postcode to desctination
 * @param lat
 * @param lon
 * @returns int location_id on success, boolean false on fail.
 */
function get_directions(from_postcode, to_lat, to_lon) {
	
	var directionDisplay;
	var directionsService = new google.maps.DirectionsService();
	var map;
	
	directionsDisplay = new google.maps.DirectionsRenderer();
	  var manchester = new google.maps.LatLng(to_lat, to_lon);
	  var myOptions = {
	    zoom:6,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  }
	  map = new google.maps.Map($("map_canvas"), myOptions);
	  directionsDisplay.setMap(map);
	
	  var start = from_postcode + ',UK';
	  var end = to_lat + ',' + to_lon;
	  
	  var request = {
	    origin:start,
	    destination:end,
	    unitSystem:google.maps.UnitSystem.IMPERIAL,
	    travelMode: google.maps.TravelMode.DRIVING
	  };
	  directionsService.route(request, function(result, status) {
		//console.log(result);
	    if (status == google.maps.DirectionsStatus.OK) {
	    	list_directions(result, directionsDisplay, result, map);
	    	
	    }
	  });

}



/**
 * Check that a set of coordinates is within a bounding box covering the UK.
 * @param latitude
 * @param longitude
 * @returns {Boolean}
 */
function valid_coords(latitude, longitude) {	
	return ((latitude > 48)&&(latitude < 59)&&(longitude < 3.3)&&(longitude > -9.7));
}


/**
 * Display any error messages relating to the map api and data lookups.
 * @param message
 */
function display_error(message) {
	$('error_message').set('html', message);
	$('error_message').setStyle('display', 'block');
}


function clear_error() {
	$('error_message').setStyle('display', 'none');
	$('error_message').set('html', '');
}


