//
// jquery.buildprice.js
// Copyright (c) Land Rover. All rights reserved.
//
// $Id: jquery.buildprice.js 737 2011-05-24 09:03:27Z adam $
//

// The number of milliseconds before checking if the user has scrolled the viewport.
var scrollCheckInterval = 1000;

var __jsonp_original_url='';

// The default settings for an overlay in build and price.
// This variable is initialized in the main jQuery function below.
var overlaySettings = {};

jQuery(function($) {
	// trackPage
	// A hash is set on the trim level, engine, wheelbase and defender model links to prevent
	// analytics from tracking the model step each time the user selects an option. The model
	// page is only tracked the first time the user accesses the page.
	var trackPage = (document.location.hash != '#__skiptrack');

	document.location.hash="__build_and_price_top";

	if (typeof bpConfig == 'undefined' || bpConfig == null) {
		return;
	}

	// Analytics tracking
	if (trackPage) {
		var url = /\/$/.test(window.location.pathname) ? window.location.pathname : window.location.pathname + '/';
		var view = getCurrentView(unescape(window.location.search));
		if (typeof(bpConfig.text.vehicle.trimlevels.selected) != 'undefined') {
			url = url + bpConfig.text.vehicle.trimlevels.selected.name.replace(' ', '-').toLowerCase() + '/';
		}
		trackurl(url + view);
	}

	$('div#bp-model-select-block dl dd.mainimage a,div#bp-wheelbase-select-block ul li a,div#bp-defendermodel-select-block ul li a,div#bp-engine-select-block ul li a').each(function() {
		var currentView = getCurrentView(unescape(window.location.search));
		var nextView = getCurrentView(unescape(getParameterByName($(this).attr('href'), 'configUrl')));
		if (currentView == nextView) {
			$(this).attr('href', $(this).attr('href') + '#__skiptrack');
		}
	});

	$('div#wrapper div#content div#primary-content div#primary-content-body div#build-price-double-col div#col2 div#options-block div.content div#verttabs ul li div.share-friends a').click(function(e) {
		trackurl(url + 'share');
	});

	// Handle SBE Links
	$("a[rel='sbe']").click(function(e){
		sbe(this.href);
		e.preventDefault();
	});

	// Initialize the default settings for an overlay
	var overlayContent
		= '<div id="photo" style="width: 864px; height: 570px">'
		+ '<div id="main-content" style="padding:0;width:850px;height:425px;"></div>'
		+ '<div id="text">'
		+ '<div class="options-price-block">'
		+ '<h3><strong></strong> <span></span></h3>';

	if (bpConfig.showPrices) {
		overlayContent += '<span class="price"><span></span></span>'
		+ '<ul class="disclaimers"></ul>'
		+ '</div>'
	}

	overlayContent += '</div></div>';

	overlaySettings = {
		closeButton:
			'<div class="close-nav"><a class="nyroModalClose" id="overlay-close-nav" title="'
			+ bpConfig.text.overlay.close
			+ '">'
			+ bpConfig.text.overlay.close
			+ '</a></div>',
		content: overlayContent,
		height: 570,
		width: 864,
		wrap: {
			ajax: '<div id="nyroModalContentWrapper"></div>',
			manual: '<div id="nyroModalContentWrapper" class="exterior360"></div>'
		},
		windowResize: false
	};

	if ($('div#build-price-double-col div#col1').length) {
		$('div#build-price-double-col div#col1').css("top", 0);
		setTimeout('adjustNavigationColumnPosition();', scrollCheckInterval);
	}

	if (bpConfig.view == 'interior') {
		$('div.options-cta-block ul', summaryColumn).prepend(
			'<li class="search first">'
				+ '<a href="#">' + bpConfig.text.interior.view + '</a>'
				+ '<p>' + bpConfig.text.interior.intro + '</p>'
			+ '</li>'
		);

		$('div.options-cta-block ul li.search a', summaryColumn).click(function(e) {
			e.preventDefault();

			overlaySettings.endFillContent = function(elts, settings) {
				$('div#main-content').append('<img src="' + bpConfig.interior + '" alt="' + $('div#master-image-block img').attr('alt') + '" width="850" height="425"/>');
				updateOverlayPriceBlock(elts.content, bpConfig.text);
			};
			$.nyroModalManual(overlaySettings);

			return false;
		});
	}

	// Send to Dealer
	$('input#__send_to_dealer_form_submit').click(function(e) {
		e.preventDefault();

		$.nyroModalManual({
			content: "<iframe src='about:blank' name='__send_to_dealer_target' width='1000' height='500'/>",
			closeButton: overlaySettings.closeButton,
			wrap: overlaySettings.wrap,
			windowResize: overlaySettings.windowResize,
			width:1000,
			height:520,
			endShowContent: function(elts, settings) {
				$("form#__send_to_dealer_form").submit();
			}
		});

		return false;
	});

	// Initalise 3D models
	if (typeof bpConfig.exterior360s != 'undefined') {
		var summaryColumn = $('div#build-price-double-col div#col1 div#col-fixed');
		if (summaryColumn.length) {
			swfobject.embedSWF(
				bpConfig.exterior360s.selected.small.swf,
				'master-image-block',
				bpConfig.exterior360s.selected.small.width,
				bpConfig.exterior360s.selected.small.height,
				"9.0.0",
				false,
				bpConfig.exterior360s.selected.small.params.flashvars,
				bpConfig.exterior360s.selected.small.params,
				{ id: bpConfig.exterior360s.selected.small.id }
			);

			$('div.options-cta-block ul', summaryColumn).prepend(
				'<li class="rotate first">'
					+ '<a href="#">' + bpConfig.text.exterior360s.view + '</a>'
					+ '<p>' + bpConfig.text.exterior360s.intro + '</p>'
				+ '</li>'
			);
			$('div.options-cta-block ul li.rotate a', summaryColumn).click(function(e) {
				e.preventDefault();

				overlaySettings.endFillContent = function(elts, settings) {
					swfobject.embedSWF(
						bpConfig.exterior360s.selected.large.swf,
						'main-content',
						bpConfig.exterior360s.selected.large.width,
						bpConfig.exterior360s.selected.large.height,
						"9.0.0",
						false,
						bpConfig.exterior360s.selected.large.params.flashvars,
						bpConfig.exterior360s.selected.large.params,
						{ id: bpConfig.exterior360s.selected.large.id }
					);
					updateOverlayPriceBlock(elts.content, bpConfig.text);
				};
				$.nyroModalManual(overlaySettings);

				return false;
			});
		}
	}

	addAjax('div#primary-content-body a:not([target="_blank"])[href^="?configUrl"]');

	// Initialise tabs
	initialiseTabs();

	//
	// tooltips
	// The following code is for handling tooltips.
	//

	$('div#wrapper div#content div#primary-content div#primary-content-body div#bp-model-select-block dl').each(function() {
		var model = $(this);

		$('dd.tooltip', $(this)).each(function() {
			var tooltip = $('<div class="tooltip buildprice-tooltip-block" style="display:none"><div class="content"></div>');
			tooltip.insertAfter($('dd.mainimage a', model));

			$(this).children('span.buildprice-content-internal').appendTo($('div.content', tooltip));
			$(this).remove();
		});

		var api = $('dd.mainimage a', model).tooltip({
			position: 'top left',
			api: true,
			onBeforeShow: function(event, position) {
				var tip = this.getTip();
				$('body').append(tip);

				var offset = $('dd.mainimage a img', model).offset().top + (position.top > $('dd.mainimage a img', model).offset().top) ? $('dd.mainimage a img', model).offset().top - position.top : position.top - $('dd.mainimage a img', model).offset().top;
				if (offset != 0) {
					this.getConf().offset[0] = offset;
				}

				if (position.left < $('div#wrapper').position().left) {
					this.getConf().position = 'top right';
					tip.addClass('left-bp-tip');
				}
				this.getConf().offset[1] = (this.getConf().position == 'top right') ? parseInt($('dd.link', model).css('padding-left')) * -1 : parseInt($('dd.link', model).css('padding-left'));

				return true;
			}
		});
		$('dd.link a', $(this)).hover(function() { api.show(); }, function() { api.hide(); });

		if(typeof bpConfig.text.exterior360s.Use3D == 'undefined' || bpConfig.text.exterior360s.Use3D=='true') {
			var image = $(this).children('dd.mainimage');
			var link = $('<span class="threesixty">' + bpConfig.text.exterior360s.modelPopup + '</span>');
			link.click(function(e) {
				e.preventDefault();

				var configuratorUrl = unescape($('a', image).attr('href').replace('?configUrl=', ''));
				var jsonUrl
					= bpConfig.jsonpBaseUrl
					+ configuratorUrl.substring(0, configuratorUrl.indexOf('&'))
					+ '&view=exterior&t=sjson&norc&jsoncallback=?';
					
				overlaySettings.endFillContent = function(elts, settings) {
					$.getJSON(jsonUrl, null, function(data) {
						var hasNotable = (typeof data.rulesConnect != 'undefined' && typeof data.rulesConnect.conflictResolution != 'undefined');
						if (hasNotable) {
							configuratorUrl = unescape(data.rulesConnect.conflictResolution.acceptUrl).replace('?configUrl=', '');
							jsonUrl
								= bpConfig.jsonpBaseUrl
								+ configuratorUrl.substring(0, configuratorUrl.indexOf('&'))
								+ '&view=exterior&t=sjson&norc&jsoncallback=?';

							$.getJSON(jsonUrl, null, function(data) {
								fillExterior360Overlay(elts, data);
							});

						} else {
							fillExterior360Overlay(elts, data);
						}
					});
				};
				$.nyroModalManual(overlaySettings);
					
				return false;
			});
			$('div.buildprice-tooltip-block span.buildprice-content-internal', image).append(link);
		}
	});

	$('div#wrapper div#content div#primary-content div#primary-content-body div#bp-model-select-block div.scroll-holder-block p').each(function() {
		$('a', $(this)).tooltip({ relative: true, offset: [-12,0] });
		$('span.tooltip', $(this)).each(function() {
			var text = $(this).text();
			$(this).hide().addClass('tooltip-block bottom-tip').empty().prepend($('<span class="content">' + text + '</span>'));
		});
	});

	$('div#wrapper div#content div#primary-content div#primary-content-body div#build-price-double-col div#col2 div.options-list-block table tbody tr th.total, div#wrapper div#content div#primary-content div#primary-content-body div#disclaimer-holder, div#wrapper div#content div#primary-content div#primary-content-body div#build-price-double-col div#col1 div#col-fixed div.options-price-block').each(function() {
		var ul = $('<ul class="disclaimers"></ul>');

		$('div.tooltip', $(this)).each(function() {
			var li = $('<li><span class="tooltip-trigger">' + $('span.content-internal span.header', $(this)).text() + '</span></li>');
			var className = 'tooltip-block ' + /*((isInSidebar) ? 'sidebar-disclaimer-tooltip-block' :*/ 'disclaimer-tooltip-block'/*)*/;
			$(this).hide().insertAfter($('span.tooltip-trigger', li)).addClass(className).prepend($('<div class="content"></div>')).children('span.content-internal').appendTo($('div.content', $(this)));
			ul.append(li);
			
			if (this.id == 'pricing-disclaimer') {
				overlaySettings.content = overlaySettings.content.replace('<ul class="disclaimers"></ul>', '<ul class="disclaimers"><li>' + li.html() + '</li></ul>' );
			}
		});

		$(this).append(ul);
		$('li span.tooltip-trigger', ul).each(function() {
			var trigger = $(this);
			trigger.tooltip({
				position: 'bottom right',
				relative: false,
				onBeforeShow: function(event, position) {
					var tip = this.getTip();
					$('body').append(tip);
					this.getConf().offset = [-15,15];
					return true;
				}
			});
		});
	});
});


//
// Initialise Tabs
//
function initialiseTabs() {
	$('div#verttabs ul li div.item a.more.connect-overlay').click(function(e) {
		e.preventDefault();

		var overlay = bpConfig.overlays[$(this).attr('id')];
		if (overlay != 'undefined' && overlay != null) {
			var content = $(overlayTemplates.connect);

			$('img', content).attr('src', overlay.image);
			$('img', content).attr('alt', overlay.title);
			$('div#text h2 strong', content).text(overlay.title);

			if (overlay.partNumber != '') {
				$('div#text p.part-number', content).text(overlay.partNumber);
			} else {
				$('div#text p.part-number', content).remove();
			}
			
			if (overlay.text != '') {
				$('div#text p:not(.part-number)', content).html(overlay.text);
			} else {
				$('div#text p:not(.part-number)', content).remove();
			}

			$.nyroModalManual({
				content: content,
				closeButton: overlaySettings.closeButton,
				wrap: overlaySettings.wrap,
				windowResize: overlaySettings.windowResize
			});
		}

		return false;
	});

	$('div#verttabs ul li div.item a.more.morello-overlay').nyroModal({
		closeButton: overlaySettings.closeButton,
		wrap: overlaySettings.wrap,
		windowResize: overlaySettings.windowResize,
		endShowContent: function(elts, settings) {
			initializeFlowplayer($('div#main-content', elts.content));
		},
		hideContent: function(elts, settings, callback) {
			unloadFlowplayer($('div#main-content', elts.content));
			callback();
		}
	});

	$('div#verttabs ul li div.item a.more:not(.connect-overlay,.morello-overlay)').toggle(
		function() {
			$('div.expanded-info', $(this).parent().parent()).slideDown();
			$(this).parent().parent().parent().addClass('expanded');
			$(this).text(bpConfig.text.list.hide);
		},
		function() {
			$('div.expanded-info', $(this).parent().parent()).slideUp();
			$(this).parent().parent().parent().removeClass('expanded');
			$(this).text(bpConfig.text.list.findOutMore);
		}
	);

	// JIRA LRO-669
	// Clear all view cookies when on the first step (Autobiography for RR, Model for LR)
	var isFirstView = $('div#step-links-block ul li:first.first-selected').length == 1;
	if (isFirstView) {
		var views = ['exterior', 'interior', 'options', 'accessories', 'summary'];
		for (var index = 0; index < views.length; index++) { $.cookie(views[index], null, { path: '/' }); }
	}

	var selectedTab = $.cookie(bpConfig.view);
	$("#verttabs").tabs('option', 'cookie', { name: bpConfig.view, expires: null, path: '/' });
	if (selectedTab !== null) {
		$("#verttabs").tabs('option', 'selected', parseInt(selectedTab));
	}
	
	$('div#step-links-block ul li a').click(function(e) {
		$.cookie(bpConfig.view, null, { expires: null, path: '/' });
	});

	$('div.options-list-block ul li').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);

	$('div#verttabs > div > div.options-list-block ul > li > div > div.item a.title, div#verttabs > div > div.options-list-block ul > li > div > dl > dt > a').click(function(e) {
		trackSelectedOption($(this));
	});

	$('div#verttabs > div > div.options-list-block ul > li > div > a').click(function(e) {
		trackSelectedOption($('dl > dt > a', $(this).parent('div')));
	});
}


//
// Add AJAX functionality to the specified elements.
//
function addAjax(selector) {
	var nodes = $(selector);
	nodes.click(function(e) {
		var href = $(this).attr('href');
		var url = unescape(getParameterByName(href, 'configUrl'));

		var isNavigation = $(this).parents('#step-links-block').length>0 || $(this).parents('div.options-navigation-block-long').length>0 || $(this).parents('div.options-navigation-block').length>0;
		var isResetNotable = (url.indexOf('resetview') > 0);
		if(!isNavigation || isResetNotable) {
			rcJSON(bpConfig.jsonpBaseUrl + url.replace('t=shtml', 't=sjson'), href);
			return false;
		}
		return true;
	});
}

// rcJSON
// A JSON request which is cache friendly
// jurl: JSONP Url to call
// url: Original non AJAX URL
function rcJSON(jurl, url) {
	if(jurl.indexOf('?')) {
		jurl = jurl + '&jsoncallback=rcajax';
	}
	__jsonp_original_url=url;
	$.ajax({url: jurl, dataType: "script",type: "GET", cache: true, callback: null, data:null });
}
//
// Executed once a JSON call has returned.
//
function rcajax(data) {
	var url = __jsonp_original_url;
	var isResetNotable = (url.indexOf('resetview') > 0);

	if(!isResetNotable) {
		updateFlash(data.exterior360s);
		
		if(data.view!='interior' && data.rulesConnect!=null && typeof data.rulesConnect.exteriorImageUrl != 'undefined') {
			updateMasterImage(data.rulesConnect.exteriorImageUrl);
		} else {
			updateMasterImage(data.interiorSml);
		}
	}
	
	var followClickThru = true;
	if (bpConfig.view != 'model') {
		bpConfig = data;
		if (typeof data.rulesConnect != 'undefined' || isResetNotable) {
			followClickThru = (typeof data.rulesConnect.conflictResolution != 'undefined' || isResetNotable) ? handleConflict(data, url, isResetNotable) : handleFeatures(data);
		}
	}
	
	if(followClickThru) {
		// Fall back to non-AJAX.
		document.location.href = (typeof data.rulesConnect.conflictResolution != 'undefined') ? data.rulesConnect.conflictResolution.acceptUrl : url;
	} else {
		bpConfig = data;
	}
}

//
// getParameterByName(url, name)
// Gets the value of a query string parameter with the specified name from the specified URL.
// PARAMS
//	url: The URL.
//	name: The name of the query string parameter whose value is to be returned.
// RETURNS
// A value for the query string parameter with the specified name, otherwise an empty string if 
// no parameter with the specified name exists.
//
function getParameterByName(url, name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var pattern = "[\\?&]" + name + "=([^&#]*)";
	var results = new RegExp(pattern).exec(url);
	return (results != null) ? results[1] : '';
}

//
// handleConflict(data)
// Handles a conflict and displays a notable.
//
function handleConflict(data,url,isResetNotable) {
	var followClickThru = false;
	var con = data.rulesConnect.conflictResolution;

	var closeButtonHtml
		= '<div class="close-nav"><a class="nyroModalClose" id="overlay-close-nav" title="'
		+ data.text.overlay.close
		+ '">'
		+ data.text.overlay.close
		+ '</a></div>';
		
	var wrapperHtml = '<div id="nyroModalContentWrapper"';
	if (!isResetNotable) {
		wrapperHtml += ' class="notable"';
	}
	wrapperHtml += '></div>';

	var innerHtml = '<div id="options-accessories-overlay" class="content-overlay-block">'+
				 '<h2>'+con.heading+'</h2>'+
				 '<p>'+con.intro+'</p>';
				 
	if(typeof con.removal != 'undefined') {
		innerHtml += '<div class="col1">'+
					 '<h3>' + con.removal.heading + '</h3>'+
					 '<div class="item-holder">';
		var nFeatures = con.removal.features.length;
		for(var i=0; i<nFeatures; i++) {
			innerHtml+='<dl';
			if(i%2==0) {
				innerHtml+=' class="alt">';
			} else {
				innerHtml+='>';
			}
			innerHtml+='<dt>';
			if(typeof con.removal.features[i].price != 'undefined') {
				innerHtml+='<span class="price">' + con.removal.features[i].price + '</span>';
			}
			innerHtml+='<strong>'+ con.removal.features[i].description+'</strong></dt></dl>';
		}
		innerHtml+='</div></div>';
	}

	if(typeof con.addition != 'undefined') {
		innerHtml += '<div class="col2">'+
					 '<h3>' + con.addition.heading + '</h3>'+
					 '<div class="item-holder">';
		var nFeatures = con.addition.features.length;
		for(var i=0; i<nFeatures; i++) {
			innerHtml+='<dl';
			if(i%2==0) {
				innerHtml+=' class="alt">';
			} else {
				innerHtml+='>';
			}
			innerHtml+='<dt>';
			if(typeof con.addition.features[i].price != 'undefined') {
				innerHtml+='<span class="price">' + con.addition.features[i].price + '</span>';
			}
			innerHtml+='<strong>'+ con.addition.features[i].description+'</strong></dt></dl>';
		}
		innerHtml+='</div></div>';
	}
	
	innerHtml+='<ul class="buttons"><li><a href="' + con.acceptUrl+ '">'+
				 '<img src="'+bpConfig.text.notables.acceptButtonImg+'" height="27" width="151" alt="' + con.acceptText + '"/>'+
				 '</a></li><li><a href="' + con.rejectUrl + '">'+
				 '<img src="'+bpConfig.text.notables.cancelButtonImg+'" height="27" width="151" alt="' + con.rejectText + '"/>'+
				 '</a></li></ul></div>';

	var notableOverlaySettings = {
		closeButton: closeButtonHtml,
		content: innerHtml,
		wrap: {
			manual: wrapperHtml
		},
		zIndexStart: 200,
		endFillContent: function(elts, settings) {
			elts.content.find('ul.buttons li:eq(1) a').click(function(e) {
				e.preventDefault();
				$.nyroModalRemove();
				return false;
			});

			if (window.refreshCufon) {
				refreshCufon();
			}
		}
	};
	
	if (!isResetNotable) {
		notableOverlaySettings.minHeight = 365;
	}
	
	$.nyroModalManual(notableOverlaySettings);

	return followClickThru;
}

//
// handleFeatures(data)
// Handles rules feature data.
//
function handleFeatures(data) {

	var rc = data.rulesConnect;

	if (rc.featurelists.length == 0) {
		return true;
	}

	// Replace navigation tabs.
	if(typeof rc.navigation!='undefined') {
//		$('#step-links-block ul').empty().append(rc.navigation.replace('t%3Dsjson','t%3Dshtml'));//.remove();//.after(rc.navigation.replace('t%3Dsjson','t%3Dshtml')).remove();
		for(var k in rc.navigation) {
			$('#'+rc.navigation[k].id+' a').attr('href',rc.navigation[k].href);
			
			if(rc.navigation[k].id == 'summary') {
				// Update view summary call to action
				$('#col-fixed .options-useful-links-block a[href*="?configUrl"]').attr('href',rc.navigation[k].href);
			}
		}
	}
	


//	addAjax('#step-links-block a[href*="?configUrl"]');
	
	if(typeof rc.nextStep!='undefined') {
		//.no, .text, .url (URL needs to be fixed in XSLT)
		renderLinkToView(rc.nextStep.no, rc.nextStep.text, rc.nextStep.url, 'next');
	}
	if(typeof rc.prevStep!='undefined') {
		//.no, .text, .url (URL needs to be fixed in XSLT)	
		renderLinkToView(rc.prevStep.no, rc.prevStep.text, rc.prevStep.url, 'previous');
	}
	if(typeof rc.totalPrice!='undefined') {
		$('#col1 #col-fixed div.options-price-block span.price span').html(rc.totalPrice);
		//TODO: Price change animation.
	}
	if(typeof rc.header!='undefined') {
		$('#options-block div.header h2').text(rc.header);
		if (window.refreshCufon) {
			refreshCufon();
		}
	}
	if(typeof rc.footer!='undefined') {
		$('#options-block div.footer').remove();
		if(rc.footer!='') {
			$('#options-block').append('<div class="footer"><p>'+ rc.footer +'</p></div>');
		}
	}
	if(typeof rc.featurelists!='undefined') {
		// [{clazz:text, img:url, title:text, 
		//	 features:[
		//						 { id: 'f_xxx', selected:'true'/undefined, 
		//							 href: '...', price: 'xxx',
		//							 designersChoice: {clazz: 'xxx',text:'xxx'}/undefined,
		//							 actionText: 'xxx'/undefined
		// 
		//html:"<...html...>"}
		//						]}, ...
		// ]
		for(var i in rc.featurelists) {
			for(var j in rc.featurelists[i].features) {
				var fid = rc.featurelists[i].features[j].id;
				
				// li
				var li = $('#'+fid);
				
				// selected
				if(rc.featurelists[i].features[j].selected == 'true') {
					li.attr("class", "selected");
				} else {
					li.attr("class", "");
				}
				
				// href
				var links = $('a',li).not('.more');
				links.attr('href',rc.featurelists[i].features[j].href);
				
				// title (actionText)
				if(typeof rc.featurelists[i].features[j].actionText != 'undefined') {
					links.attr('title',rc.featurelists[i].features[j].actionText);
				}
				
				// price
				$('span.price',li).text(rc.featurelists[i].features[j].price);
				
				// designers choice
				if(typeof rc.featurelists[i].features[j].designersChoice != 'undefined') {
					var dc=$('dd.designerschoice',li);
					var clazz = 'designerschoice';
					if(rc.featurelists[i].features[j].designersChoice.clazz != '') {
						clazz=clazz+' '+ rc.featurelists[i].features[j].designersChoice.clazz;
					}
					dc.attr('class',clazz);
					dc.text(rc.featurelists[i].features[j].designersChoice.text);
				}
				
			}
		}
	}
	
	return false;
}

//
// Render the prev/next button as specified by type.
// Params:
// no: Step Number
// text: Text to display in button
// url: URL to link to
// type: 'previous' or 'next'
function renderLinkToView(no, text, url,type) {
	var html = '<a href="'+url+'"><span class="step-number">'+no+'</span>'+
						 '<span class="step-text">'+text+'</span></a>';
	var div = $('#col-fixed div.'+type).empty().append(html);
	// TODO: Re-add ajax to these elements, once they support AJAX.
}

//
// updateFlash(config)
// Updates the small Flash exterior 360 to reflect the user's choices.
// PARAMS
//	config: The Flash exterior 360 configuration data.
//
function updateFlash(config) {
	if (typeof config == 'undefined' || config == null) {
		return;
	}
	
	var movie = document.getElementById(config.selected.small.id);
	if (movie != undefined && movie != null) {
		var layers = new Array();

		for(var name in config.selected.small.params.flashvars) {
			if(name.match("^layer") == 'layer') {
				var layerNo = parseInt(name.substring(5));
				var url = config.selected.small.params.flashvars[name];
				var layer = [layerNo, url];
				layers.push(layer);
			}
		}
		movie.setAllLayers(layers);
	}
}

//
// updateMasterImage(config)
// Updates the small interior image or exterior image to reflect the user's choice.
// PARAMS
//	config: The interior configuration data.
//
function updateMasterImage(config) {
	if (typeof config == 'undefined' || config == null) {
		return;
	}
	$('div#build-price-double-col div#col1 div#col-fixed div#master-image-block img').attr('src', config);
}


//
// fillExterior360Overlay(overlay, data)
// Fills the exterior 360 overlay with the correct 360 model and vehicle name and price.
// PARAMS:
//	overlay: The overlay which will contain the 360.
//	data: The data for the overlay.
//
function fillExterior360Overlay(overlay, data) {
	swfobject.embedSWF(
		data.exterior360s.selected.large.swf,
		'main-content',
		data.exterior360s.selected.large.width,
		data.exterior360s.selected.large.height,
		"9.0.0",
		false,
		data.exterior360s.selected.large.params.flashvars,
		data.exterior360s.selected.large.params,
		{ id: data.exterior360s.selected.large.id }
	);
	updateOverlayPriceBlock(overlay.content, data.text);
}

//
// updateOverlayPriceBlock(config)
// Updates the overlay price block.
// PARAMS
//	overlay: An overlay containing a price block.
//	config: The price block configuration data.
//
function updateOverlayPriceBlock(overlay, config) {
	if (typeof config == 'undefined' || config == null) {
		return;
	}

	$('li span.tooltip-trigger', overlay).tooltip({
		position: 'top center',
		relative: true,
		onBeforeShow: function(event, position) {
			var tip = this.getTip();
			tip.addClass('bottom-tip');
		}
	});

	$('h3 strong', overlay).html(config.vehicle.nameplate);
	$('h3 span', overlay).html(config.vehicle.trimlevels.selected.name);
	$('span.price span', overlay).html(config.vehicle.trimlevels.selected.price);

	if (window.refreshCufon) {
		refreshCufon();
	}
}

//
// adjustNavigationColumnPosition()
// Adjusts the position of the navigation column in a list view when a user scrolls the viewport.
//
function adjustNavigationColumnPosition() {
	var parent = $('div#build-price-double-col');
	var column = $('div#col1', parent);

	var scrollTop = $(window).scrollTop();
	var offset = scrollTop - parent.position().top;

	var columnHeight = offset + column.height();

	var change = 0;
	if (columnHeight > parent.height()) {
		change = parent.height() - column.height();
	} else if (offset > 0) {
		change = offset;
	}

	column.animate({ top: change }, 600, function() {
		setTimeout('adjustNavigationColumnPosition();', scrollCheckInterval); 
	});
}
//
// getCurrentView(configUrl)
// Gets the current Build and Price view
// PARAMS
//	configUrl: The URL for the current configuration.
// RETURNS
//	The name of the current Build and Price view
//
function getCurrentView(configUrl) {
	var match = /view=(\w+)&/.exec(configUrl);
	if (match != null && match.length == 2) {
		return match[1];
	}
	return 'model';
}
//
// trackSelectedOption(category, option)
// Registers an option selected by the user as an analytics event
// PARAMS
//	option: The selected option.
//
function trackSelectedOption(option) {
	var nameplate = bpConfig.text.vehicle.nameplate;
	var trim = bpConfig.text.vehicle.trimlevels.selected.name;
	var event = 'Build and Price - ' + nameplate + ' - ' + trim;
	var category = $('h3', $(option).closest('div.options-list-block')).text();
	addEvent(event, category, $(option).text());
}
