﻿function fixContentHeight() {
	var main = document.getElementById("content");
	var right = document.getElementById("contentRight");
	/*alert("main.offsetHeight: " + main.offsetHeight
	+ "right.offsetHeight: " + right.offsetHeight
	);*/
	//alert(right.style.height);
	if (right && main.offsetHeight > right.offsetHeight)
		right.style.height = main.offsetHeight + "px";
	//alert(right.style.height)
}

function populateSearchControls(minYear, selMakeID, selModelID, selBstid, selMinPrice, selMaxPrice, maxYear) {
	var yearFromCtrl = getById("ddlYearFrom");
	var yearToCtrl = getById("ddlYearTo");
	var makeCtrl = getById("ddlMake");
	var modelCtrl = getById("ddlModel");
	var bstCtrl = getById("ddlBodyStyleType");
	var minPriceCtrl = getById("ddlMinPrice");
	var maxPriceCtrl = getById("ddlMaxPrice");
	populateUsedYears(yearFromCtrl, minYear);
	populateUsedYears(yearToCtrl, maxYear);
	populateUsedMakes(makeCtrl, selMakeID);
	if (selMakeID > 0) {
		populateUsedModels(modelCtrl, selMakeID, selModelID);
	}
	populateUsedBodyStyleTypes(bstCtrl, selBstid);
	if (selMinPrice > 0) minPriceCtrl.selectedIndex = getOptionIndexByValue(minPriceCtrl, selMinPrice);
	if (selMaxPrice > 0) maxPriceCtrl.selectedIndex = getOptionIndexByValue(maxPriceCtrl, selMaxPrice);
}

function doSearch(url, isRecycledSearch) {
	var qs = "";
	var yearfrom = getById("ddlYearFrom").options[getById("ddlYearFrom").selectedIndex].value;
	if (yearfrom > 0) qs += "&yearfrom=" + yearfrom;
	var yearto = getById("ddlYearTo").options[getById("ddlYearTo").selectedIndex].value;
	if (yearto > 0) qs += "&yearto=" + yearto;
	var make = getById("ddlMake").options[getById("ddlMake").selectedIndex].value;
	if (make > 0) qs += "&makeID=" + make;
	var model = getById("ddlModel").options[getById("ddlModel").selectedIndex].value;
	if (model > 0) qs += "&modelID=" + model;
	var bstype = getById("ddlBodyStyleType").options[getById("ddlBodyStyleType").selectedIndex].value;
	if (bstype > 0) qs += "&bodyStyleTypeID=" + bstype;
	var minPrice = getById("ddlMinPrice").options[getById("ddlMinPrice").selectedIndex].value;
	if (minPrice > 0) qs += "&minPrice=" + minPrice;
	var maxPrice = getById("ddlMaxPrice").options[getById("ddlMaxPrice").selectedIndex].value;
	if (maxPrice > 0) qs += "&maxPrice=" + maxPrice;
	if (isRecycledSearch) {
		var sort = document.getElementById("hdnSort").value;
		if (sort.length > 0) qs += "&sort=" + sort;
		var search = document.getElementById("hdnSearchID").value;
		if (search.length > 0) qs += "&searchid=" + search;
	}
	if (url.toString().indexOf('?') < 0) {
		qs = qs.replace("&", "?");
	}
	url += qs;
	redirect(url);
}

function doSort(url, sort) {
	var objSort = document.getElementById('hdnSort');
	if (objSort.value == sort) {
		sort += ' desc';
	}
	objSort.value = sort;
	doSearch(url, true);
	return false;
}
function hideLoadingMessage() {
	document.getElementById('divLoading').style.display = "none";
	document.getElementById('myframe').style.display = "";
}

var modelList;
var chromeModelList;
function prepareLeadRequest(excludeModels) {
	dojo.query("img.lrSubmit").onclick(function(e) {
		var callbacks = {
			"base": function(response) {
				if (response.success) {
					dojo.query(".form input").attr("disabled", "disabled");
					dojo.query(".form select").attr("disabled", "disabled");
					dojo.query(".form textarea").attr("disabled", "disabled");
					dojo.query("img.lrSubmit").style("display", "none");
				}
				alert(response.message);
			},
			"lrModal": function(response) {
				var ctrlPrefix = response.code;
				var ctrlErr = document.getElementById(ctrlPrefix + 'divError');
				if (response.success) {
					ctrlErr.style.color = '#F1A01B';
					ctrlErr.style.backgroundColor = '#4f4f4f';
					ctrlErr.innerHTML = response.message;
					ctrlErr.style.display = '';
					closeModal(ctrlPrefix + 'modalRequestInfo');
					trackEvent({ events: 'event2' });
				}
				else {
					ctrlErr.style.color = '#cc0000';
					ctrlErr.innerHTML = response.message;
					ctrlErr.style.display = '';
				}
			},
			"feedback": function(response) {
				if (response.success) {
					dojo.query(".form input").attr("disabled", "disabled");
					dojo.query(".form select").attr("disabled", "disabled");
					dojo.query(".form textarea").attr("disabled", "disabled");
					dojo.query(".form img.fb").style("display", "none");
				}
				alert(response.message);
			},
			"orderParts": function(response) {
				if (response.success) {
					dojo.query(".orderParts .form input").forEach(function(obj) {
						obj.value = "";
					});
					dojo.query(".orderParts .form textarea").forEach(function(obj) {
						obj.value = "";
					});
					closeModal('modalOrderParts');
					trackEvent({ events: 'event8' });
					alert(response.message);
				}
				else
					alert(response.message);
			}
		};
		var viewState = dojo.byId("__VIEWSTATE").parentNode;
		var aspnetForm = dojo.byId("aspnetForm");
		var postURL = dojo.attr(e.currentTarget, "href"); //changed this to an attribute to make more flexible
		var callbackOption = dojo.attr(e.currentTarget, "callback") || "base";
		if (viewState) aspnetForm.removeChild(viewState);
		dojo.xhrGet({
			"url": postURL,
			"form": dojo.byId("aspnetForm"),
			"handleAs": "json",
			"load": callbacks[callbackOption]
		});
		aspnetForm.insertBefore(viewState, aspnetForm.firstChild);
	});
	// I take advantage of this because it happens to be on every page, but would not ordinarily put this much functionality in a place like this
	if (!excludeModels) {
		modelList = new dojo.data.ItemFileReadStore({ url: "/data.aspx?fn=AllModels" });
		chromeModelList = new dojo.data.ItemFileReadStore({ url: "/data.aspx?fn=ChromeModels" });
		dojo.query(".yearDD").onchange(searchYearChanged).forEach(function(yearList) {
			searchYearChanged({ currentTarget: yearList });
		});	
		dojo.query(".makeDD").onchange(updateModelDropDown).forEach(function(makeList) {
			updateModelDropDown({ currentTarget: makeList });
		});
		dojo.query(".modelDD").onchange(updateTrimDropDown);
	}
}

function searchYearChanged(e) {
	var dropdownID = dojo.attr(e.currentTarget, "makeList");
	dojo.attr(dropdownID, "year", e.currentTarget.value);
	updateModelDropDown({currentTarget: dojo.byId(dropdownID)});
}

function updateModelDropDown(e) {
	var dropdownID = dojo.attr(e.currentTarget, "modelList");
	var year = dojo.attr(e.currentTarget, "year");
	var makeid = e.currentTarget.value;
	var ctrlNameAry = e.currentTarget.id.split('_');
	var invtypeID;
	if (ctrlNameAry.length > 1) {
		if (ctrlNameAry[0] = "GAQ") {
			invtypeID = "new";
		} else {
			invtypeID = "used";
		}
	} else {
		invtypeID = dojo.byId('lrType').value;
	}

	if (makeid > 0) {
		if (invtypeID == "new") {
			chromeModelList.fetch({
				"query": { "MakeID": makeid, "Year": year },
				"sort": [{ attribute: "Name"}],
				"onComplete": function(items) {
					var selectList = dojo.byId(dropdownID);
					clearSelectList(selectList);
					addOpt(selectList, "Select A Model", 0);
					for (var ndx = 0; ndx < items.length; ndx++)
						addOpt(selectList, items[ndx].Name, items[ndx].ID);
					dojo.attr(dropdownID, "disabled", makeid == 0);
				},
				"onError": function(err) {
					console.error(err);
				}
			});
		} else {
			modelList.fetch({
				"query": { "MakeID": makeid },
				"sort": [{ attribute: "Name"}],
				"onComplete": function(items) {
					var selectList = dojo.byId(dropdownID);
					clearSelectList(selectList);
					addOpt(selectList, "Select A Model", 0);
					for (var ndx = 0; ndx < items.length; ndx++)
						addOpt(selectList, items[ndx].Name, items[ndx].ID);
					dojo.attr(dropdownID, "disabled", makeid == 0);
				},
				"onError": function(err) {
					console.error(err);
				}
			});
		}
	}
	var tddid = dojo.attr(dropdownID, "trimList");
	if (dojo.byId(tddid)) {
		dojo.byId(tddid).selectedIndex = 0;
		dojo.attr(tddid, "disabled", "disabled");
	}
}

function updateTrimDropDown(e) {
	var dropdownID = dojo.attr(e.currentTarget, "trimList");
	var modelid = e.currentTarget.value;
	var invtypeID = dojo.byId('lrType').value;
	/*
		unlike the model dropdown list, we can't download ALL trims for ALL models and then sort thru the list, so we do an AJAX call each time the 
		model is changed. Hopefully one day in the future I'll figure out how to keep adding to the current store so that the list is completed over time,
		but for now it's a unneeded overhead
	*/
	if (dojo.byId(dropdownID)) {
		console.log("check");
		if (modelid > 0) {
			dojo.xhrGet({
				"url": "/data.aspx?fn=ModelTrims&modelid=" + modelid + "&invtype=" + invtypeID,
				"handleAs": "json",
				"load": function(response) {
					var selectList = dojo.byId(dropdownID);
					clearSelectList(selectList);
					addOpt(selectList, "Select A Trim", 0);
					for (var ndx = 0; ndx < response.items.length; ndx++)
						addOpt(selectList, response.items[ndx].Name, response.items[ndx].ID);
					dojo.attr(dropdownID, "disabled", modelid == 0);
				},
				"error": function(data) {

				}
			});
		} else {
			dojo.attr(dropdownID, "disabled", modelid == 0);
		}
	}
}

function toggleRequestInfo(visible) {
	var dimmer;
	if ((dimmer = dojo.byId("dimmer")) == null) {

		dimmer = document.createElement("iframe");
		dojo.body().appendChild(dimmer);
		dimmer.id = "dimmer";
		dimmer.frameBorder = 0;
		var vp = dijit.getViewport();
		dojo.style(dimmer, { "top": vp.t + "px", "left": vp.l + "px", "width": vp.w + "px", "height": vp.h + "px", "position": "absolute", "backgroundColor": "black", "opacity": 0 });
	}
	if (visible) {
		dojo.anim(dimmer, { "opacity": .5 }, 500);
	}
	else {
		dojo.anim(dimmer, { "opacity": 0 }, 500);
	}
}

function ShowHideContent(modname, section, action, label) {

	var labelName = modname + '_' + section + 'Label';
	var objLabel = document.getElementById(labelName);

	var sectionName = modname + '_' + section + "Content";
	var divSection = document.getElementById(sectionName);

	var minusName = sectionName + '_minus';
	var imgMinus = document.getElementById(minusName);

	var plusName = sectionName + '_plus';
	var imgPlus = document.getElementById(plusName);

	if (action == 'expand') {
		imgPlus.style.display = 'none';
		imgMinus.style.display = '';
		//divSection.style.display = '';
		dojo.removeClass(sectionName, "collapse");
	} else if (action == 'collapse') {
		imgPlus.style.display = '';
		imgMinus.style.display = 'none';
		//divSection.style.display = 'none';
		dojo.addClass(sectionName, action);
	}
	if (objLabel) { objLabel.innerHTML = label; }
}

function EvoxInExteriorSlideshow() {

	var currentThumb = 0;
	var imageList;
	var timer = null;

	function hilightThumb(obj) {
		if (obj == null) return;
		dojo.query(".evoxThumbs .selected").removeClass("selected");
		dojo.addClass(obj, "selected");
		var src = "http://imageonthefly.autodatadirect.com/images/?IMG=" + obj.id + "&HEIGHT=240&WIDTH=320&ACT=F";
		dojo.query(".miv")[0].src = src;
		currentThumb = obj.position;

		dojo.query(".currentView")[0].innerHTML = "You are viewing slide " + (currentThumb + 1) + " of " + imageList.length;
	}
	this.thumbSelected = function(e) {
		hilightThumb(e.currentTarget);
	};
	this.startSlideshow = function() {
		if (timer != null || imageList == null) return;
		timer = setInterval(function() {
			hilightThumb(imageList[currentThumb]);
			currentThumb = (currentThumb + 1) % imageList.length;
		}, 1000);
	};

	this.stopSlideshow = function() {
		clearInterval(timer);
		timer = null;
	};

	this.nextThumb = function() {
		hilightThumb(imageList[(currentThumb + 1) % imageList.length]);
	}
	this.prevThumb = function() {
		var nextNdx = currentThumb > 0 ? currentThumb - 1 : imageList.length - 1;
		hilightThumb(imageList[nextNdx]);
	}

	imageList = dojo.query(".EvoxThumb").onclick(this.thumbSelected).forEach(function(img, ndx) { img.position = ndx; });
	if (imageList.length > 0)
		hilightThumb(imageList[0]);
}

function select360View(obj) {
	if (dojo.byId("VideoFrame").src != dojo.attr(obj, "viewURL"))
		dojo.byId("VideoFrame").src = dojo.attr(obj, "viewURL");
}

function initialize360View() {
	var selected = dojo.query("input[name='views']:checked").forEach(function(obj) {
		select360View(obj);
	}).length == 1;
	var list = dojo.query("input[name='views']");

	if (!selected)
		list.onclick(function(e) {
			select360View(e.currentTarget);
		}).forEach(function(obj, ndx) {
			if (ndx == 0) {
				select360View(obj);
				obj.checked = "checked";
			}
		});
}
function paymentCalculate() {
	var valPrice = document.getElementById('pcPrice').value;
	if (!valPrice) {
		alert('You must enter a Purchase Price.');
		return;
	}
	var valDown = document.getElementById('pcDown').value;
	if (!valDown) valDown = 0;
	var valPrinciple = (valPrice - valDown);
	var valRate = document.getElementById('pcRate').value;
	if (!valRate) {
		alert('You must select an interest rate.');
		return;
	}
	var valTerm = document.getElementById('pcTerm').value;
	if (!valTerm) {
		alert('You must select a Loan Term');
		return;
	}

	if (valPrinciple > 0) {
		var valPayment = CalcPayment(valPrinciple, valRate, valTerm, null, null);
		objPayment = document.getElementById('pcPayment');
		objPayment.value = "$" + valPayment;
	} else {
		alert('Purchase Price minus Down Payment must exceed 0.');
	}
}
function budgetCalculate() {
	var valPayment = document.getElementById('bcPayment').value;
	if (!valPayment) {
		alert('You must enter a Monthly Payment.');
		return;
	}
	var valDown = document.getElementById('bcDown').value;
	if (!valDown) valDown = 0;
	var valRate = document.getElementById('bcRate').value;
	if (!valRate) {
		alert('You must select an interest rate.');
		return;
	}
	var valTerm = document.getElementById('bcTerm').value;
	if (!valTerm) {
		alert('You must select a Loan Term');
		return;
	}

	if (valPayment > 0) {
		var valPrinciple = CalcPayment(null, valRate, valTerm, valPayment, valDown);
		var objPrinciple = document.getElementById('bcPrice');
		objPrinciple.value = "$" + valPrinciple;
	} else {
		alert('Monthly Payment amount must exceed 0');
		return;
	}
}
function CalcPayment(principle, rate, term, payment, down) {

	rate = (rate / 100) / 12;
	if (!principle) {
		if (rate == 0) {
			principle = payment * term;
		} else {
			principle = ((payment * (1 - (Math.pow(1 / (1 + rate), term)))) / rate) + parseInt(down);
		}
		principle = Math.round(100 * principle) / 100;
		return principle;
	} else if (!payment) {
		if (rate == 0) {
			payment = principle / term;
		} else {
			payment = principle * rate / (1 - (Math.pow(1 / (1 + rate), term)))
		}
		payment = Math.round(100 * payment) / 100;
		return payment;
	}

}

function validateNumeric(obj) {
	if (!IsNumeric(obj.value)) {
		obj.value = obj.value.substring(0, obj.value.length - 1)
	}
}
function IsNumeric(sText) { return isNumeric(sText) };
function isNumeric(sText) {
	if (typeof sText == 'object') sText = sText.value; // If sent a object (like 'this') get it's value!
	if (sText.length == 0) return true;
	var retVal = (sText.match('[^0-9.]') == null);
	if (!retVal && (arguments.length > 1)) alert((arguments[1] != "") ? arguments[1] : "Please enter only numbers."); // Use optional 2nd parm do std or custom msg

	return retVal;
}

// this was a misunderstanding, the image doesn't rotate in javascript, but just a different image o0n different page loads
function RotateHomeSpecialsImage() {

	var imgAry = document.getElementsByName('imgHomeSpecials');
	//loop through images
	for (var i = 0; i < imgAry.length; i++) {
		imgObject = imgAry[i];
		//find currently displayed image
		if (imgObject.style.display == '') {
			imgName = imgObject.id;
			imgNameAry = imgName.split('_');
			//if it's last image reset image index to 1 else iterate to next index
			if (imgNameAry[1] == imgAry.length) {
				nextImageIndex = "1";
			} else {
				nextImageIndex = (imgNameAry[1] - 0) + 1;
			}
			//find next image and toggle it to display instead
			nextImageName = imgNameAry[0] + '_' + nextImageIndex;
			nextImageObject = document.getElementById(nextImageName);
			if (nextImageObject) {
				imgObject.style.display = 'none';
				nextImageObject.style.display = '';
				i = imgAry.length;
			}
		}
	}
	imageToggleTimer = setTimeout("RotateHomeSpecialsImage()", 5000);
}

function createDetailPagePrintDialog() {
	var printDialog = dojo.byId("prtDlg");
	if (!printDialog) {
		printDialog = document.createElement("div");
		dojo.body().appendChild(printDialog);
		pos = dojo.query("div[printOption='true']").forEach(function(obj, ndx) {
			var lblText = dojo.query("h2.printOnly", obj);
			if (lblText.length > 0)
				obj.optText = lblText[0].innerHTML;
		});

		var optionsHTML = "";
		for (var ndx = 0; ndx < pos.length; ndx++)
			optionsHTML += "<div><input type='checkbox' checked='checked' onclick='togglePrintability(\"" + pos[ndx].id + "\")'/><label>" + pos[ndx].optText + "</label></div>";

		dojo.attr(printDialog, { "id": "prtDlg", "class": "modal", "style": "width:308px; display:none;" });
		printDialog.innerHTML = "<div class='header' onclick='closeModal(\"prtDlg\")'><img src='/images/DowntownJaguar/header_printPref.gif' alt='Print Options'/></div>"
								+ "<div class='content'>"
								+ optionsHTML
								+ "<img src='/images/DowntownJaguar/button_print.gif' alt='Print' style='margin: 10px 0; cursor:pointer;' onclick='doDetailPagePrint()'/>"
								+ "</div>";
	}
	openModal("prtDlg");
	return false;
}

function togglePrintability(sectionName) {
	dojo.toggleClass(sectionName, "noPrint");
}
function doDetailPagePrint() {
	var cdAnim = closeModal("prtDlg");
	dojo.connect(cdAnim, "onEnd", function() { window.print() });
}

function EvoxColorPicker(imageColor, imageName) {
	var baseURL = "http://imageonthefly.autodatadirect.com/images/?IMG="; 
	var noPic = "http://www.carsoup.com/images/newdetail/no_images_sideView.gif"
	var imageSize = '&HEIGHT=240&WIDTH=320'
	var _currentImageColor = imageColor;
	var mainImage, colorDisplay;

	function buildImageColorPath() {
		if (!imageName) {
			mainImage.src = noPic;
		} else {
			mainImage.src = baseURL + imageName + imageSize;
		}
	}
	function setColorDisplay(obj) {
		if (colorDisplay != null)
			colorDisplay.parentNode.removeChild(colorDisplay);
		colorDisplay = dojo.clone(dojo.byId(obj.title));
		dojo.query(".mainCPViewer")[0].appendChild(colorDisplay);
	}
	this.changeColor = function(e) {
		_currentImageColor = dojo.attr(e.currentTarget, "imageCC");
		imageName = dojo.attr(e.currentTarget, "imagePath");
		buildImageColorPath();
		setColorDisplay(e.currentTarget);
	}
	mainImage = dojo.query(".mainCPViewer img")[0];
	dojo.query(".evoxColors a").onclick(this.changeColor).forEach(function(obj, ndx) { if (ndx == 0) setColorDisplay(obj); });
	if(_currentImageColor)
		buildImageColorPath();
}

function changeDisplayedEvent(objSelect) {
	var eventid = objSelect.value;
	window.location = '/events.aspx?eventid=' + eventid;
}

var clone;
function toggleEventImage(path, objThumb) {
	var objEmbed;
	var objVidDiv = document.getElementById('divVideo');
	if (objVidDiv.style.display == "") {
		objEmbed = document.getElementById('embedWrap');
		clone = objEmbed.cloneNode(true);
		objVidDiv.removeChild(objEmbed);
		objVidDiv.style.display = "none";
	}
	document.getElementById('imgMain').style.display = "";
	document.getElementById('imgMain').src = path;
	var thumbName = "";
	var objLoopThumb
	deactivateThumbStyle();
	objThumb.setAttribute("class", "eventThumbActive");
}
function toggleEventVideo() {
	if (clone) {
		document.getElementById('divVideo').appendChild(clone);
	} 
	document.getElementById('divVideo').style.display = '';
	document.getElementById('imgMain').style.display = 'none';
	deactivateThumbStyle();
	document.getElementById('imgThumb_v').setAttribute("class", "eventThumbActive");
}
function deactivateThumbStyle() {
	document.getElementById('imgThumb_v').setAttribute("class", "eventThumb");
	for (var i = 0; i < 9; i++) {
		thumbName = "imgThumb_" + i;
		objLoopThumb = document.getElementById(thumbName);
		if (objLoopThumb) objLoopThumb.setAttribute("class", "eventThumb");
	}
}

function trackEvent(obj, isPageEvent) {
	if (isPageEvent) {
		dojo.addOnLoad(function() {
			if (dojo.global.eventTracker) return;
			_trackEvent(obj);
			dojo.global["eventTracker"] = true;
		});
	}
	else {
		_trackEvent(obj);
	}
}

function _trackEvent(obj) {
	var trackFrame = dojo.byId("ots");
	if (trackFrame) dojo.body().removeChild(trackFrame);

	trackFrame = document.createElement("iframe");
	trackFrame.id = "ots";
	trackFrame.src = "/Pages/DowntownJaguar/Tracker.aspx?" + dojo.objectToQuery(obj);
	trackFrame.className = "trackFrame";

	dojo.body().appendChild(trackFrame);

}

function validateRegistration() {
	var retval = true;
	var retmsg = "";
	var objInput = document.getElementById('evreg_Name');
	if (objInput) {
		if (objInput.value.length == 0) {
			retval = false;
			retmsg = "You must enter your name.\r\n";
		}
	}
	objInput = document.getElementById('evreg_Email');
	if (objInput) {
		if (objInput.value.length == 0) {
			retval = false;
			retmsg = retmsg + "You must enter your email address.";
		}
	}
	if (retmsg.length > 0) alert(retmsg);
	return retval;
}
