//Functions
function checkDate(date) 
	{
	
	// Regular expression used to check if date is in correct format dd/mm/yyyy
	var pattern = new RegExp([0-3][0-9]/0|1[0-9]/19|20[0-9]);
	if(date.value.match(pattern))
		{
			
			return true;
		}
	else
		{
			return false;
		}
		
	}
	
function popIn(width, height, source, id)
	{
		var thisWidth = width;
		var thisHeight = height;
		var thisId = id;
		
		//Window dimensions
		var windowHeight = window.getHeight();
		var windowWidth = window.getWidth();
		var scrollTop = window.getScrollTop();
		
		//position
		var top = (windowHeight/2) - (thisHeight/2);
		var left = (windowWidth/2) - (thisWidth/2);
		
		//Create Div
		var poc = new Element('div', {
					    'styles': {
						'display': 'block',
						'position': 'absolute',
						'top': eval(top),
						'left': eval(left),
						'z-index': '100',
						'width': eval(thisWidth),
						'height': eval(thisHeight),
						'padding': '0px 0px',
						'visibility': 'hidden'
					    },
					   'class': 'overlay',
					   'id': thisId
   				 });
		
		//Insert into page
		poc.injectTop(document.body);
		
		var url = "popin.php"
		var data = Object.toQueryString({id: id, source: source});
		//get form
		new Ajax(url, {
			method: 'get',
			data: data,
			update: $(thisId),
			evalScripts: true,
			onComplete: function(){
					//resize to fit form
					var childheight = parseInt($(thisId+"_child").getStyle('height'));
					$(thisId).setStyle('height', childheight+50);
					repositionOverlay(thisId);
					//$(id).setStyle('visibility', 'visible');
					var fadein = new Fx.Style(thisId, 'opacity', {duration: 500, wait: false});
					fadein.start(0,1);
									    
				}
		}).request();
	}
function closeOverlay(element)
	{
		$(element.id).remove();
	}
	
function repositionOverlay(element)
	{
		//Element dimensions
		var height = parseInt($(element).getStyle('height'));
		var width = parseInt($(element).getStyle('width'));
		
		//Window dimensions
		var windowHeight = window.getHeight();
		var windowWidth = window.getWidth();
		var scrollTop = window.getScrollTop();
		
		//New position
		var top = (windowHeight/2) - (height/2) + scrollTop;
		var left = (windowWidth/2) - (width/2);
		
		$(element).setStyle('top', top);
		$(element).setStyle('left', left);
	}


function submitForm(form)
	{
					
		var req = false;
		var dateError = false;
		var errorMessage = "";
		
		//Check fields
		var required = $$('form#'+form.id+' .required');
		required.each(function(element) {
					     
				$(element).setStyle("border-color", "#A2D8ED");
				if($(element).value == "")
				{
					$(element).setStyle("border-color", "#FF0000");
					req = true;
				}
			});
		
		//Check date fields
		if($$('form#'+form.id+' .date'))
		{
			var dates = $$('form#'+form.id+' .date');
			dates.each(function(element) {
						     
					if($(element).value != "" && checkDate($(element)) == false)
					{
						dateError = true;
					}
					else
					{
						dateError = false;
					}
				});
		}
		
		//Error messaeges
		if(req == true)
			{
				errorMessage = "Please complete the required fields highlighted in red";
				if(dateError == true)
				{
					errorMessage += " and make sure your date(s) are in the correct format";
				}
				alert(errorMessage);
				return false;
			}
		else if(req == false && dateError == true)
			{
				alert("Please make sure your date(s) are in the correct format");
			}
		else if(req == false)
			{
				return true;
			}
	}
	
	
function switchNav(id)
	{
		$(id).setStyle("background-position", "left -23px");
		var alink = $(id).getElement('a');
		alink.setStyle("background-position", "right -23px");
	}
function reverseNav(id)
	{
		if(!$(id).hasClass('on'))
		{
			$(id).setStyle("background-position", "top left");
			var alink = $(id).getElement('a');
			alink.setStyle("background-position", "top right");
		}
	}

function changeBanner(id) 
	{
		id += "_content";
		var div = $$('div#banner_content div');
		div.each(function(element) {
				$(element.id).setStyle('display', 'none');
			});
		
		var fadein = new Fx.Style(id, 'opacity', {duration: 400, wait: false});
		$(id).setStyle('visibility', 'hidden');
		$(id).setStyle('display', 'block');
		fadein.start(0,1);
	}
	
function SearchLabel(id) 
	{
		if($(id).value == "search coverbox site")
		{
			$(id).value = "";
			$(id).setStyle('color', '#000');
		}
		else if($(id).value == "")
		{
			$(id).setStyle('color', '#CCC');
			$(id).value = "search coverbox site";
		}
	}

function startBannerCycle(delay)
	{
		//var bannerCycle = setTimeout("bannerCycle()", 3000);

	}
function stopBannerCycle()
	{
		clearTimeout(bannerCycle);
	}
	
	
function getFleetStats(id)
	{
		var url = "get_fleet_stats.php?id="+id;
		var ajaxlog = $('fleet_stat_container');
		ajaxlog.empty().addClass('ajax-loading');
		
		new Ajax(url, {
			method: 'get',
			update: $('fleet_stat_container'),
			onComplete: function(){
				ajaxlog.removeClass('ajax-loading');
				}
		}).request();
	}
	
function attachRating(rating_id)
	{
		for(e = 1; e<=1; e++)

		{
			$('rating_'+rating_id+"_"+e).addEvent('mouseover', function() {

					var score = element.id.split("_")[2];
					var rating_id = element.id.split("_")[1];
					
					for(var x = score; x > 0; x--)
					{
						$('rating_'+rating_id+"_"+x).setStyle('background-position','top left');		
					}
									   
				});
			$('rating_'+rating_id+"_"+e).addEvent('mouseout', function() {				   
					var score = element.id.split("_")[2];
					var rating_id = element.id.split("_")[1];
					
					for(var x = score; x > 0; x--)
					{
						$('rating_'+rating_id+"_"+x).setStyle('background-position','left -20px');		
					}						   
				});
			
			$('rating_'+rating_id+"_"+e).addEvent('click', function() {
									
					var score = element.id.split("_")[2];
					var rating_id = element.id.split("_")[1];				
									
					//send rating
					var url = "update_rating.php"
					var data = Object.toQueryString({id: rating_id, score: score});
					//get form
					
					$('stars_'+rating_id).empty().addClass('loading');
					new Ajax(url, {
						method: 'get',
						data: data,
						update: $('rating_'+rating_id),
						evalScripts: true,
						onComplete: function(){									
								//attach events
								attachRating(rating_id);
								}
						}).request();
						   
				});
			}
	}
	
	
//Attach Events
window.addEvent('domready', function(){
						 
	if($$('li.nav'))
		{
			var nav = $$('li.nav');
			nav.each(function(element) {
				element.addEvent('mouseover', function(){
				switchNav(element.id);
				});
			});
		}
	if($E('li.on'))
		{
			$E('li.on').setStyle("background-position", "left -23px");
			var alink = $E('li.on').getElement('a');
			alink.setStyle("background-position", "right -23px");
		}
		
	if($$('li.nav'))
		{
			var nav = $$('li.nav');
			nav.each(function(element) {
				element.addEvent('mouseout', function(){
				reverseNav(element.id);
				});
			});
		}
		
	if($$('ul#banner_links li'))
		{
			var benefits = $$('ul#banner_links li');
			benefits.each(function(element) {
				
				var fx = new Fx.Styles(element, {duration:400, wait:false});
				
				element.addEvent('mouseover', function(){
					changeBanner(element.id);
					fx.start({color: '#fff'});	
				});
				
				element.addEvent('mouseout', function(){
					fx.start({color: '#5d9641'});	
				});
				
			});
		}
	if($('search_term'))
		{
			var searchTerm = $('search_term');
			
			searchTerm.addEvent('focus', function(){
				SearchLabel(searchTerm.id);
			});
				
			searchTerm.addEvent('blur', function(){
				SearchLabel(searchTerm.id);
			});

		}
	if($('banner_content'))
		{
			startBannerCycle(3000);
		}
	if($('pp'))
		{
			$('pp').addEvent('click', function(){
						popIn(400, 300, 'privacy_popin.php', 'privacy_policy');
						});
		}
	/* if($('login_link'))
		{
			$('login_link').addEvent('click', function(){
						popIn(400, 200, 'login_popin.php', 'login_popin');
						});
		} */
		
	 if($('big_bro'))
		{
			$('big_bro').addEvent('click', function(){
						popIn(400, 400, 'big_bro_popin.php', 'big_bro_popin');
						});
		}
		
	/* if($('tips_scroller'))
		{
			
			var scroll = new Fx.Scroll('tips_scroller', {
			wait: false,
			duration: 500
			});
			
			//scroll.toElement('scrolltop');
			
			var scroll2 = new Fx.Scroll('tips_scroller', {
			wait: false,
			duration: 14000,
			transition: Fx.Transitions.linear,
			onComplete: function(){
					scroll.toElement('scrolltop');
					$('tips_scroller').setStyle('overflow', 'auto');
				}
			});
			
			scroll2.toElement('scrollbottom');
			
		} */
		
	if($('savings_calculator'))
		{
			$('savings_calculator').addEvent('submit', function(e) {
											    
				/* Prevent the submit event */
				new Event(e).stop();
				
				/* validate form */
				if(submitForm($('savings_calculator')) == true)
				{
			 
					/* This empties the log	 */
					var log = $('savings_result').empty();
				 
					/**
					 * send takes care of encoding and returns the Ajax instance.
					 * onComplete removes the spinner from the log.
					 */
					this.send({
						update: log,
						onComplete: function() {
						}
					});
				}
			});	
		}
		
	if($('submit_tip_form'))
		{
			$('submit_tip_form').addEvent('submit', function(e) {
											    
				/* Prevent the submit event */
				new Event(e).stop();
				
				/* validate form */
				if(submitForm($('submit_tip_form')) == true)
				{
			 
					/* This empties the log	 */
					var log = $('tip_result').empty().addClass('loading');
				 
					/**
					 * send takes care of encoding and returns the Ajax instance.
					 * onComplete removes the spinner from the log.
					 */
					this.send({
						onComplete: function() {
							$('submit_tip').empty();
							$('submit_tip').setHTML("<p class=\"success\">Thank you for submitting your fuel saving tip!</p>");
						}
					});
				}
			});	
		}
		
	//send to a friend - right
	if($('send_to_a_friend_right'))
		{
			$('send_to_a_friend_right').addEvent('submit', function(e) {
											    
				/* Prevent the submit event */
				new Event(e).stop();
				
				/* validate form */
				if(submitForm($('send_to_a_friend_right')) == true)
				{
			 
					/* This empties the log	 */
					var log = $('send_result').empty().addClass('loading');
				 
					/**
					 * send takes care of encoding and returns the Ajax instance.
					 * onComplete removes the spinner from the log.
					 */
					this.send({
						onComplete: function() {
							$('send_to_a_friend_right').empty();
							$('send_to_a_friend_right').setHTML("<p class=\"success\">This page has been sent to your friend!</p>");
						}
					});
				}
			});	
		}
		
	//live rating
	if($$('div.rating'))
	{
		liverating = $$('div.rating');
		liverating.each(function(element){
								 
			element.addEvent('mouseover', function() {
					
					var score = element.id.split("_")[2];
					var rating_id = element.id.split("_")[1];
					
					for(var x = score; x > 0; x--)
					{
						$('rating_'+rating_id+"_"+x).setStyle('background-position','top left');		
					}
									   
				});
			element.addEvent('mouseout', function() {				   
					var score = element.id.split("_")[2];
					var rating_id = element.id.split("_")[1];
					
					for(var x = score; x > 0; x--)
					{
						$('rating_'+rating_id+"_"+x).setStyle('background-position','left -20px');		
					}						   
				});
			
			element.addEvent('click', function() {
									
					var score = element.id.split("_")[2];
					var rating_id = element.id.split("_")[1];				
									
					//send rating
					var url = "update_rating.php"
					var data = Object.toQueryString({id: rating_id, score: score});
					//get form
					
					$('stars_'+rating_id).empty().addClass('loading');
					new Ajax(url, {
						method: 'get',
						data: data,
						update: $('rating_'+rating_id),
						evalScripts: true,
						onComplete: function(){									
								//attach events
								attachRating(rating_id);
								
								}
						}).request();
											   
				});
						 
		});
	}
		
	if($('add_tip_comment'))
		{
			$('add_tip_comment').addEvent('submit', function(e) {
											    
				/* Prevent the submit event */
				new Event(e).stop();
				
				/* validate form */
				if(submitForm($('add_tip_comment')) == true)
				{
			 
					/* This empties the log	 */
					var log = $('tip_result').empty().addClass('loading');
				 
					/**
					 * send takes care of encoding and returns the Ajax instance.
					 * onComplete removes the spinner from the log.
					 */
					this.send({
						onComplete: function() {
							$('comment').empty();
							$('comment').setHTML("<p class=\"success\">Thank you for submitting your comment on this fuel saving tip!</p>");
						}
					});
				}
			});	
		}
		
	if($('fuel'))
	{
		var fuel = new Fx.Slide('fuel_slider', {duration: 390});
		fuel.hide();
		
		$('fuel').addEvent('click', function(){fuel.toggle();} );
	}
	if($('whatis'))
	{
		var whatis = new Fx.Slide('whatis_slider', {duration: 390});
		whatis.hide();
		
		$('whatis').addEvent('click', function(){whatis.toggle();});
	}
	if($('howmuch'))
	{
		var howmuch = new Fx.Slide('howmuch_slider', {duration: 390});
		howmuch.hide();
		
		$('howmuch').addEvent('click', function(){howmuch.toggle();});
	}
	
	if($$('span.view_stats'))
	{
		var stats = $$('span.view_stats');
		stats.each(function(element) {
			
			element.addEvent('mouseup', function(){
				getFleetStats(element.id);	
			});
						
		});
	}	
	//Tool Tips
	var Tips1 = new Tips($$('.tip'));
		
}); 
window.addEvent('resize', function() {
	if($$('div.overlay'))
		{
			var overlay = $$('div.overlay');
			overlay.each(function(element) {
				repositionOverlay(element);
			});
		}
});