var offers = {};

var calculator = {};

var amount = null;
var establishfee = null;
var balloon = 0;
var accountfee = 5;
var term = null;
var rate = null;
var desposit = null;
var n = null;
var uplift = null;
var test = null;
var total = null;
var x = null;
var result = null;

var userInteraction = false;

calculator.tracking = {
	tracked : false,
	
	trackGA : function() {
		
		if (!calculator.tracking.tracked) {
			_gaq.push(['_trackPageview', '/virtual/calculator/start']);
			
			calculator.tracking.tracked = true;
		}
	}
}


calculator.algorithm = {
	activate : function(type, user) {

		function addCommas(nStr) {
			nStr += '';
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		}

	
		amount = $('.calculator li.amount input').val();
		term = $('.calculator li.loan-term select option:selected').val();
		rate = $('.calculator li.interest-rate input[type="text"]').val() / 100;
		desposit = $('.calculator li.deposit input').val();
		

		
		total = amount - desposit;	
		
		var clickedUser = $('input[name="loan-type"]:checked').val();
		if(user != clickedUser) {
			user = clickedUser;
		}
		
		
		
		switch(user) {
		case 'private':
			if(balloon == 0) {
				n = term * 1;
				x = 0;
			} else {
				n = term - 1;
				x = accountfee * 1;
			}
			if(term <= 48) {
				first = 1+rate/365;
				second = 1+4*rate/365;
				uplift = first*second; 
				uplift = Math.round(uplift*10000+0.5)/10000;
			} else {
				first = 1461/1460;
				second = 1+rate/365;
				third = 1+4*rate/365;
				uplift = first*second*third; 
				uplift = Math.round(uplift*10000+0.5)/10000;
			}
			break;
		case 'business':
			n = term * 1;
			if(balloon == 0) {
				x = 0;
			} else {
				x = accountfee * 1;
			}
			uplift = 1;
			break;
		}		

		/*console.log('start');
		console.log('user: '+user);
		console.log('amount: '+amount);
		console.log('term: '+term);
		console.log('rate: '+rate);
		console.log('desposit: '+desposit);
		console.log('balloon: '+balloon);
		console.log('n: '+n);
		console.log('x: '+x);
		console.log('uplift: '+uplift);
		console.log('balloon: '+balloon);
		console.log('end');*/
		
		if(rate != 0 && amount != '' && amount != '0') {

			switch(user) {
			case 'private':
				monthlyrepayment = ((total + establishfee - ((((total *  balloon) - x) / uplift) * (1 - rate/12) * Math.pow((1+rate/12), -n)))) / ( ( 1 - Math.pow((1+rate/12), -n) ) / (rate/12)) * uplift + accountfee;
				break;
			case 'business':
				//AmtFin+EstabFee-(AmtFin*Balloonpc*((1+Rate/12)^(-Term))))/(((1-((1+Rate/12)^-Term))/(Rate/12))*(1+Rate/12))+AccFee
				monthlyrepayment = ((total + establishfee - ((((total *  balloon))) * Math.pow((1+rate/12), -n)))) / ( (( 1 - Math.pow((1+rate/12), -n) ) / (rate/12)) * (1 + rate/12)) + accountfee;
				
				break;
			}
			monthlyrepayment = monthlyrepayment + 0.005;
			monthlyrepayment = monthlyrepayment.toFixed(2);
			ballonrepayment = (balloon * amount);
			ballonrepayment = ballonrepayment.toFixed(2);
			
			monthlyrepayment = addCommas(monthlyrepayment);
			ballonrepayment = addCommas(ballonrepayment);
			
			$('.results p.repayment .monthly-amount').text('$'+monthlyrepayment);
			$('.results p.balloon .monthly-amount').text('$'+ballonrepayment);
			
			/*TRACKING*/
			if(userInteraction) {
				try{
					tracking.event.receive({EventClass:"Calculator",Action:"Submit",Type:"loanrepayments"});
				} catch(err) {}
			}
			
		} else {
			$('.results p.repayment .monthly-amount').text('$0.00');
			$('.results p.balloon .monthly-amount').text('$0.00');
		}
	}
};

function validateAmount() {
	var value = $('.calculator li.amount input[type="text"]').val();
	if(value != '') {
		if(value != '0') {
			if(value < 5000) {
				$('.calculator li.amount input[type="text"]').addClass('error');
				$('.calculator li.amount .error').show();
			} else {
				$('.calculator li.amount input[type="text"]').removeClass('error');
				$('.calculator li.amount .error').hide();
			}
		}
	}
	
	var value = $('.calculator li.deposit input[type="text"]').val();
	if(value) {
		if(value != '0') {
			var amount = $('.calculator li.amount input[type="text"]').val() - 5000;
			if(amount < value) {
				$('.calculator li.deposit input[type="text"]').addClass('error');
				$('.calculator li.deposit .error').show();
			} else {
				$('.calculator li.deposit input[type="text"]').removeClass('error');
				$('.calculator li.deposit .error').hide();
			}
		}
	}
}


calculator.activate = function(type, user) {
	
	function twopointninePrivate(amount) {
		establishfee = 265;
		balloon = 0;
		
		$('.calculator .results .balloon').hide();
		$('.calculator .results .repayment .month').text('48');
		
		//$('.calculator li.loan-type input[value="private"]').click();
		
		$('.calculator li.amount input').val(amount);
		
		$('.calculator li.interest-rate input[type="text"]').val('2.06');
		$('.calculator li.interest-rate input').attr('disabled', 'true');

		$('.calculator li.comparison-rate').show();
		$('.calculator li.comparison-rate input').val('2.9');
		$('.calculator li.comparison-rate input').attr('disabled', 'true');
		
		$('.calculator li.loan-term select option[value="48"]').attr('selected', 'true');
		$('.calculator li.loan-term select option[value="60"]').remove();
		$('.calculator li.loan-term select').attr('disabled', 'true');
		
		$('.calculator li.deposit input').val('0');
		$('.calculator li.deposit').hide();
		
		$('.calculator li.balloon .inputs #slider').slider({
			value: 0,
			min: 0,
			max: 40,
			step: 10,
			slide: function(event, ui) {
				balloon = ui.value / 100;
				if (balloon > '0') {
					$('.calculator .results .balloon').show();
					$('.repayment .month').text($('.calculator li.loan-term select').val() - 1);				
				} else {
					$('.calculator .results .balloon').hide();
					$('.repayment .month').text($('.calculator li.loan-term select').val());
				}
				userInteraction = true;
				calculator.algorithm.activate(type, user);
			}
		});

		$('.calculator li.loan-term select').change(function() {
			if (balloon > '0') {
				$('.calculator .results .balloon').show();
				$('.repayment .month').text($('.calculator li.loan-term select').val()-1);				
			} else {
				$('.calculator .results .balloon').hide();
				$('.repayment .month').text($('.calculator li.loan-term select').val());
			}
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		$('.calculator li.loan-type input[id="loan-type-business"]').click(function() {
			twopointnineBusiness($('.calculator li.amount input').val());
		});
		calculator.algorithm.activate('twopointnine', 'private');
	}
	function twopointnineBusiness(amount) {
		establishfee = 355;
		balloon = 0;
		
		$('.calculator .results .balloon').hide();
		$('.calculator .results .repayment .month').text('48');
		
		//$('.calculator li.loan-type input[id="loan-type-business"]').click();
		
		$('.calculator li.amount input').val(amount);
	
		$('.calculator li.interest-rate input[type="text"]').val('2.9');
		$('.calculator li.interest-rate input').attr('disabled', 'true');
		
		$('.calculator li.comparison-rate').hide();
		
		$('.calculator li.loan-term select option[value="60"]').remove();
		$('.calculator li.loan-term select option[value="48"]').attr('selected', 'true');
		$('.calculator li.loan-term select').removeAttr('disabled');
		
		$('.calculator li.deposit input').val('0');
		$('.calculator li.deposit').hide();
		
		$('.calculator li.balloon .inputs #slider').slider({
			value: 0,
			min: 0,
			max: 40,
			step: 10,
			slide: function(event, ui) {
				balloon = ui.value / 100;
				if (balloon > '0') {
					$('.calculator .results .balloon').show();
					$('.repayment .month').text($('.calculator li.loan-term select').val() - 1);				
				} else {
					$('.calculator .results .balloon').hide();
					$('.repayment .month').text($('.calculator li.loan-term select').val());
				}
				userInteraction = true;
				calculator.algorithm.activate(type, user);
			}
		});

		$('.calculator li.loan-term select').change(function() {
			if (balloon > '0') {
				$('.calculator .results .balloon').show();
				$('.repayment .month').text($('.calculator li.loan-term select').val()-1);				
			} else {
				$('.calculator .results .balloon').hide();
				$('.repayment .month').text($('.calculator li.loan-term select').val());
			}
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		$('.calculator li.loan-type input[id="loan-type-private"]').click(function() {
			twopointninePrivate($('.calculator li.amount input').val());
		});
		calculator.algorithm.activate('twopointnine', 'business');
	}
	
	function threepointninePrivate(amount) {
		establishfee = 265;
		balloon = 0;
		
		$('.calculator .results .balloon').hide();
		$('.calculator .results .repayment .month').text('48');
		
		//$('.calculator li.loan-type input[value="private"]').click();
		
		$('.calculator li.amount input').val(amount);
		
		$('.calculator li.interest-rate input[type="text"]').val('3.05');
		$('.calculator li.interest-rate input').attr('disabled', 'true');

		$('.calculator li.comparison-rate').show();
		$('.calculator li.comparison-rate input').val('3.9');
		$('.calculator li.comparison-rate input').attr('disabled', 'true');
		
		$('.calculator li.loan-term select option[value="48"]').attr('selected', 'true');
		$('.calculator li.loan-term select option[value="60"]').remove();
		//$('.calculator li.loan-term select').attr('disabled', 'true');
		
		$('.calculator li.deposit input').val('0');
		$('.calculator li.deposit').hide();
		
		$('.calculator li.balloon .inputs #slider').slider({
			value: 0,
			min: 0,
			max: 40,
			step: 10,
			slide: function(event, ui) {
				balloon = ui.value / 100;
				if (balloon > '0') {
					$('.calculator .results .balloon').show();
					$('.repayment .month').text($('.calculator li.loan-term select').val() - 1);				
				} else {
					$('.calculator .results .balloon').hide();
					$('.repayment .month').text($('.calculator li.loan-term select').val());
				}
				userInteraction = true;
				calculator.algorithm.activate(type, user);
			}
		});

		$('.calculator li.loan-term select').change(function() {
			if (balloon > '0') {
				$('.calculator .results .balloon').show();
				$('.repayment .month').text($('.calculator li.loan-term select').val()-1);				
			} else {
				$('.calculator .results .balloon').hide();
				$('.repayment .month').text($('.calculator li.loan-term select').val());
			}
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		$('.calculator li.loan-type input[id="loan-type-business"]').click(function() {
			threepointnineBusiness($('.calculator li.amount input').val());
		});
		calculator.algorithm.activate('threepointnine', 'private');
	}
	function threepointnineBusiness(amount) {
		establishfee = 355;
		balloon = 0;
		
		$('.calculator .results .balloon').hide();
		$('.calculator .results .repayment .month').text('48');
		
		//$('.calculator li.loan-type input[id="loan-type-business"]').click();
		
		$('.calculator li.amount input').val(amount);
	
		$('.calculator li.interest-rate input[type="text"]').val('3.9');
		$('.calculator li.interest-rate input').attr('disabled', 'true');
		
		$('.calculator li.comparison-rate').hide();
		
		$('.calculator li.loan-term select option[value="60"]').remove();
		$('.calculator li.loan-term select option[value="48"]').attr('selected', 'true');
		$('.calculator li.loan-term select').removeAttr('disabled');
		
		$('.calculator li.deposit input').val('0');
		$('.calculator li.deposit').hide();
		
		$('.calculator li.balloon .inputs #slider').slider({
			value: 0,
			min: 0,
			max: 40,
			step: 10,
			slide: function(event, ui) {
				balloon = ui.value / 100;
				if (balloon > '0') {
					$('.calculator .results .balloon').show();			
				} else {
					$('.calculator .results .balloon').hide();
				}
				$('.repayment .month').text($('.calculator li.loan-term select').val());
				userInteraction = true;
				calculator.algorithm.activate(type, user);
			}
		});

		$('.calculator li.loan-term select').change(function() {
			if (balloon > '0') {
				$('.calculator .results .balloon').show();			
			} else {
				$('.calculator .results .balloon').hide();
			}
			$('.repayment .month').text($('.calculator li.loan-term select').val());
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		$('.calculator li.loan-type input[id="loan-type-private"]').click(function() {
			threepointninePrivate($('.calculator li.amount input').val());
		});
		calculator.algorithm.activate('threepointnine', 'business');
	}
	
	function fourpointninePrivate(amount) {
		establishfee = 265;
		balloon = 0;
		
		$('.calculator .results .balloon').hide();
		$('.calculator .results .repayment .month').text('48');
		
		//$('.calculator li.loan-type input[value="private"]').click();
		
		$('.calculator li.amount input').val(amount);
		
		$('.calculator li.interest-rate input[type="text"]').val('4.04');
		$('.calculator li.interest-rate input').attr('disabled', 'true');

		$('.calculator li.comparison-rate').show();
		$('.calculator li.comparison-rate input').val('4.9');
		$('.calculator li.comparison-rate input').attr('disabled', 'true');
		
		$('.calculator li.loan-term select option[value="48"]').attr('selected', 'true');
		$('.calculator li.loan-term select option[value="60"]').remove();
		$('.calculator li.loan-term select').attr('disabled', 'true');
		
		$('.calculator li.deposit input').val('0');
		$('.calculator li.deposit').hide();
		
		$('.calculator li.balloon .inputs #slider').slider({
			value: 0,
			min: 0,
			max: 40,
			step: 10,
			slide: function(event, ui) {
				balloon = ui.value / 100;
				if (balloon > '0') {
					$('.calculator .results .balloon').show();
					$('.repayment .month').text($('.calculator li.loan-term select').val() - 1);				
				} else {
					$('.calculator .results .balloon').hide();
					$('.repayment .month').text($('.calculator li.loan-term select').val());
				}
				userInteraction = true;
				calculator.algorithm.activate(type, user);
			}
		});

		$('.calculator li.loan-term select').change(function() {
			if (balloon > '0') {
				$('.calculator .results .balloon').show();
				$('.repayment .month').text($('.calculator li.loan-term select').val()-1);				
			} else {
				$('.calculator .results .balloon').hide();
				$('.repayment .month').text($('.calculator li.loan-term select').val());
			}
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		$('.calculator li.loan-type input[id="loan-type-business"]').click(function() {
			fourpointnineBusiness($('.calculator li.amount input').val());
		});
		calculator.algorithm.activate('fourpointnine', 'private');
	}
	function fourpointnineBusiness(amount) {
		establishfee = 355;
		balloon = 0;
		
		$('.calculator .results .balloon').hide();
		$('.calculator .results .repayment .month').text('48');
		
		//$('.calculator li.loan-type input[id="loan-type-business"]').click();
		
		$('.calculator li.amount input').val(amount);
	
		$('.calculator li.interest-rate input[type="text"]').val('4.9');
		$('.calculator li.interest-rate input').attr('disabled', 'true');
		
		$('.calculator li.comparison-rate').hide();
		
		$('.calculator li.loan-term select option[value="60"]').remove();
		$('.calculator li.loan-term select option[value="48"]').attr('selected', 'true');
		$('.calculator li.loan-term select').removeAttr('disabled');
		
		$('.calculator li.deposit input').val('0');
		$('.calculator li.deposit').hide();
		
		$('.calculator li.balloon .inputs #slider').slider({
			value: 0,
			min: 0,
			max: 40,
			step: 10,
			slide: function(event, ui) {
				balloon = ui.value / 100;
				if (balloon > '0') {
					$('.calculator .results .balloon').show();			
				} else {
					$('.calculator .results .balloon').hide();
				}
				$('.repayment .month').text($('.calculator li.loan-term select').val());
				userInteraction = true;
				calculator.algorithm.activate(type, user);
			}
		});
		$('.calculator li.loan-term select').change(function() {
			if (balloon > '0') {
				$('.calculator .results .balloon').show();			
			} else {
				$('.calculator .results .balloon').hide();
			}
			$('.repayment .month').text($('.calculator li.loan-term select').val());	
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		$('.calculator li.loan-type input[id="loan-type-private"]').click(function() {
			fourpointninePrivate($('.calculator li.amount input').val());
		});
		calculator.algorithm.activate('fourpointnine', 'business');
	}
	switch(type) {
	case 'twopointnine':
		$('.calculator li.interest-rate input.interest-rate-up').hide();
		$('.calculator li.interest-rate input.interest-rate-down').hide();
		switch(user) {
		case 'private':
			$('.calculator li.loan-type input[id="loan-type-private"]').click();
			twopointninePrivate('0');
			$('.calculator li.loan-type input[id="loan-type-business"]').click(function() {
				userInteraction = true;
				user = 'business';
				twopointnineBusiness($('.calculator li.amount input').val());
			});
			break;
		case 'business':
			$('.calculator li.loan-type input[id="loan-type-business"]').click();
			twopointnineBusiness('0');
			$('.calculator li.loan-type input[id="loan-type-private"]').click(function() {
				userInteraction = true;
				user = 'private';
				twopointninePrivate($('.calculator li.amount input').val());
			});	
			break;
		}
		break;
	case 'threepointnine':
		$('.calculator li.interest-rate input.interest-rate-up').hide();
		$('.calculator li.interest-rate input.interest-rate-down').hide();
		switch(user) {
		case 'private':
			$('.calculator li.loan-type input[id="loan-type-private"]').click();
			threepointninePrivate('0');
			$('.calculator li.loan-type input[id="loan-type-business"]').click(function() {
				userInteraction = true;
				user = 'business';
				threepointnineBusiness($('.calculator li.amount input').val());
			});
			break;
		case 'business':
			$('.calculator li.loan-type input[id="loan-type-business"]').click();
			threepointnineBusiness('0');
			$('.calculator li.loan-type input[id="loan-type-private"]').click(function() {
				userInteraction = true;
				user = 'private';
				threepointninePrivate($('.calculator li.amount input').val());
			});
			break;
		}
		break;
	case 'fourpointnine':
		$('.calculator li.interest-rate input.interest-rate-up').hide();
		$('.calculator li.interest-rate input.interest-rate-down').hide();
		switch(user) {
		case 'private':
			$('.calculator li.loan-type input[id="loan-type-private"]').click();
			fourpointninePrivate('0');
			$('.calculator li.loan-type input[id="loan-type-business"]').click(function() {
				userInteraction = true;
				user = 'business';
				fourpointnineBusiness($('.calculator li.amount input').val());
			});
			break;
		case 'business':
			$('.calculator li.loan-type input[id="loan-type-business"]').click();
			fourpointnineBusiness('0');
			$('.calculator li.loan-type input[id="loan-type-private"]').click(function() {
				userInteraction = true;
				user = 'private';
				fourpointninePrivate($('.calculator li.amount input').val());
			});
			break;
		}
		break;
	case 'generic':
		establishfee = 265;
		
		$('.calculator .results .balloon').hide();
		$('.calculator .results .repayment .month').text('12');
		
		$('.calculator li.loan-type input[id="loan-type-private"]').click();
		$('.calculator li.loan-type').hide();
		
		if($('.offer-details .pricing-offer').length > 0) {
			var price = $('.offer-details .pricing-offer .price').text().replace(/[^0-9\.]/g, '');
			$('.calculator li.amount input').val(price);
		} else {
			$('.calculator li.amount input').val('0');
		}
				
		$('.calculator li.interest-rate input').val('0');
		$('.calculator li.interest-rate input.interest-rate-up').click(function() {
			var val = $('.calculator li.interest-rate input.interest-rate').val();
			val = val * 1 + 0.25;
			$('.calculator li.interest-rate input.interest-rate').val(val);	
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		$('.calculator li.interest-rate input.interest-rate-down').click(function() {
			var val = $('.calculator li.interest-rate input.interest-rate').val();
			val = val * 1 - 0.25;
			if(val >= 0) {
				$('.calculator li.interest-rate input.interest-rate').val(val);
				userInteraction = true;
				calculator.algorithm.activate(type, user);		
			}
		});
		
		$('.calculator li.loan-term select').change(function() {
			if (balloon > '0') {
				$('.calculator .results .balloon').show();
				$('.repayment .month').text($('.calculator li.loan-term select').val() - 1);				
			} else {
				$('.calculator .results .balloon').hide();
				$('.repayment .month').text($('.calculator li.loan-term select').val());
			}
			userInteraction = true;
			calculator.algorithm.activate(type, user);
		});
		
		$('.calculator li.comparison-rate').hide();
		
		$('.calculator li.deposit input').val('0');
		
		$('.calculator li.balloon').hide();

		break;
	}

	
	$('.calculator li.amount input').keyup(function() {
		var value = $('.calculator li.amount input[type="text"]').val();
		if(value != '') {
			if(value != '0') {
				if(value >= 5000) {
					$('.calculator li.amount input[type="text"]').removeClass('error');
					$('.calculator li.amount .error').hide();
				}
			}
		}
		userInteraction = true;
		calculator.algorithm.activate(type, user);
	});
	
	$('.calculator li.amount input').focus(function() {
		calculator.tracking.trackGA();
	});
	
	$('.calculator li.amount input').blur(function() {
		validateAmount();
	});
	
	$('.calculator li.interest-rate input[type="text"]').keyup(function() {
		userInteraction = true;
		calculator.algorithm.activate(type, user);
	});
	
	$('.calculator li.deposit input').keyup(function() {
		userInteraction = true;
		calculator.algorithm.activate(type, user);
		validateAmount();
	});
	$('.calculator li.deposit input').blur(function() {
		userInteraction = true;
		validateAmount();
	});
	
	calculator.algorithm.activate(type, user);		
};


$(document).ready(function() {
	//calculator.activate('twopointnine', 'private');
	//calculator.activate('twopointnine', 'business');
	//calculator.activate('generic', 'private');

	$('.finance-calculator .calculator #amount').focus(function() {
		console.log('tracking fired');
		console.log(_gaq);
		calculator.tracking.trackGA();
	});
});

offers.knownUser = {
	show: {
		details: function(options) {
	
			var referrer = $('body').attr('id');
			if(userDetailsKnown) {
				data = 'referrer='+referrer+'&postcode='+userDetailsPostcode+'&registrationType='+userDetailsRegType;
			} else {
				data = 'referrer='+referrer;
			}
			
			$.ajax({
				url: '/service/offers/details/'+options.offerId,
				data: data,
				dataType: 'html',
				error: function(XMLHttpRequest, textStatus, errorThrown) {
				},
				success: function(data, textStatus, XMLHttpRequest){
					var wt_vehicle = '';
		        	var wt_offer= '';
		        	var wt_2_9 = 0;
		        	var campaignIds = '';
		        	
					switch(options.type) {
					case 'overlay':
						$(window).scrollTop('0');
						$('#overlay.offer-details .content').html(data);
						var element = $('#overlay.offer-details .content .dealer');
						if(userDetailsKnown) {
							personalisation.display.dealerInfo.summary(element, '200x274', '13', {valid: false});
						} else {
							personalisation.display.form(element, {valid: false});
						}
			        	wt_vehicle = $($('#overlay').find('h3')[0]).text();
						wt_offer = wt_vehicle + ' ' + $('#overlay').find('h4').text();
						campaignIds = $('#overlay.offer-details .offer-details').attr('rel');
						break;
					case 'page':
						$(options.element).html(data);
						var element = $('.offer-details .dealer');
						if(userDetailsKnown) {
							personalisation.display.dealerInfo.summary(element, '200x274', '13', {valid: false});
						} else {
							personalisation.display.form(element, {valid: false});
						}
						wt_vehicle = $($('.offer-details').find('h3')[0]).text();
						wt_offer = wt_vehicle + ' ' + $('.offer-details').find('h4').text();
						campaignIds = $('.offer-details').attr('rel');
						break;
					}
									
					var pageURL = window.location.hostname;
					var shareURL = $('.addthis_toolbox a').attr('addthis:url');
					$('.addthis_toolbox a').attr('addthis:url', 'http://'+pageURL+shareURL);
		            if (window.addthis) {
		               window.addthis.ost = 0;
		               window.addthis.ready();
		            }
		            
					campaignIds = campaignIds.split(':');
					if(campaignIds[1] == '15es57193') {//twopointnine ID
						var user = 'private';
						if(userDetailsRegType) {
							user = userDetailsRegType.toLowerCase();
						}							
						$('.offer-details .finance-calculator').addClass('finance-promo');
						$('.offer-details .module-regular-offers').remove();
						$('.offer-details .module-threepointnine-offers').remove();
						calculator.activate('twopointnine', user);
						wt_2_9 = 1;
					} else if(campaignIds[1] == '15n4o0t0q') {//threepointnine ID
						var user = 'private';
						if(userDetailsRegType) {
							user = userDetailsRegType.toLowerCase();
						}			
						$('.offer-details .finance-calculator .module-enquire-finance-offer a').html('ENQUIRE ABOUT THE TOYOTA FINANCE <br> ADVANTAGE OFFER');
						$('.offer-details .finance-calculator .module-enquire-finance-offer a').attr('href', 'https://www.toyota.com.au/toyota-finance-advantage-enquiry');
						$('.offer-details .finance-calculator .module-enquire-finance-offer a').click(function() {
							 window.open('https://www.toyota.com.au/toyota-finance-advantage-enquiry?WT.ac=SpecialOfferDetailsTFAENQForm&VehicleConversionID=SpecialOffers&SpecOffer=1','popup','width=970,height=765,scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no');
							 return false; 
						});
						$('.offer-details .finance-calculator').addClass('finance-promo');
						$('.offer-details .module-twopointnine-offers').remove();
						$('.offer-details .module-regular-offers').remove();
						calculator.activate('threepointnine', user);
						wt_2_9 = 2;
					} else if(campaignIds[1] == '15n4o2aj8') {//fourpointnine ID
						var user = 'private';
						if(userDetailsRegType) {
							user = userDetailsRegType.toLowerCase();
						}			
						$('.offer-details .finance-calculator .module-enquire-finance-offer a').html('ENQUIRE ABOUT THE TOYOTA FINANCE <br> ADVANTAGE OFFER');
						$('.offer-details .finance-calculator .module-enquire-finance-offer a').attr('href', 'https://www.toyota.com.au/toyota-finance-advantage-enquiry');
						$('.offer-details .finance-calculator .module-enquire-finance-offer a').click(function() {
							 window.open('https://www.toyota.com.au/toyota-finance-advantage-enquiry?WT.ac=TFAHybridCamrySpecialOfferTFALandingPageTFAENQForm&VehicleConversionID=Hybrid+Camry&SpecOffer=1','popup','width=970,height=765,scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no');
							 return false; 
						});
						$('.offer-details .finance-calculator').addClass('finance-promo');
						$('.offer-details .module-twopointnine-offers').remove();
						$('.offer-details .module-threepointnine-offers').remove();
						calculator.activate('fourpointnine', user);
						wt_2_9 = 2;
					} else {
						var user = 'private';
						$('.offer-details .finance-calculator').addClass('finance-no-promo');
						$('.offer-details .module-twopointnine-offers').remove();
						$('.offer-details .module-threepointnine-offers').remove();
						calculator.activate('generic', user);
					}
					
		            /*TRACKING*/
		        	try {

			        	window["vehicle"] = wt_vehicle;
			        	
			        	$('#page-link a').each(function(i,n) {
			        		tracking.webtrends.link.morelink(n);
			        	});
			        	$('a.more-link').each(function(i,n) {
			        		tracking.webtrends.link.morelink(n);
			        	});
			        	$('.col-2 .module .media a').each(function(i,n) {
			        		tracking.webtrends.link.morelink(n);
			        	});
			        	$('.col-2 .module h2 a').each(function(i,n) {
			        		tracking.webtrends.link.morelink(n);
			        	});
			        	
						$('.offer-details .finance-calculator .module-enquire-finance-offer a').attr('href', '#');
						
						switch(options.section) {
							case 'special-offers':
								tracking.event.activate('trackingevent', {EventClass: "SpecialOffer", Action: "View", Vehicle: wt_vehicle, OfferID: options.offerId, OfferName: wt_offer, PostCode: userDetailsPostcode, Source:"Special Offer", Region: userDetailsDealerPostcode, IsTFO: wt_2_9, ClickType: options.viewed});
								break;
							case 'vehicles':
								tracking.event.activate('trackingevent', {EventClass:"SpecialOffer", Action:"View", Vehicle: wt_vehicle, OfferID: options.offerId, OfferName: wt_offer, PostCode: userDetailsPostcode, Source:"Vehicle Hub", Region: userDetailsDealerPostcode, IsTFO: wt_2_9, ClickType: options.viewed});
								break;
							case 'special-offers-twopointnine':
								tracking.event.activate('trackingevent', {EventClass: "SpecialOffer", Action: "View", Vehicle: wt_vehicle, OfferID: options.offerId, OfferName: wt_offer, PostCode: userDetailsPostcode, Source: "Toyota Finance Offer", Region: userDetailsDealerPostcode, IsTFO: wt_2_9, ClickType: options.viewed});
								break;
							case 'finance-advantage':
								tracking.event.activate('trackingevent', {EventClass: "SpecialOffer", Action: "View", Vehicle: wt_vehicle, OfferID: options.offerId, OfferName: wt_offer, PostCode: userDetailsPostcode, Source: "Toyota Finance Offer", Region: userDetailsDealerPostcode, IsTFO: wt_2_9, ClickType: options.viewed});
								break;	
						}
					} catch (err) {}
				}
			});
			
		},
		campaignList: function(filterIds) {
			var data = '';
			$.ajax({	
				url: '/service/offers/listbycampaign/'+filterIds,
				data: data,
				dataType: 'html',
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					module.noOffers.activate();
				},
				success: function(data, textStatus, XMLHttpRequest){
					$('.offer-group-summary-list').empty();
					$('.offer-group-summary-list').html(data);
					if($('.offer-group-summary-list .offer-group-nooffers').length > 0) {
						$('.offer-group-summary-list').empty();
						module.noOffers.activate();
					} else {
						$('.offer-summary').each(function(i,n) {
							$(n).click(function() {
								var sSection = $('body').attr('id');
								var sOfferId = $(n).attr('id').split('-')[1];
								createOverlay({customClass: 'offer-details'});
								showOverlay(deleteOverlay, offers.knownUser.show.details, {offerId: sOfferId, type: 'overlay', element: '', section: sSection, viewed: 'SpecOfferTile'});
								return false;
							});
						});
					}
				}
			});
		},
		summaryList: function(type, filterType, filterId) {
			var data = '';
			switch(type) {
				case 'special-offers':
					data = 'postcode='+userDetailsPostcode+'&suburb='+userDetailsSuburb+'&registrationType='+userDetailsRegType
					if (filterType) data += '&filterTypes='+filterType;
					if (filterId) data += '&filterIds='+filterId;
					break;
				case 'campaign': 
					data = 'filterTypes=CAMPAIGN&filterIds='+campaignId;
					if (filterType) data += '&filterTypes='+filterType;
					if (filterId) data += '&filterIds='+filterId;
					break;
				case 'finance-offer': 
					data = 'filterTypes=CAMPAIGN&filterIds=15n4o0t0q&filterTypes=CAMPAIGN&filterIds=15n4o2aj8';
					break;
			}
			$.ajax({	
				url: '/service/offers/list',
				data: data,
				dataType: 'html',
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					module.noOffers.activate();
				},
				success: function(data, textStatus, XMLHttpRequest){
					$('.offer-group-summary-list').empty();
					$('.offer-group-summary-list').html(data);
					if($('.offer-group-summary-list .offer-group-nooffers').length > 0) {
						$('.offer-group-summary-list').empty();
						module.noOffers.activate();
					} else {
						$('.offer-summary').each(function(i,n) {
							$(n).click(function() {
								var sSection = $('body').attr('id');
								var sOfferId = $(n).attr('id').split('-')[1];
								createOverlay({customClass: 'offer-details'});
								showOverlay(deleteOverlay, offers.knownUser.show.details, {offerId: sOfferId, type: 'overlay', element: '', section: sSection, viewed: 'SpecOfferTile'});
								return false;
							});
						});
					}
				}
			});
		},
		promoTile: function(type) {
			if($('#special-offer.module').length > 0) {
				var sOfferInfo = $('#special-offer.module').attr('rel');
				var sVehicleGroupId = sOfferInfo.split('-')[1];
				var sVehicleAnchorId = sOfferInfo.split('-')[2];
				var sWidth = sOfferInfo.split('-')[3];
				$.ajax({ 
					url: '/service/offers/promo',
					data: 'postcode='+userDetailsPostcode+'&suburb='+userDetailsSuburb+'&registrationType='+userDetailsRegType+'&vehicleGroupId='+sVehicleGroupId+'&vehicleAnchorId='+sVehicleAnchorId+'&imageWidth='+sWidth,
					error: function(XMLHttpRequest, textStatus, errorThrown) {},
					success: function(data, textStatus, XMLHttpRequest){
						$('#special-offer').empty();
						$('#special-offer').append(data);
						if ($('#special-offer .offer-promo').attr('id') != null) {
							if($('body').hasClass('homepage')){
								$('#special-offer').removeClass('module-why-buy-a-toyota');
								
							}else{
								$('#special-offer').removeClass('special-offer-message');
							}
							$('#special-offer').click(function(){
								var sSection = $('body').attr('id');
								var sOfferId = $('#special-offer .offer-promo').attr('id').split('-')[1];
								createOverlay({
									customClass: 'offer-details'
								});
								showOverlay(deleteOverlay, offers.knownUser.show.details, {
									offerId: sOfferId,
									type: 'overlay',
									element: '',
									section: sSection,
									viewed: 'SpecOfferTile'
								});
								return false;
							});
						} else {
							if($('body').hasClass('homepage')){
								$('#special-offer').addClass('module-why-buy-a-toyota').html('<h2>WHY BUY <span>A TOYOTA?</span></h2><div class="info"><div class="media"><a href="/toyota/promise"><img width="215" height="95" alt="Why buy a Toyota" src="/static/images/169ob-toyota-module-why-buy-215x95.jpg"></a></div><div class="content"><p>We are committed to delivering Quality, Safety and Innovation in everything we do; while at the same time finding ways to improve.<br />This is not a motto. It&prime;s simply the way we do things. We have a word for it: "Kaizen". It&prime;s the Toyota promise.</p></div><a class="more-link" href="/toyota/promise">Find out more about the Toyota Promise</a></div>');							
							}else{
								$('#special-offer').addClass('special-offer-message');
							}							
						}
					}
				});
			}
		},
		promoTileJson: function(type) {
			if($('#special-offer.module').length > 0) {
				var sOfferInfo = $('#special-offer.module').attr('rel');
				var sVehicleGroupId = sOfferInfo.split('-')[1];
				var sVehicleAnchorId = sOfferInfo.split('-')[2];
				var sWidth = sOfferInfo.split('-')[3];
				$.ajax({ 
					url: '/service/offers/promo.json',
					data: 'postcode='+userDetailsPostcode+'&suburb='+userDetailsSuburb+'&registrationType='+userDetailsRegType+'&vehicleGroupId='+sVehicleGroupId+'&vehicleAnchorId='+sVehicleAnchorId+'&imageWidth='+sWidth,
					error: function(XMLHttpRequest, textStatus, errorThrown) {},
					success: function(data, textStatus, XMLHttpRequest){
						//var offer = '<div class="offer-promo" id="offer-1287276434677"><h2>Special offer</h2><div class="image"><img width="'+sWidth+'" alt="Retail-yaris-yr-hatch-auto-428-1F8-silver-lining" src="/static/images/yaris_yr_5dr_front_3_4_silver_lining_v02-300x169.png"></div><div class="content"><h3>Yaris YR 5 door hatch</h3><div class="nonpricing"><h4>2.9% Comparison rate^~</h4><p>Toyota Finance Advantage</p></div><div class="normal">It\'s hard to look beyond the stylish looks of the Yaris Hatch, but it offers plenty for such a small package.</div></div><a class="more-link" href="/special-offers/offer?offerId=1287276434677">See offer details</a></div>';
						$('#special-offer').empty();
						$('#special-offer').append(data);
						$('#special-offer').click(function() {
							var sSection = $('body').attr('id');
							var sOfferId = $('#special-offer .offer-promo').attr('id').split('-')[1];
							createOverlay({customClass: 'offer-details'});
							showOverlay(deleteOverlay, offers.knownUser.show.details, {offerId: sOfferId, type: 'overlay', element: '', section: sSection, viewed: 'SpecOfferTile'});
							return false;
						});
					}
				});
			}
		},
		disclaimers: function(type) {
			if($('.offer-group-disclaimers').length > 0) {
				var data = '';
				switch(type) {
					case 'special-offers': 
						break;
					case 'campaign': 
						data = 'campaignId='+campaignId;
						break;
				}
				$.ajax({
					url: '/service/offers/disclaimers',
					data: data,
					dataType: 'html',
					error: function(XMLHttpRequest, textStatus, errorThrown) {
					},
					success: function(data, textStatus, XMLHttpRequest){
						$('.offer-group-disclaimers').empty();
						$('.offer-group-disclaimers').html(data);
					}
				});
			}
		},
		filters: function(type) {
			if($('.offer-group-carousel-filters').length > 0) {
				var data = '';
				switch(type) {
					case 'special-offers': 
						data = 'postcode='+userDetailsPostcode+'&suburb='+userDetailsSuburb+'&registrationType='+userDetailsRegType;
						break;
					case 'campaign': 
						data = 'campaignId='+campaignId;
						break;
					case 'campaign-special':
						data = 'campaignId='+campaignId;
						break;
				}
				$.ajax({
					url: '/service/offers/filters',
					data: data,
					dataType: 'html',
					error: function(XMLHttpRequest, textStatus, errorThrown) {
					},
					success: function(data, textStatus, XMLHttpRequest){
						$('.offer-group-carousel-filters').empty();
						$('.offer-group-carousel-filters').html(data);
						switch(type) {
							case 'special-offers': 
								break;
							case 'campaign':
								//$('#main .show-all-activate .link-b a').click();
								break;
							case 'campaign-special':
								$('#main .offer-grouping-list .offer-group#filter-'+VEHICLE_ID+'-VEHICLE_GROUP').click();
								break;
						}
						var hashParam = location.hash;
						hashParam = hashParam.replace('#', '');
						$('.offer-group-carousel-filters .offer-group').each(function(i,n) {

							if(hashParam) {
								var heading = $(n).find('h2').text();
								heading = heading.replace(/\s/g, '-');
								heading = heading.toLowerCase();	
								if(heading == hashParam) {
									$(n).click();
								}	 
							}
							
						});
					}
				});
			}
		},
		carouselFilters: function(type) {
			if($('.offer-group-carousel-filters').length > 0) {
				var data = '';
				switch(type) {
					case 'special-offers': 
						data = 'postcode='+userDetailsPostcode+'&suburb='+userDetailsSuburb+'&registrationType='+userDetailsRegType;
						break;
					case 'campaign': 
						data = 'campaignId='+campaignId;
						break;
					case 'campaign-special':
						break;
				}
				$.ajax({
					url: '/service/offers/carousel-filters',
					data: data,
					dataType: 'html',
					error: function(XMLHttpRequest, textStatus, errorThrown) {
					},
					success: function(data, textStatus, XMLHttpRequest){
						$('.offer-group-carousel-filters').empty();
						$('.offer-group-carousel-filters').html(data);
						if($('.offer-group-carousel-filters .offer-group-nooffers').length > 0) {
							$('.offer-group-carousel-filters .offer-group-nooffers').html('<p>There are no offers for your postcode/suburb at this moment in time.</p>').show();
							//$('.offer-group-carousel-filters').empty();
							//module.noOffers.activate();
						} else {
							/*if(!campaignId) {
								$('.offer-group-carousel-filters .offer-carousel .column-count-1 .col-1').empty().append('<div id="offer-carousel"></div>');
								var flashvars = {
								  configUrl: '/service/offers/getOfferCarouselData.xml '
		                        };
		                        var params = {
		                          salign: 't',
		                          wmode: 'opaque',
		                          swLiveConnect: 'true',
		                          menu: 'false',
		                          scaleMode: 'noScale',
		                          AllowScriptAccess: 'always'
		                        };
		                        swfobject.embedSWF('/static/flash/specialOffersCarousel/SpecialOffersCarousel.swf', 'offer-carousel', '750', '350', '9.0.0', '', flashvars, params);
							}*/
						}
						var hashParam = location.hash;
						hashParam = hashParam.replace('#', ''); 
						$('.offer-group-carousel-filters .offer-group').each(function(i,n) {
							if(hashParam) {
								var heading = $(n).find('h2').text();
								heading = heading.replace(/\s/g, '-');
								heading = heading.toLowerCase();	
								if(heading == hashParam) {
									$(n).click();
								}	 
							}
						});
					}
				});
			}
		},
		banner: function(type) {
			if($('.offer-group-banner').length > 0) {
				var data = '';
				switch(type) {
					case 'special-offers': 
						data = 'postcode='+userDetailsPostcode+'&suburb='+userDetailsSuburb;
						break;
					case 'campaign':  
						data = 'campaignId='+campaignId;
						break;
				}
				$.ajax({
					url: '/service/offers/banner',
					data: data,
					dataType: 'html',
					error: function(XMLHttpRequest, textStatus, errorThrown) {
					},
					success: function(data, textStatus, XMLHttpRequest){
						$('.offer-group-banner').empty();
						$('.offer-group-banner').html(data);
						$('.offer-group-banner embed').height('300px');
					}
				});
			}
		}
	},
	remove: {
		summaryList: function() {
			$('.offer-group-summary-list').empty();
		}
	}
};

offers.anonUser = {
	show: {
		banner: function(campaignId) {
			var data = '';
			switch(type) {
				case 'special-offers': 
					break;
				case 'campaign': 
					data = 'campaignId='+campaignId;
					break;
			}
			$.ajax({
				url: '/service/offers/banner',
				data: data,
				dataType: 'html',
				error: function(XMLHttpRequest, textStatus, errorThrown) {
				},
				success: function(data, textStatus, XMLHttpRequest){
					$('.offer-group-banner').empty();
					$('.offer-group-banner').html(data);
				}
			});
		},
		promoTile : function() {
			
		}
	}
};

offers.activate = function() {
	if($('body#special-offers').length > 0) {
		if(campaignId) {
			switch(campaignId) {
				case '15es57193':
					$('body').attr('id', 'special-offers-twopointnine');
					if($('body').hasClass('special-offers')) {
						var sFilterType = 'CAMPAIGN';
						var sFilterId = '15es57193';
						if(VEHICLE_ID) {
			        		offers.knownUser.show.banner('campaign');
			        		offers.knownUser.show.filters('campaign-special');
			        		offers.knownUser.show.disclaimers('campaign');
						} else {
			        		offers.knownUser.show.banner('campaign');
			        		offers.knownUser.show.filters('campaign');
			        		offers.knownUser.show.disclaimers('campaign');
						}
						
						$('.module-dealer-enquiry a').each(function(i,n) {
							var oCurrentLink = $(this);
							var sCurrentDELink = oCurrentLink.attr('href');
							oCurrentLink.attr('href', sCurrentDELink+'&formType=retail_dealer_enquiry');
					        		
			        	});
						$('.module-book-a-test-drive a').each(function(i,n) {
							var oCurrentLink = $(this);
							var sCurrentBATDLink = oCurrentLink.attr('href');
							oCurrentLink.attr('href', sCurrentBATDLink+'&formType=retail_batd');
					        		
			        	});	
					} else {
						if($('body').hasClass('special-offers-offer')) {
							var sElement = $('.offer-group-offer-detail');
			        		var sOfferId = $('#offerId').attr('class').split('-')[1];
							var sSection = $('body').attr('id');
							
							offers.knownUser.show.banner('campaign');
			        		offers.knownUser.show.details({offerId: sOfferId, type: 'page', element: sElement, section: sSection, viewed: 'Embedded'});
						}
					}
					break;
				default:
					break;
			}
		} else {
			
			if($('body').hasClass('special-offers')) {
				if(userDetailsKnown != null) {
	        		offers.knownUser.show.banner('special-offers');
	        		offers.knownUser.show.carouselFilters('special-offers');
	        		offers.knownUser.show.disclaimers('special-offers');
	        		offers.knownUser.remove.summaryList();
					
					/* Special offers survey form */
					//survey.specialOffers();
				}
				else if($('body').hasClass('landing-page')) {
					// Do not redirect
				}
				else {
					window.location = '/special-offers/entry';
				}
				
				if($('body').hasClass('landing-page')) {
					// Sets up offer link so that the popup appears
					$('.offer-summary').each(function(i,n) {
						$(n).click(function() {
							var sSection = $('body').attr('id');
							var sOfferId = $(n).attr('id').split('-')[1];
							hh_WT.trackEvent({'WT.ac':'RT_LandingPage_'+$(this).find('h3').html()+'_ViewOfferDetail'}, true);
							createOverlay({customClass: 'offer-details'});
							showOverlay(deleteOverlay, offers.knownUser.show.details, {offerId: sOfferId, type: 'overlay', element: '', section: sSection, viewed: 'SpecOfferTile'});
							return false;
						});
					});
					
					// Sets up the finance advantage link (taken from /static/finance/generic/js/finance-campaign.js)
					$('.offer-link a').attr('href', '#');
					$('.offer-link a').click(function() {
						 window.open('https://www.toyota.com.au/toyota-finance-advantage-enquiry?WT.ac=RT_LandingPage_Aurion_TFAOffer&ModuleName=TFA+ENQ+FORM&ModuleLoc=/finance/toyota-finance-advantage&ModuleCTA=TFA+ENQ+FORM&ModuleState=&ModuleInteract=1','popup','width=970,height=765,scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no');
						 return false; 
					});
				}
				
				$('.module-dealer-enquiry a').each(function(i,n) {
					var oCurrentLink = $(this);
					var sCurrentDELink = oCurrentLink.attr('href');
					oCurrentLink.attr('href', sCurrentDELink+'&formType=retail_dealer_enquiry');
			        		
	        	});
				$('.module-book-a-test-drive a').each(function(i,n) {
					var oCurrentLink = $(this);
					var sCurrentBATDLink = oCurrentLink.attr('href');
					oCurrentLink.attr('href', sCurrentBATDLink+'&formType=retail_batd');
			        		
	        	});
			} else if($('body').hasClass('special-offers-entry')) {
				if(userDetailsKnown != null) {
					function get_url_parameter(param){
						param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
						var r1 = "[\\?&]"+param+"=([^&#]*)";
						var r2 = new RegExp( r1 );
						var r3 = r2.exec( window.location.href );
						if( r3 == null ) { 
							return "";
						} else {
							return r3[1];
						}
					}
					var destination = get_url_parameter('destination');
					if(destination) {
						destination = destination.split(';');
						window.location = '/special-offers/offer?offerId='+destination[1];
					} else {
						window.location = '/special-offers';
					}
				} else {
					module.offersEntry.anonUser();
				}	
			} else if($('body').hasClass('special-offers-offer')) {
				function get_url_parameter(param){
					param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
					var r1 = "[\\?&]"+param+"=([^&#]*)";
					var r2 = new RegExp( r1 );
					var r3 = r2.exec( window.location.href );
					if( r3 == null ) { 
						return "";
					} else {
						return r3[1]; 
					}
				}
				var sElement = $('.offer-group-offer-detail');
				var sOfferId = get_url_parameter('offerId');
				if(!sOfferId) {
					var sOfferId = get_url_parameter('offerid');
				}
				if(userDetailsKnown != null) {
					var sSection = $('body').attr('id');					
	        		offers.knownUser.show.banner('special-offer');
	        		offers.knownUser.show.details({offerId: sOfferId, type: 'page', element: sElement, section: sSection, viewed: 'Embedded'});
				} else {
					window.location = '/special-offers/entry?destination=offerId;'+sOfferId;
				}
			}
		}
		
		/*TRACKING - WT.AC TAGGING*/
		/*FOOTER TRACKING*/
		var footerEbroHref = $('#footer .module-ebrochure a.more-link').attr('href');
		var footerDEHref = $('#footer .module-dealer-enquiry a.more-link').attr('href');
		var footerBATDHref = $('#footer .module-book-a-test-drive a.more-link').attr('href');
		$('#footer .module-ebrochure a.more-link').attr('href', footerEbroHref + '&WT.ac=SpecialoffersFooterIconebro');
		$('#footer .module-dealer-enquiry a.more-link').attr('href', footerDEHref + '&WT.ac=SpecialoffersFooterIconDE');
		$('#footer .module-book-a-test-drive a.more-link').attr('href', footerBATDHref + '&WT.ac=SpecialoffersFooterIconBATD');
				
	} else if ($('body#vehicles').length > 0) {
		if ($('body').hasClass('special-offers')) {
			if(userDetailsKnown != null) {
				setTimeout(function() { 
	        		offers.knownUser.show.banner('special-offers');
					offers.knownUser.show.summaryList('special-offers', 'VEHICLE_GROUP', VEHICLE_ID);
	        		offers.knownUser.show.disclaimers('special-offers');
				}, 250);
			} else {
				var url = window.location;
				url = url.pathname + '/entry';
				window.location = url;
			}
		} else if ($('body').hasClass('special-offers-entry')) {
			if(userDetailsKnown != null) {
				var url = window.location;
				url = url.pathname.replace('/entry', '');
				window.location = url;
			} else {
				module.offersEntry.anonUser();
			}
		} else if ($('body').hasClass('homepage')) {
			var element = $('#special-offer.module');
			if($(element).length > 0) {
				var sVehicleInfo = $(element).attr('rel');
				var sVehicleGroupId = sVehicleInfo.split('-')[1];
				var OFFERS_VEHICLE_NAME = '';
				var oPageBody = $('body');
				if (oPageBody.attr('id') == 'vehicles') {
					if(oPageBody.hasClass('camry')){OFFERS_VEHICLE_NAME = 'camry';}
					else if(oPageBody.hasClass('corolla')){OFFERS_VEHICLE_NAME = 'corolla';}
					else if(oPageBody.hasClass('tarago')){OFFERS_VEHICLE_NAME = 'tarago';}
					else if(oPageBody.hasClass('coaster')){OFFERS_VEHICLE_NAME = 'coaster';}
					else if(oPageBody.hasClass('hiace')){OFFERS_VEHICLE_NAME = 'hiace';}
					else if(oPageBody.hasClass('hilux')){OFFERS_VEHICLE_NAME = 'hilux';}
					else if(oPageBody.hasClass('landcruiser-70-series')){OFFERS_VEHICLE_NAME = 'lc70';}
					else if(oPageBody.hasClass('kluger')){OFFERS_VEHICLE_NAME = 'kluger';}
					else if(oPageBody.hasClass('prado')){OFFERS_VEHICLE_NAME = 'prado';}
					else if(oPageBody.hasClass('rav4')){OFFERS_VEHICLE_NAME = 'rav4';}
					else if(oPageBody.hasClass('rukus')){OFFERS_VEHICLE_NAME = 'rukus';}
					else if(oPageBody.hasClass('prius')){OFFERS_VEHICLE_NAME = 'prius';}
					else if(oPageBody.hasClass('yaris')){OFFERS_VEHICLE_NAME = 'yaris';}
					else if(oPageBody.hasClass('aurion')){OFFERS_VEHICLE_NAME = 'aurion';}
					else if(oPageBody.hasClass('landcruiser-200')){OFFERS_VEHICLE_NAME = 'lc200';}
					else if(oPageBody.hasClass('camry-hybrid-camry')){OFFERS_VEHICLE_NAME = 'hybridcamry';}
					else if(oPageBody.hasClass('corolla-sedan')){OFFERS_VEHICLE_NAME = 'corolla';}
					else if(oPageBody.hasClass('fj-cruiser')){OFFERS_VEHICLE_NAME = 'fjcruiser';}
				}	
				$.ajax({
					url: '/service/offers/hasoffers/'+sVehicleGroupId,
					success: function(response) {
						if(response == 'true') {
							if(userDetailsKnown != null) {
								offers.knownUser.show.promoTile('homepage');
							} else {
								$(element).empty();
								$(element).append('<h2 class="highlighted">Special Offers</h2>');
								$(element).append('<p>Special Offers are available, please enter your postcode to view offers</p>');
								personalisation.display.form(element, {valid: false});
							}
						} else {
							$(element).empty().addClass('module-large');
							$(element).append('<a href="/special-offers?WT.ac=VH_'+OFFERS_VEHICLE_NAME+'Homepage_SpecialOffers"><img width="300" height="424" alt="Toyota Lifetime Advantage" src="/static/images/15vjr-toyota-lifetime-advantages-300x424.jpg"</h2>'); 
						}
					}
				});
			}
			
		} else if ($('body').hasClass('features') || $('body').hasClass('prices')) {
			var element = $('#special-offer.module');
			if($(element).length > 0) {
				var sVehicleInfo = $(element).attr('rel');
				var sVehicleGroupId = sVehicleInfo.split('-')[1];
				$.ajax({
					url: '/service/offers/hasoffers/'+sVehicleGroupId,
					success: function(response) {
						if(response == 'true') {
							if(userDetailsKnown != null) {
								offers.knownUser.show.promoTile('homepage');
							} else {
								$(element).empty();
								$(element).append('<h2 class="highlighted">Special Offers</h2>'); 
								$(element).append('<p>Special Offers are available, please enter your postcode to view offers</p>');
								personalisation.display.form(element, {valid: false});
							}
						} else {
							$(element).remove();
						}
					}
				});
			}
		}
	}
}

function flashOfferPopup(sOfferId) {
	var sSection = $('body').attr('id');
	createOverlay({customClass: 'offer-details'});
	showOverlay(deleteOverlay, offers.knownUser.show.details, {offerId: sOfferId, type: 'overlay', element: '', section: sSection, viewed: 'FlashBanner'});
}



$(document).ready(function() {

	$('#main .offer-grouping-list .offer-group').hover(
		function() {
			$(this).addClass('hover');
		}, 
		function() {
			$(this).removeClass('hover');
		}
	);
	
	$('#main .offer-grouping-list .offer-group').live('click', function() {
		if($(this).hasClass('active')) {
			$(this).removeClass('active');
			offers.knownUser.remove.summaryList();
		} else {
			$('#main .offer-grouping-list .offer-group').removeClass('active');
			$('#main .show-all-activate .link-b a').addClass('show').text('See all offers');
			$(this).addClass('active');
			if(campaignId) {
				var type = 'campaign';
			} else {
				var type = 'special-offers';
			}
			var oOfferFilter = $(this).attr('id');
			var sFilterType = oOfferFilter.split('-')[2];
			var sFilterId = oOfferFilter.split('-')[1];
			offers.knownUser.show.summaryList(type, sFilterType, sFilterId);
			if(!campaignId) {
				var offset = $('.offer-grouping-list').offset();
				$(window).scrollTop(offset.top - 20);
			}
			var vehicle = $(this).find('h2').text();
			tracking.event.activate('trackingevent', {EventClass:"SpecialOffers", Action:"ButtonClick", Vehicle:vehicle, State: 'VehicleOffer'});
		}
	});
	
	$('#main .offer-grouping-list .show-all-activate .link-b a').live('click', function() {
		if($(this).hasClass('show')) {
			$(this).removeClass('show');
			$('#main .offer-grouping-list .offer-group').removeClass('active');
			$(this).text('Hide all offers');
			if(campaignId) {
				var type = 'campaign';
				var sFilterType = 'CAMPAIGN';
				var sFilterId = campaignId;
			} else {
				var type = 'special-offers';
				var sFilterType = '';
				var sFilterId = '';
			}
			offers.knownUser.show.summaryList(type, sFilterType, sFilterId);
			if(!campaignId) {
				var offset = $('.offer-grouping-list').offset();
				$(window).scrollTop(offset.top - 20);
			}
			tracking.event.activate('trackingevent', {EventClass:"SpecialOffers", Action:"ButtonClick", State: 'SeeAllOffers'});
		} else {
			$(this).addClass('show');
			$(this).text('See all offers');
			offers.knownUser.remove.summaryList();
			tracking.event.activate('trackingevent', {EventClass:"SpecialOffers", Action:"ButtonClick", State: 'HideAllOffers'});
		}
		return false;
	});
	
});
/*
$(document).ready(function() {
	if ($('body').hasClass('special-offers-entry')) {
		if ($('.userDetailSearch').hasClass('entry-mvt')) {
			if(MVTTrackingStartFlag == false){
				try{
					wt.MVTImpression(MVTTestSection,MVTTestCase);
				} catch(err) {};
				MVTTrackingStartFlag = true;
			}	
		}
	}
});*/
