Cufon.replace(
    '#footer ul li a, .reserve h1, .standard h1, .reserve_three_simple h1, .savings_calc h1',  
    { fontFamily: 'Avenier Light', hover: 'true', separate: 'words' });

Cufon.replace(
    '#main_nav ul li a, a.box_link, span.box_link, ul#main_nav li ul li a, ul#gallery_nav li a, #windmill p a, #step_three form h3, dl dt, ul#tertiary_nav li a, div.gray_box h3, #main h3', 
    { fontFamily: 'Avenier Medium', hover: 'true', separate: 'words' });
    
Cufon.replace(
    '.box h2, div#form_cars form div label span, a.btn', 
    { fontFamily: 'Avenier Heavy', separate: 'words', hover: 'true' });

Cufon.replace(
    'ul#color_swatches li a, ul#color_swatches li.note, .reserve p.intro, #main h4',
    { fontFamily: 'Avenier Book', separate: 'words', hover: 'true' });

Cufon.replace(
    '#step_three form div.form_row label, #step_three label p, #car_to_reserve p, div#IGS_PAYMENTTYPE-row div span, #coda_savings div label', 
    { fontFamily: 'Avenier Book', separate: 'words' });	

Cufon.replace(
    '.savings_calc p.savings_head',
    { fontFamily: 'Avenir Black', separet: 'words' });

jQuery(function() {

	/*
	* For extensive form
	*/
	$('#IGS_PAYMENTTYPE_0').click(function() {
		$('#IGS_TYPE-row, #IGS_CC-row, #IGS_EXPIRE-row, #IGS_CVV-row, #IGS_ADDRESS-row, #IGS_CITY-row, #IGS_STATE-row, #IGS_ZIP-row, #payment-method').attr('style', 'display: block;');
		$('#check-wire, #check-wire-two').attr('style', 'display: none;');
		$('form.wt').removeClass('wt').addClass('cc');
	});
	
	$('#IGS_PAYMENTTYPE_1').click(function() {
		$('#IGS_TYPE-row, #IGS_CC-row, #IGS_EXPIRE-row, #IGS_CVV-row, #IGS_ADDRESS-row, #IGS_CITY-row, #IGS_STATE-row, #IGS_ZIP-row, #payment-method').attr('style', 'display: none;');
		$('#check-wire, #check-wire-two').attr('style', 'display: block;');
		$('form.cc').removeClass('cc').addClass('wt');
	})

	/*
	* This binds the hallway animation to the car image galleries for coda > gallery > exteriors
	* Each time you click an image, the main gallery image is swapped by finding the clicked
	* image path, appending _big, and swapping the paths
	*/
	$('div#car_gallery').hallway();
	var bigimg = $('div#main div#gallery img');
	$('div#car_gallery ul li').click(function(e) {
		e.preventDefault();
		e.stopPropagation();
		
		//Remove selected class and set it to newly clicked
		$('div#car_gallery ul li').removeClass('selected');
		$(this).addClass('selected');
		
		//Get newly clicked anchor href b/c it holds the large image link
		//Set it to the gallery holder.
		var full = $('a', this).attr('href');
		bigimg.attr('src', full);
		
		var full = $('a', this).attr('rel');
		if (full != '') {
			$('a.btn_gallery_download').show().attr('href', full);
		} else {
			$('a.btn_gallery_download').hide();
		}
		
		
		return false;
	});

	
	$('#gallery_nav ul li a').click(function() {$('#gallery_nav ul li:first a').addClass('white');});


	/*
	*The following code is for the reserver step two page.
	*These following methods control the selected form state
	*and allow the different elements to animate.
	*Flag to determine whether anything has been clicked
	*/
		var flag = 0;
		var t = '';
		$('#form_cars form input').click(function(e) {
			var _this = $(this);
			//First click, show submit button
			if (flag == 0) {
				t = setTimeout(function() {
					_this.parent().siblings('div#submit').show(); 
					flag = 1;
				}, 200);
			}
		
			//Move submit button and lightening background depending on which car is clicked
			var whichcar = $(this).attr('id');
			switch(whichcar) {
				case 'white':
					$('div#submit').animate({'left': '0px'}, 100);
					$('div#car_lightening').css({'left': '-49px', 'background-position': 'left 0px'}).fadeIn('fast');
					break;
				case 'black':
					$('div#submit').animate({'left': '250px'}, 100);
					$('div#car_lightening').css({'left': '168px', 'background-position': 'left -79px'}).fadeIn('fast');
					break;
				case 'blue':
					$('div#submit').animate({'left': '500px'}, 100);
					$('div#car_lightening').css({'left': '412px', 'background-position': 'left -159px'}).fadeIn('fast');
					break;
				case 'silver':
					$('div#submit').animate({'left': '750px'}, 100);
					$('div#car_lightening').css({'left': '654px', 'background-position': 'left -235px'}).fadeIn('fast');
					break;
				default:
					break;
			}

		});
		
		/*
		* On submit of step two in the reserve form flow
		* We want to set the color of the clicked element
		* to a cookie. This way we have a reference on 
		* step three.
		*/
		$('#form_cars form').submit(function() { return false; });
		$('div#form_cars form div#submit a.btn').click(function(e) {
			var color = $('#form_cars form input:checked').attr('id');
			if (color) {
				var date = new Date();
				date.setTime(date.getTime()+(10*24*60*60*1000));
				document.cookie = 'carColor='+color+'; expires='+date.toGMTString()+'; path=/';
				return true;
			}
			return false;
		});
		
		
		/*
		* Quick script for setting the background positioning
		* of each list element in the EV ordered list -- 17 x 17
		*/
		var incx = -204;
		var incy = 0;
		$('ol#ev_facts li').each(function() {
			$(this).attr('style', 'background-position: '+incx+'px '+incy+'px;');
			//ev_fact_counter++;
			//ev_bg_pos = ev_bg_pos - 80;
			incx = incx + (17*2);
			incy = incy - (17 * 2);
		});
		
		

		/*
		* This is to flip through the different homepage facts
		* and the blogs
		*/
		var factprev = $('a#fact_left'), factnext = $('a#fact_right'), faqprev = $('a#faq_left'), faqnext = $('a#faq_right');
		$('#fact_slider div, #faq_slider div').attr('style', 'display: none;');
		$('#fact_slider div:first, #faq_slider div:first').attr('style', 'display: block');

		factnext.click(function() {
			$('#fact_slider div:first').attr('style', 'display: none').remove().appendTo('div#fact_slider');
			$('#fact_slider div:first').attr('style', 'display: block');
			return false;
		});
		factprev.click(function() {
			$('#fact_slider div:first').attr('style', 'display: none');
			$('#fact_slider div:last').remove().prependTo('div#fact_slider').attr('style', 'display: block');
			return false;
		});
		
		faqnext.click(function() {
			$('#faq_slider div:first').attr('style', 'display: none').remove().appendTo('div#faq_slider');
			$('#faq_slider div:first').attr('style', 'display: block');
			return false;
		});
		faqprev.click(function() {
			$('#faq_slider div:first').attr('style', 'display: none');
			$('#faq_slider div:last').remove().prependTo('div#faq_slider').attr('style', 'display: block');
			return false;
		});
		
		/*
		* Remove default actions on the color buttons
		*/
		$('ul#color_swatches li a').click(function() {
			return false;
		})
		
		/* 
    * Before loading step three, check for cookie car color
    * and set html car display and text. else return error
    */
   // var carcolor = readCookie('carColor');
//    switch (carcolor) {
//		case 'black':
//			$('div#car_to_reserve').addClass('black').attr('style', '_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="fixed", src="/assets/templates/coda/i/ie6_car_black.png"); _background: none;');
//			$('#step_three.simple div#car_to_reserve').css('background-position', '0 -375px');	
//			$('div#car_to_reserve p span').text('Onyx');
//			break;
//		case 'blue':
//			$('div#car_to_reserve').addClass('blue').attr('style', '_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="fixed", src="/assets/templates/coda/i/ie6_car_blue.png"); _background: none;');
//			$('#step_three.simple div#car_to_reserve').css('background-position', '0 -178px');
//			$('div#car_to_reserve p span').text('Sapphire');
//			break;
//		case 'silver':
//			$('div#car_to_reserve').addClass('silver').attr('style', '_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="fixed", src="/assets/templates/coda/i/ie6_car_gray.png"); _background: none;');
//			$('#step_three.simple div#car_to_reserve').css('background-position', '0 -4px');
//			$('div#car_to_reserve p span').text('Platinum');
//			break;
//		case 'white':
//		default:
//			$('div#car_to_reserve').addClass('white').attr('style', '_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="fixed", src="/assets/templates/coda/i/ie6_car_white.png"); _background: none;');
//			$('#step_three.simple div#car_to_reserve').css('background-position', '0 -562px');
//			$('div#car_to_reserve p span').text('Pearl');
//	}




}); /* End of document.ready */

var jsReady = false;
function isReady() { return jsReady; }
function pageInit() {
	jsReady = true;
	document.forms["form1"].output.value += "\n" + "JavaScript is ready.\n";
}

function getFlashMovie(movieID) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieID] : document[movieID]; 
}

function callToActionScript(str) { 
	var movie = getFlashMovie("swfBase").sendToActionScript(str); 
}
function general_JS_call( str ){ me.onChange( prompt(str) ); }

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2008 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }
  document.write(str);
}
function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    
    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

/* Flash swapper */
function swapper(html, selector) {
	selector = selector || '#text_swap';
	$(selector).html(html);
	Cufon.replace(selector+' h3');
}

(function(scope, name) {

	var $ = window[scope];
	//Create class
	var c = function(wrapper, options) {
		if(this.__construct) {
			this.__construct(wrapper, options || {});
		}
	};

	c.prototype = (function() {
		var p = c.prototype;
		
		// Private Properties
		var _this = null;
		
		//Construct
		p.__construct = function(wrapper, options) {
			this.wrapper = $(wrapper); //Get my wrapper as a jquery object
			options = this.getDefaultOptions(options); //Run options function
			_this = this; //Set this to scope this
			this.left 			= this.wrapper.find(options.leftHandle);
			this.right		= this.wrapper.find(options.rightHandle);
			this.items		= this.wrapper.find(options.items);
			this.frame 		= this.wrapper.find(options.frame);
			this.strip		= this.wrapper.find(options.strip);
			
			this.range		= options.range;
			this.start		= options.start;
			
			this.disableClass = options.disableClass;
			
			this.outerWidths	= [];
			this.isAnimating	= false;
			this.stripWidth = 5000;
			
			var interval = setInterval(function() {
				var arraylength = _this.items.length;
				for (var i = 0; i < arraylength+1; i++) {
					if (_this.items.eq(i).outerWidth(true) != 0 && _this.items.eq(i).outerWidth(true) != null) {
						_this.outerWidths.push(_this.items.eq(i).outerWidth(true));
						_this.stripWidth = _this.stripWidth + _this.items.eq(i).outerWidth(true);
					}
				}
				//Set strip width to combined width of elements
				_this.strip.attr('style', 'width: '+_this.stripWidth+'px;');
				clearInterval(interval);
			}, 300);

			var t = setTimeout(function() {
				clearInterval(interval);
			}, 3000);
			
			//Set event listeners
			this.left.click(_eventScrollLeft);
			this.right.click(_eventScrollRight);
			this.items.click(options.itemClickAction);
			this.items.hover(options.itemHoverOverAction, options.itemHoverOutAction);
		}
		
		//Public methods
		
		p.getDefaultOptions = function(options) {
			options								= options || {};
			options.range 						= options.range || 5;
			options.start 						= options.start || 0;
			options.frame						= options.frame || '#car_gallery';
			options.strip						= options.strip || 'ul';
			options.items						= options.items || 'ul li a img';
			options.leftHandle				= options.leftHandle || '.next';
			options.rightHandle				= options.rightHandle || '.prev';
			options.disableClass				= options.disableClass || 'disabled';
			options.itemClickAction		= options.itemClickAction || function(e) {};
			options.itemHoverOverAction	= options.itemHoverOverAction || function(e) {};
			options.itemHoverOutAction	= options.itemHoverOutAction || function(e) {};
			return options;
		};
		
		p.moveToItem = function(index) {
			if(index < 0) {
				index = 0;
			} else if(index > (_this.outerWidths.length -1)) {
				return;
			}

			//add widths of each point up to the end point
			var position = 0;
			for (var i = 0; i < index; i++) {
				position -= _this.outerWidths[i];
			}
			
			//Animate if not already animating
			if(!_this.isAnimating) {
				_this.isAnimating = true;
				_this.strip.animate({left:position}, 'slow', function() {
					_this.isAnimating = false;
					_this.start = index;
					//calculate the disabled class
					var min = _this.start - _this.range;
					var max = _this.start + _this.range;
					if(min < 0) {
						_this.left.addClass(_this.disableClass);
					} else {
						_this.left.removeClass(_this.disableClass);
					}
					
					if(max > (_this.outerWidths.length -1)) {
						_this.right.addClass(_this.disableClass);
					} else {
						_this.right.removeClass(_this.disableClass);
					}
				});
			}
		};
		
		//Private methods
		var _eventScrollLeft = function(e) {
			e.stopPropagation();
			e.preventDefault();
			
			_this.moveToItem(_this.start - _this.range);
		}
		
		var _eventScrollRight = function(e) {
			e.stopPropagation();
			e.preventDefault();

			_this.moveToItem(_this.start + _this.range);
		}
		
		return p;
		
	})();
	//jQuery adaptor so that anytime this method is called it will create a new instance of the class
	$.fn.extend(new function() {
		this[name] = function(options, returnInstance) {
			returnInstance = returnInstance || false; //Offer access to class methods
			var instance = new c(this, options || {}); // Pass class 'this' which is the wrapper or jquery object
			if(returnInstance) {
				return instance;
			}
			return this;
		}
	});
})('jQuery', 'hallway');

(function(scope) {
	//let anyone name this class
	window[scope] = function(options) {
		if(this.__construct) {
			this.__construct(options || {}); //call the construct
		}
	};
	
	/* Base Class Definition
	-------------------------------------*/
	window[scope].prototype = (function() {
		/* Private Properties
		-------------------------------------*/
		var p = window[scope].prototype;      //scope
		
		/* Construct
		-------------------------------------*/
		p.__construct = function(options) {
			$('#year').change(_bind(_setMakeModelMpg, this));
			
			$('#make').change(_bind(_setModelMpg, this));
			
			$('#model').change(_bind(_setMpg, this));
			
			//$('#state').change(_bind(_setKwh, this));
			
			$('#coda_savings').bind('submit', _validateSubmit);
			$('#coda_savings div.submit a.btn').click(_submitForm);
		};
		
		/* Public Methods
		-------------------------------------*/
		/**
		 * AJAX call to get the make given the year
		 *
		 * @param number the year
		 * @param function success callback
		 * @param function error callback
		 * @return void
		 */
		p.getMake = function(year, success, error) {
			$.ajax({
				type: "GET",
				url: window.location.href,
				dataType: 'json',
				data: { ajax: 'makes',  year: year},
				success: _bind(success, this),
				error: _bind(error, this)});
		};
		
		/**
		 * AJAX call to get the model given the year and make
		 *
		 * @param number the year
		 * @param string the make
		 * @param function callback
		 * @return void
		 */
		p.getModel = function(year, make, callback) {
			$.getJSON(window.location.href, {
				ajax: 'models', 
				year: year, 
				make: make}, _bind(callback, this));
		};
		
		/**
		 * AJAX call to get the mpg given the year, make and model
		 *
		 * @param number the year
		 * @param string the make
		 * @param string the model
		 * @param function callback
		 * @return void
		 */
		p.getMpg = function(year, make, model, callback) {
			$.getJSON(window.location.href, {
				ajax: 'mpg', 
				year: year, 
				make: make, 
				model: model},  _bind(callback, this));
		};
		
		/**
		 * AJAX call to get the kwh given the state
		 *
		 * @param number the state
		 * @param function callback
		 * @return void
		 */
		p.getKwh = function(state, callback) {
			$.getJSON(window.location.href, {
				ajax: 'kwh', 
				state: state}, _bind(callback, this));
		};
		
		/* Private Methods
		-------------------------------------*/
		var _setMakeModelMpg = function() {
			var year = $('#year').find('option:selected').html();
			
			var date = new Date();
			date.setTime(date.getTime()+(10*24*60*60*1000));
			document.cookie = 'scYear='+year+'; expires='+date.toGMTString()+'; path=/';
			
			this.getMake(year, _bind(_getMakeResponse, this), _changeMakeModelToInput);
		};
		
		var _setModelMpg = function() {
			var year = $('#year').find('option:selected').html();
			var make = $('#make').find('option:selected').html();
			
			var date = new Date();
			date.setTime(date.getTime()+(10*24*60*60*1000));
			document.cookie = 'scMake='+make+'; expires='+date.toGMTString()+'; path=/';
			
			this.getModel(year, make, _bind(_getModelResponse, this));
		};
		
		var _setMpg = function() {
			var year = $('#year').find('option:selected').html();
			var make = $('#make').find('option:selected').html(); 
			var model = $('#model').find('option:selected').html();
			
			var date = new Date();
			date.setTime(date.getTime()+(10*24*60*60*1000));
			document.cookie = 'scModel='+model+'; expires='+date.toGMTString()+'; path=/';
			
			this.getMpg(year, make, model, _bind(_getMpgResponse, this));
		};
		
		var _setKwh = function() {
			var state = $('#state').find('option:selected').html();
			
			var date = new Date();
			date.setTime(date.getTime()+(10*24*60*60*1000));
			document.cookie = 'scModel='+model+'; expires='+date.toGMTString()+'; path=/';
			
			this.getKwh(state, _bind(_getKwhResponse, this));
		};
		
		var _getMakeResponse = function(response) {
			if(document.getElementById('make').tagName.toLowerCase() != 'select') {
				_changeMakeModelToSelect();
			}
			
			$('#make').html('<option>'+response.join('</option><option>')+'</option>');
			
			_setModelMpg.call(this);
			
		};
		
		var _getModelResponse = function(response) {
			$('#model').html('<option>'+response.join('</option><option>')+'</option>');
			
			_setMpg.call(this);
		};
		
		var _getMpgResponse = function(response) {
			$('#mpg').attr('value', response);
		};
		
		var _getKwhResponse = function(response) {
			$('#kwh').attr('value', response);
		};
		
		var _changeMakeModelToInput = function() {
			$('#make').replaceWith('<input type="text" id="make" name="make" />');
			$('#model').replaceWith('<input type="text" id="model" name="model" />');
		};
		
		var _changeMakeModelToSelect = function() {
			$('#make').replaceWith('<select id="make" name="make"></select>');
			$('#model').replaceWith('<select id="model" name="model"></select>');
		};
		
		var _submitForm = function(e) {
			e.preventDefault();
			$('#coda_savings div.submit input').get(0).click();
		};
		
		var _validateSubmit = function(e) {
			var valid = true;
			if(document.getElementById('make').tagName.toLowerCase() != 'select') {
				if(!$('#make').attr('value') || $('#make').attr('value') == 'Cannot be Empty!' || $('#make').attr('value') == 'Letters and numbers only!') {
					$('#make').addClass('error');
					$('#make').attr('value', 'Cannot be Empty!');
					
					var labeler = $('#make').siblings('label');
					labeler.addClass('error');
					Cufon.replace(labeler);
					
					valid = false;
				} else if(!validAlphaNum($('#make').attr('value'))) {
					$('#make').addClass('error');
					$('#make').attr('value', 'Letters and numbers only!');
					
					var labeler = $('#make').siblings('label');
					labeler.addClass('error');
					Cufon.replace(labeler);
					
					valid = false;
				} else {
					var labeler = $('#make').siblings('label');	
					$('#make').removeClass('error');
					
					labeler.removeClass('error');
					Cufon.replace(labeler, { fontFamily: 'Avenier Book', separate: 'words' });
				}
			}
			
			if(document.getElementById('model').tagName.toLowerCase() != 'select') {
				if(!$('#model').attr('value') || $('#model').attr('value') == 'Cannot be Empty!' || $('#model').attr('value') == 'Letters and numbers only!') {
					$('#model').addClass('error');
					$('#model').attr('value', 'Cannot be Empty!');
					
					var labeler = $('#model').siblings('label');
					labeler.addClass('error');
					Cufon.replace(labeler);
					
					valid = false;
				} else if(!validAlphaNum($('#model').attr('value'))) {
					$('#model').addClass('error');
					$('#model').attr('value', 'Letters and numbers only!');
					
					var labeler = $('#model').siblings('label');
					labeler.addClass('error');
					Cufon.replace(labeler);
					
					valid = false;
				} else {
					$('#model').removeClass('error');
					var labeler = $('#model').siblings('label');
					
					labeler.removeClass('error');
					Cufon.replace(labeler, { fontFamily: 'Avenier Book', separate: 'words' });
				}
			}
			
			var price = $('#coda_savings input#price');
			var mpg = $('#coda_savings input#mpg');
			var elec = $('#coda_savings input#kwh');
			if (checkNum(price.val()) != true) {
				price.addClass('error');
				price.siblings('span').text('This must be a number');
				price.siblings('label').addClass('error');
				Cufon.replace(price.siblings('label'));
				valid = false;
			} else if (isPositive(price.val()) != true) {
				price.addClass('error');
				price.siblings('span').text('This must be positive');
				price.siblings('label').addClass('error');
				Cufon.replace(price.siblings('label'));
				valid = false;
			} else if (price.val().length >= 10) {
				price.addClass('error');
				price.siblings('span').text('This number is too long');
				price.siblings('label').addClass('error');
				Cufon.replace(price.siblings('label'));
				valid = false;
			} else {
				price.removeClass('error');
				price.siblings('span').text('');
				price.siblings('label').removeClass('error');
				Cufon.replace(price.siblings('label'), { fontFamily: 'Avenier Book', separate: 'words' });
			}
			
			if (checkNum(mpg.val()) != true) {
				mpg.addClass('error');
				mpg.siblings('span').text('This must be a number');
				mpg.siblings('label').addClass('error');
				Cufon.replace(mpg.siblings('label'));
				valid = false;
			} else if (isPositive(mpg.val()) != true) {
				mpg.addClass('error');
				mpg.siblings('span').text('This must be positive');
				mpg.siblings('label').addClass('error');
				Cufon.replace(mpg.siblings('label'));
				valid = false;
			} else if (mpg.val().length > 3) {
				mpg.addClass('error');
				mpg.siblings('span').text('This number is too long');
				mpg.siblings('label').addClass('error');
				Cufon.replace(mpg.siblings('label'));
				valid = false;
			} else {
				mpg.removeClass('error');
				mpg.siblings('span').text('');
				mpg.siblings('label').removeClass('error');
				Cufon.replace(mpg.siblings('label'), { fontFamily: 'Avenier Book', separate: 'words' });
			}
			
			if (checkNum(elec.val()) != true) {
				elec.addClass('error');
				elec.siblings('span').text('This must be a number');
				//elec.siblings('label').addClass('error');
				//Cufon.replace(elec.siblings('label'));
				valid = false;
			} else if (isPositive(elec.val()) != true) {
				elec.addClass('error');
				elec.siblings('span').text('This must be positive');
				//elec.siblings('label').addClass('error');
				//Cufon.replace(elec.siblings('label'));
				valid = false;
			} else if (elec.val().length >= 12) {
				elec.addClass('error');
				elec.siblings('span').text('This number is too long');
				valid = false;
			} else {
				elec.removeClass('error');
				elec.siblings('span').text('');
				//elec.siblings('label').removeClass('error');
				//Cufon.replace(elec.siblings('label'));
			}
			
			if (valid != true) {
				e.preventDefault();
			}
		};
		
		var checkNum = function(val) {
			val = val.replace("$", "");
			if (isNaN(val) == false && val != '') {
				return true;
			} else {
				return false;
			}
		};
		
		var isPositive = function(val) {
			val = val.replace("$", "");
			if (val < 0) {
				return false;
			} 
			return true;
		};
		
		var validAlphaNum = function(str) {
                return (/^([a-zA-Z0-9_-]+)$/).test(str.replace(' ', '').replace(' ', '').replace(' ', '').replace(' ', '').replace(' ', '').replace(' ', ''));
        };
		
		var _bind = function() {
                //lets get the args for this.
                var args = Array.prototype.slice.call(arguments);
				
                //this is the function that bind attached to
                var __method = args.shift(), __scope = args.shift();
                
                if(typeof __method != 'function')
                {
                        return null;
                }
                
                //now lets run this function
                return function() {
                        //lets concat the arguments from the old one and the new one
                        for(var i = 0, length = arguments.length, args2 = []; i < length; i++)
                        {
                                args2.push(arguments[i]);
                        }
                        return __method.apply(__scope, args2.concat(args));
                };
        };
		
		return p;
	})();

})('savingsCalculatorForm');

/* Driver
-------------------------------------*/
new savingsCalculatorForm();


	/*
*	Slide show code
*
*/

			

	
	function slideSwitch() {
		
		var $active = $('#slide div.active');

		if ( $active.length == 0 ) $active = $('#slide div:last');


		var $next =  $active.next().length ? $active.next()	: $('#slide div:first');
		var $child = $active.next().length ? $active.children() : $('#slide div:last').children();	
		var $nextChild = $active.next().length ? $next.children() : $('#slide div:first').children();	
	
		$active.addClass('last-active');
	
			$child.animate({opacity: 0.0}, 1000);	
			$nextChild.animate({opacity: 1.0}, 1000);			
			
			$next.css({opacity: 0.0})
				.addClass('active')
				.animate({opacity: 1.0}, 1000, function() {
					$active.removeClass('active last-active');	
				 });
   
	};
  
 	$(document).ready(function() {	 	
		$(function() {
				setInterval( "slideSwitch()", 5000 );
		});
  	});

	
