/* Manufacturer Incentives Widget JS v0.1.1 by Josh Lizarraga */
/* Copyright 2009 Autofusion.com */

(function(){

/* AF Library */

if(typeof(YAHOO.AUTOFUSION) == "undefined"){
	YAHOO.namespace("AUTOFUSION");
}
if(typeof(YAHOO.AUTOFUSION.items) == "undefined"){
	YAHOO.AUTOFUSION.items = new Object();
}
var AF = YAHOO.AUTOFUSION;

/* Manufacturer Incentives Widget */

// MIW Constructor
AF.IncentivesWidget = function(afID, afConfig){
	// Properties:
	this.id = (afID) ? afID : false;
	this.config = (afConfig) ? afConfig : false;
	this.container = document.getElementById(this.id);
	this.confid = false;
	this.make = false;
	this.years = false;
	this.models = false;
	this.MIL = false;
	this.currentResults = [];
	this.currentResultIndex = 0;
	this.quoteCGI = "/cgi-bin/quick_quote.cgi";
	this.altTemplate = false;
	this.savedIncentive = false;
	this.savedButtons = false;
	this.fadeLevel = 0.5;
	this.fadeSpeed = 0.25;
	this.fadeEasing = YAHOO.util.Easing.easeOut;
	this.header = false;
	this.body = false;
	this.nav = false;
	this.footer = false;
	this.selectYear = false;
	this.selectModel = false;
	this.prev = false;
	this.next = false;
	this.viewing = false;
	this.info = false;
	this.busy = false;
	if(this.config != false){
		for(var i in this.config){
			this[i] = this.config[i];
		}
	}
	var that = this;
	// Validation:
	this.validate = {
		text: function(pInput){
			if(pInput.value.length > 1){
				return true;
			} else {
				return "Please enter a valid name.";
			}
		},
		phone: function(pInput){
			var oStripped = pInput.value.replace(/[\(\)\.\-\ ]/g, "");
			oStripped = parseInt(oStripped);
			if(isNaN(oStripped) == false){
				if((oStripped + "").length == 7 || (oStripped + "").length == 10 || (oStripped + "").length == 11){
					return true;
				} else {
					return "Please enter a valid phone number.";
				}
			} else {
				return "Please enter a valid phone number.";
			}
		},
		email: function(pInput){
			var oPattern = /^.+@.+\..{2,6}$/;
			var oIllegal = /[\s\(\)\<\>\,\;\:\\\/\"\[\]]/;
			if(pInput.value.length > 1 && oPattern.test(pInput.value) && pInput.value.match(oIllegal) == null){
				return true;
			} else {
				return "Please enter a valid email address.";
			}
		}
	}; // this.validate{}
	// Methods:
	this.resultObject = function(pIncentive){
		// Basic:
		this.year = that.MIL.getValue(pIncentive.getElementsByTagName("year")[0]);
		this.model = that.MIL.getValue(pIncentive.getElementsByTagName("model_generic")[0]);
		// Rebate:
		this.rebate = false;
		if(pIncentive.getElementsByTagName("amount").length > 0){
			this.rebate = that.MIL.getValue(pIncentive.getElementsByTagName("amount")[1]);
		}
		// Rates:
		var oRates = pIncentive.getElementsByTagName("rate");
		this.lowestAPR = 100.00;
		this.rates = [];
		for(var i=0; i<oRates.length; i++){
			var oAPR = parseFloat(that.MIL.getValue(oRates[i]));
			if(oAPR < this.lowestAPR){
				this.lowestAPR = oAPR;
			}
			var oTerm = oRates[i].getAttribute("term");
			oTerm = (oTerm.toLowerCase().indexOf("months") > -1) ? oTerm : oTerm + " Months";
			this.rates.push({
				term: oTerm,
				apr: oAPR
			});
		}
		// Trims:
		var oTrims = pIncentive.getElementsByTagName("trim");
		if(oTrims.length > 0){
			this.appliesTo = [];
			for(var i=0; i<oTrims.length; i++){
				this.appliesTo.push(that.MIL.getValue(oTrims[i].getElementsByTagName("name")[0]));
			}
			this.appliesTo = this.appliesTo.join(", ");
		} else {
			this.appliesTo = "All trims!";
		}
		// URL:
		this.url = that.MIL.getValue(pIncentive.getElementsByTagName("details_link")[0]);
		if(that.altTemplate != false){
			this.url = this.url.replace(/TrimsIncentives/, that.altTemplate);
		}
		// Disclaimer:
		this.disclaimer = "<strong>Applies to: " + this.appliesTo + "</strong><br />" + that.MIL.getValue(pIncentive.getElementsByTagName("comment")[0]) + "<br />Expires " + that.MIL.getValue(pIncentive.getElementsByTagName("expiration")[0]) + '.<br /><a href="' + this.url + '#trims_incentives">Click here</a> for complete terms and conditions.';
	}; // this.resultObject()
	this.fadeContent = function(pTarget, pOpacity, pCallback){
		var oFade = new YAHOO.util.Anim(pTarget, {
				opacity: { to: pOpacity }
			}, that.fadeSpeed, that.fadeEasing);
		oFade.animate();
		if(YAHOO.env.ua.ie == 6 || YAHOO.env.ua.ie == 7){
			oFade.onComplete.subscribe(function(){
				pTarget.style.removeAttribute("filter");
			});
		}
		if(pCallback){
			oFade.onComplete.subscribe(pCallback);
		}
	}; // this.fadeContent()
	this.startLoad = function(){
		that.fadeContent(that.header, that.fadeLevel);
		that.fadeContent(that.body, that.fadeLevel);
		that.fadeContent(that.footer, that.fadeLevel, function(){
			that.container.appendChild(that.loadBar);
			that.toggleSelects(true);
			that.busy = !that.busy;
		});
	}; // this.startLoad()
	this.endLoad = function(){
		that.fadeContent(that.header, 1);
		that.fadeContent(that.body, 1);
		that.fadeContent(that.footer, 1, function(){
			that.container.removeChild(that.loadBar);
			that.toggleSelects(false);
			that.busy = !that.busy;
		});
	}; // this.endLoad()
	this.toggleSelects = function(pBoolean){
		if(YAHOO.util.Dom.inDocument(that.selectYear)){
			that.selectYear.disabled = pBoolean;
		}
		if(YAHOO.util.Dom.inDocument(that.selectModel)){
			that.selectModel.disabled = pBoolean;
		}
	}; // this.toggleSelects()
	this.populateHeader = function(){
		// Years:
		that.selectYear = document.createElement("select");
		that.selectYear.className = "miw-select-year";
		that.selectYear.disabled = true;
		var oYear = document.createElement("option");
		oYear.innerHTML = "Year";
		that.selectYear.appendChild(oYear);
		for(var i=0; i<that.years.length; i++){
			var oOption = document.createElement("option");
			oOption.innerHTML = that.years[i];
			that.selectYear.appendChild(oOption);
		}
		var oAllYears = document.createElement("option");
		oAllYears.innerHTML = "View All";
		that.selectYear.appendChild(oAllYears);
		that.header.appendChild(that.selectYear);
		// Models:
		that.selectModel = document.createElement("select");
		that.selectModel.className = "miw-select-model";
		that.selectModel.disabled = true;
		var oModel = document.createElement("option");
		oModel.innerHTML = "Model";
		that.selectModel.appendChild(oModel);
		for(var i in that.models){
			var oOptgroup = document.createElement("optgroup");
			oOptgroup.label = i;
			that.selectModel.appendChild(oOptgroup);
			for(var j=0; j<that.models[i].length; j++){
				var oOption = document.createElement("option");
				oOption.innerHTML = that.models[i][j];
				oOptgroup.appendChild(oOption);
			}
		}
		var oAllModels = document.createElement("option");
		oAllModels.innerHTML = "View All";
		that.selectModel.appendChild(oAllModels);
		that.header.appendChild(that.selectModel);
	}; // this.populateHeader()
	this.populateNav = function(){
		that.prev = document.createElement("a");
		that.prev.className = "miw-prev";
		that.prev.href = "javascript:void(0);";
		that.prev.innerHTML = "Previous";
		that.nav.appendChild(that.prev);
		that.next = document.createElement("a");
		that.next.className = "miw-next";
		that.next.href = "javascript:void(0);";
		that.next.innerHTML = "Next";
		that.nav.appendChild(that.next);
		that.viewing = document.createElement("div");
		that.viewing.className = "miw-viewing";
		that.viewing.innerHTML = "Please select a year &amp; model.";
		that.nav.appendChild(that.viewing);
		var oClear = document.createElement("div");
		oClear.className = "miw-clear";
		that.nav.appendChild(oClear);
	}; // this.populateNav()
	this.populateFooter = function(){
		that.footer.innerHTML = '\
			<a class="miw-links-af" href="http://www.autofusion.com/" target="_blank">&copy;2009 Autofusion.com</a>\
			<a class="miw-links-all" href="/incentives.html">View all Incentives</a>\
		';
	}; // this.populateFooter()
	this.infoBox = function(pColor, pMessage){
		that.info = document.createElement("div");
		that.info.className = "miw-info-box miw-box-" + pColor;
		that.info.innerHTML = pMessage;
		that.body.appendChild(that.info);
	}; // this.infoBox()
	this.removeAltContent = function(){
		var oLoaders = YAHOO.util.Dom.getElementsByClassName("miw-loading", null, that.container);
		for(var i=0; i<oLoaders.length; i++){
			oLoaders[i].parentNode.removeChild(oLoaders[i]);
		}
	}; // this.removeAltContent()
	this.sortIncentives = function(pXML){
		// Setup:
		var oReturn = [];
		// Process:
		var oIncentives = pXML.getElementsByTagName("Incentive");
		for(var i=0; i<oIncentives.length; i++){
			oReturn.push(new that.resultObject(oIncentives[i]));
		}
		// Return:
		return oReturn;
	}; // this.sortIncentives()
	this.loadIncentive = function(pIndex){
		var oIndex = (pIndex) ? pIndex : that.currentResultIndex;
		that.currentResultIndex = oIndex;
		var oResult = that.currentResults[oIndex];
		that.viewing.innerHTML = "Viewing " + (that.currentResultIndex + 1) + " of " + (that.currentResults.length) + " Results";
		that.wrapper.innerHTML = '';
		var oIncentiveDiv = document.createElement("div");
		oIncentiveDiv.className = "miw-incentive";
		that.wrapper.appendChild(oIncentiveDiv);
		if(oResult.rebate != false){
			var oAS = "OR AS";
			oIncentiveDiv.innerHTML = '\
				<div class="miw-rebate-amount">' + oResult.rebate + '</div>\
				<div class="miw-rebate-after">Factory<br />Rebate!</div>\
				<div class="miw-clear"></div>\
			';
		} else {
			var oAS = "AS";	
		}
		if(oResult.rates.length > 0){
			var oRatesHTML = '';
			for(var i=0; i<oResult.rates.length; i++){
				oRatesHTML += '<div>' + oResult.rates[i].apr + '% up to ' + oResult.rates[i].term + '</div>';
			}
			oIncentiveDiv.innerHTML += '\
				<div class="miw-apr">\
					<div class="miw-apr-before">' + oAS + '<br />LOW AS</div>\
					<div class="miw-apr-amount">' + oResult.lowestAPR + '%</div>\
					<div class="miw-apr-after">APR!</div>\
				</div>\
				<div class="miw-rates">' + oRatesHTML + '</div>\
				<div class="miw-clear"></div>\
			';
		}
		that.wrapper.innerHTML += '\
			<div id="' + that.confid + '-image" class="miw-image"></div>\
			<div class="miw-disclaimer">' + oResult.disclaimer + '</div>\
			<div class="miw-clear"></div>\
			<div class="miw-buttons">\
				<a class="miw-inventory" href="' + oResult.url + '#trims_incentives">View More Details</a>\
				<a class="miw-quote" href="javascript:void(0);">Get a Quick Quote</a>\
			</div>\
		';
		// Get Pricebooks image:
		that.getImageFromFeed();
	}; // this.loadIncentive()
	this.getIncentive = function(pYear, pModel){
		// Start loading:
		that.startLoad();
		// Info box?
		var oInfos = YAHOO.util.Dom.getElementsByClassName("miw-info-box", "div", that.container);
		for(var i=0; i<oInfos.length; i++){
			oInfos[i].parentNode.removeChild(oInfos[i]);
		}
		// Reset index:
		that.currentResultIndex = 0;
		// Make request:
		that.MIL.getYear(that.make, pModel, pYear, function(){
			that.currentResults = that.sortIncentives(that.MIL.XML);
			if(that.currentResults.length > 0){
				that.loadIncentive();
			} else {
				that.wrapper.innerHTML = '';
				that.viewing.innerHTML = "Please select a year &amp; model.";
				that.infoBox("yellow", "There are no current incentives for this model year. Please select another model.");
			}
			if(that.currentResults.length < 2){
				that.fadeContent(that.nav, that.fadeLevel);
			} else {
				that.fadeContent(that.nav, 1);
			}
			// End loading:
			that.endLoad();
		}); // that.MIL.getYear()
	}; // this.getIncentive()
	this.getImageFromFeed = function(){
		var oImageDiv = document.getElementById(that.confid + "-image");
		var oImage = document.createElement("img");
		var oSuccess = function(o){
			var oModels = o.responseXML.getElementsByTagName("model");
			var oSelectedYear = that.selectYear.options[that.selectYear.selectedIndex].innerHTML;
			var oSelectedModel = that.selectModel.options[that.selectModel.selectedIndex].innerHTML;
			for(var i=0; i<oModels.length; i++){
				var oYear = oModels[i].getAttribute("year");
				var oModel = oModels[i].getAttribute("name");
				if(oSelectedYear == oYear && oSelectedModel == oModel){
					oImage.src = oModels[i].getAttribute("image");
					oImage.alt = oYear + " " + that.make + " " + oModel;
					oImageDiv.appendChild(oImage);
					break;
				}
			}
		};
		var oFailure = function(o){
			oImage.src = "http://images.carprices.com/autofusion_data/usa/default_noimage.jpg";
			oImage.alt = "Photos coming soon!";
			oImageDiv.appendChild(oImage);
		};
		var oCallback = {
			success: oSuccess,
			failure: oFailure
		};
		var oRequest = YAHOO.util.Connect.asyncRequest("GET", "/xml_feeds/" + that.make.toLowerCase(), oCallback, null);
	}; // this.getImageFromFeed()
	this.showQuote = function(){
		that.busy = true;
		that.fadeContent(that.nav, that.fadeLevel);
		var oResult = that.currentResults[that.currentResultIndex];
		var oIncentiveDiv = YAHOO.util.Dom.getElementsByClassName("miw-incentive")[0];
		that.savedIncentive = oIncentiveDiv.innerHTML;
		var oButtonsDiv = YAHOO.util.Dom.getElementsByClassName("miw-buttons")[0];
		that.savedButtons = oButtonsDiv.innerHTML;
		oIncentiveDiv.innerHTML = '\
			<div class="miw-quote-title">Free Price Quote</div>\
			<div class="miw-quote-subtitle">All fields are required.</div>\
			<form class="miw-quote-form" action="' + that.quoteCGI + '">\
				<input type="hidden" name="comments" value="Incentives Widget Lead" />\
				<input type="hidden" name="year" value="' + oResult.year + '" />\
				<input type="hidden" name="make" value="' + that.make + '" />\
				<input type="hidden" name="model" value="' + oResult.model + '" />\
				<span>Name:</span>\
				<input type="text" name="firstname" />\
				<div class="miw-clear"></div>\
				<span>Phone:</span>\
				<input type="text" name="dayphone" />\
				<div class="miw-clear"></div>\
				<span>Email:</span>\
				<input type="text" name="email" />\
				<div class="miw-clear"></div>\
			</form>\
		';
		oButtonsDiv.innerHTML = '\
			<a class="miw-submit-form" href="javascript:void(0);">Submit Quote Form</a>\
			<a class="miw-cancel-form" href="javascript:void(0);">Back to Results</a>\
		';
	}; // this.showQuote()
	this.validateForm = function(){
		var oValid = true;
		var oForm = that.container.getElementsByTagName("form")[0];
		var oInputs = oForm.getElementsByTagName("input");
		var oBroken = false;
		for(var i=0; i<oInputs.length; i++){
			if(oBroken == false){
				if(oInputs[i].type != "hidden"){
					switch(oInputs[i].name){
						case "firstname":
							oValid = that.validate.text(oInputs[i]);
							if(oValid != true){
								oBroken = true;
							}
							break;
						case "dayphone":
							oValid = that.validate.phone(oInputs[i]);
							if(oValid != true){
								oBroken = true;
							}
							break;
						case "email":
							oValid = that.validate.email(oInputs[i]);
							if(oValid != true){
								oBroken = true;
							}
							break;
						default:
							oValid = that.validate.text(oInputs[i]);
					}
				}
			}
		}
		if(oValid == true){
			oForm.submit();
		} else {
			alert(oValid);
		}
	}; // this.validate
	this.handleChange = function(e){
		YAHOO.util.Event.stopPropagation(e);
		YAHOO.util.Event.preventDefault(e);
		var oTarget = YAHOO.util.Event.getTarget(e);
		if(oTarget.nodeName.toUpperCase() == "SELECT"){
			switch(oTarget.options[oTarget.selectedIndex].innerHTML){
				case "Year":
					break;
				case "Model":
					break;
				case "View All":
					window.location.href = "/incentives.html";
					break;
				default:
					if(that.selectYear.options[that.selectYear.selectedIndex].innerHTML != "Year" && that.selectModel.options[that.selectModel.selectedIndex].innerHTML != "Model"){
						that.getIncentive(that.selectYear.options[that.selectYear.selectedIndex].innerHTML, that.selectModel.options[that.selectModel.selectedIndex].innerHTML);
					}
			}
		}
	}; // this.handleChange()
	this.handleClick = function(e){
		YAHOO.util.Event.stopPropagation(e);
		var oTarget = YAHOO.util.Event.getTarget(e);
		switch(oTarget.className){
			case "miw-prev":
				if(that.currentResultIndex > 0 && that.busy == false){
					that.currentResultIndex--;
					that.loadIncentive();
				}
				break;
			case "miw-next":
				if(that.currentResultIndex + 1 < that.currentResults.length && that.busy == false){
					that.currentResultIndex++;
					that.loadIncentive();
				}
				break;
			case "miw-quote":
				that.showQuote();
				break;
			case "miw-submit-form":
				that.validateForm();
				break;
			case "miw-cancel-form":
				if(that.currentResults.length < 2){
					that.fadeContent(that.nav, that.fadeLevel);
				} else {
					that.fadeContent(that.nav, 1);
				}
				that.busy = false;
				that.loadIncentive();
				break;
			default:
				return true;
		}
	}; // this.handleClick()
	// Init:
	this.init = function(){
		// Header:
		this.header = document.createElement("div");
		this.header.className = "miw-header";
		this.container.appendChild(this.header);
		// Body:
		this.body = document.createElement("div");
		this.body.className = "miw-body";
		this.container.appendChild(this.body);
		// Footer:
		this.footer = document.createElement("div");
		this.footer.className = "miw-footer";
		this.container.appendChild(this.footer);
		// Load Bar:
		this.loadBar = document.createElement("div");
		this.loadBar.className = "miw-load-bar";
		// Start loading:
		this.startLoad();
		this.removeAltContent();
		this.populateHeader();
		// Nav:
		this.nav = document.createElement("div");
		this.nav.className = "miw-nav";
		this.body.appendChild(this.nav);
		// Incentive Wrapper:
		this.wrapper = document.createElement("div");
		this.wrapper.className = "miw-wrapper";
		this.body.appendChild(this.wrapper);
		// MILAPI:
		this.MIL = new MILAPI(this.confid);
		// Continue loading:
		this.populateNav();
		this.populateFooter();
		this.infoBox("green", "Select a year and model to search for available incentives.");
		// Attach listeners:
		YAHOO.util.Event.addListener(this.container, "click", this.handleClick);
		if(YAHOO.env.ua.ie > 0){
			// IE's "change" event does not bubble, and YUI 2.7.0 doesn't fix it. WAH!
			YAHOO.util.Event.addListener(this.container.getElementsByTagName("select"), "change", this.handleChange);
		} else {
			YAHOO.util.Event.addListener(this.container, "change", this.handleChange);
		}
		// End loading:
		this.endLoad();
	}; // this.init()
}; // AF.IncentivesWidget()

})();