if (!window.IBDOM) {alert("IBDOM Not loaded!")}

IBDOM.IBElement.methods["hide"] = function() {
	this.style.display = "none";
};

IBDOM.IBElement.methods["show"] = function() {
	_a=arguments;
	dv=_a[0] ? _a[0] : "block";
	this.style.display = dv;
};

function noop(){}

function handleError(s) {
	if (
		(location.href.indexOf("staging") != -1)
		||
		(location.href.indexOf("stg-web") != -1)
		||
		(location.href.indexOf("localhost") != -1)
		||
		(location.href.indexOf("://172") != -1)
		)
		alert("ERROR: " + s);
}

if (window.DWREngine) {
	DWREngine.setErrorHandler(handleError);
}

function signOutResponse(profileInfo){
	if (document.cookie && document.cookie.length > 0) {
		var date = new Date();
		date.setTime(0);
		document.cookie = "InternetBrandsProfileId=; expires=" + date.toGMTString() + "; path=/";
	}
	top.location.href = "./search";
}

if (!window.imageUrlPrefix) {
	imageUrlPrefix = '//cdcssl.ibsrv.net';
}
if (!window.dynImageUrlPrefix) {
	dynImageUrlPrefix = '//www.carsdirect.com'
}
AKAMAI_RESIZE_PREFIX = dynImageUrlPrefix + "/used_cars/images/autoResize?";

IMAGE_CACHE = new Array();

BLANK_IMAGE_URL = "//cdcssl.ibsrv.net/common/x.gif";

function addImageToCache(location) {
	theImage = IMAGE_CACHE[scape(location)];
	if (!theImage) {
		theImage = IMAGE_CACHE[scape(location)] = new Image();
		theImage.src = BLANK_IMAGE_URL;
		theImage.srcToProcess = location;
	}
	return theImage;
}//addImageToCache

function processCachedImages() {
	for (imgKey in IMAGE_CACHE) {
		if (!IMAGE_CACHE[imgKey].src || (theImage.src == BLANK_IMAGE_URL)) {
			IMAGE_CACHE[imgKey].src = IMAGE_CACHE[imgKey].srcToProcess;
		}
	}
}//processCachedImages

/* start DOM-esque stuff */
function findElement(e,c,tagMatch) {
foundElement = false;
te = e;
while(te && !foundElement) {
	if (te && te.tagName && (te.tagName.toLowerCase() == tagMatch) && te.className && (te.className.indexOf(c) != -1)) {
		foundElement = te;
	} else {
		te = te.parentNode;
	}
}
return te;
}//findElement

function freezeEvent(e) {
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
return false;
}//freezeEvent

function getEvent(event) {
return (event ? event : window.event);
}//getEvent()

function getEventElement(e) {
return (e.srcElement ? e.srcElement: (e.target ? e.target : e.currentTarget));
}//getEventElement()

function populateSelect(selectObject, collectionOfStrings, defaultOptionString, defaultOptionValue, optionSelectValueMatch, postProcessor) {
	selectObject.removeAllChildren();
	matchingIndex = 0;

	if(defaultOptionString){
		firstOption = selectObject.appendChild(document.createElement("option"));
		firstOption.text = defaultOptionString;
		firstOption.value = defaultOptionValue;
	}

	selectMatch = false;

	for (mcount=0;(selectItem=collectionOfStrings[mcount]);mcount++) {
		opt = selectObject.appendChild(document.createElement("option"));
		opt.text = opt.value = selectItem;
		if (optionSelectValueMatch && (optionSelectValueMatch != "undefined") && (optionSelectValueMatch.toLowerCase() == opt.value.toLowerCase())) {
			opt.selected = "selected";
			selectMatch = true;
		}
	}//loop thru passed strings
	if (!selectMatch) selectObject.selectedIndex = 0;
	if (postProcessor) {
		setTimeout(
			function() {
				postProcessor.call();
			}
			,
			0
		);
	}
}//popuplateSelect

function registerEvent(o,eventString,funcPointer) {
	if (o.addEventListener) {
		o.addEventListener(eventString,funcPointer,false);
	} else if (o.attachEvent) {
		o.attachEvent("on" + eventString,funcPointer);
	} else {
		o["on" + eventString] = funcPointer;
	}
}//registerEvent

function selectPullDownValue(po,v) {
	found = false;
	for(i=0;opt = po.options[i];i++) {
		if (opt.value == v) {
			found = true;
			opt.selected = true;
		}//opt value match
		else {
			opt.selected = false;
		}
	}//loop thru each option of pull-down
	if (found) {
		changeAction = po.onchange;
		if (changeAction) {
			po.onchange.call();
		}//changeAction exists
	}
}//selectPullDownValue

/* end DOM-esque stuff */

/* start CORE-esque stuff */

function scape(s) {
	return window.encodeURIComponent ? window.encodeURIComponent(s) : escape(s);
}//escape/encodeURIComponent

function getStrippedWhite(s) {
	return s.replace(/[ \r\n\t\f\s]+/gi,'');
}//getStrippedWhite

function getTrimmed(s) {
	return s.replace(/^[ \r\n\t\f\s]+/gi,'').replace(/[ \r\n\t\f\s]+$/gi,'');
}//getTrimmed

function getInt(s) {
s = s.replace(/^ *0+/gi,'');
if ((s == "") || (s.indexOf(".") == 0)) s = 0;
i = parseInt(s);
return i;
}

function error(message){
	if($e('messages')){
		$e('messages').innerHTML += message + '<br />';
	} else {
		alert(message);
	}
}

function debugObject(obj){
	if($e('messages')){
		for(var key in obj){
			debug(key + ' = ' + obj[key]);
		}
	}
}

function debug(message) {
	if($e('messages')){
		$e('messages').innerHTML += message + '<br />';
	} 
}//debug

function setPermCookie(k,v) {
	//todo: set domain field once we've got a better handle on what it might be. heh.
	document.cookie = k + "=" + v + "; path=/; expires=Tue, 12 Mar 2030 19:17:48 GMT";
}//setPermCookie

function getCookieValue(theKey) {
	cFields = document.cookie.split("; ");
	kanswer = null;
	for (cc=0;!kanswer&&(ck=cFields[cc]);cc++) {
		cks=ck.split("=");
		kanswer = ((cks[0] == theKey) ? cks[1] : null);
	}//loop thru cookies
	return kanswer;
}//getCookieValues

/* end CORE-esque stuff */

/* start visual-esque stuff */

	function getScrollX() {
	var sx = 0;
	if (self.pageXOffset)
		sx = self.pageXOffset;
	else if (document.documentElement && document.documentElement.scrollLeft)
		sx = document.documentElement.scrollLeft;
	else if (document.body)
		sx = document.body.scrollLeft;
	return sx;
	}//getScrollX()

	function getScrollY() {
	var sy = 0;
	if (self.pageYOffset)
		sy = self.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop)
		sy = document.documentElement.scrollTop;
	else if (document.body)
		sy = document.body.scrollTop;
	return sy;
	}//getScrollY()
	
	function getWindowWidth() {
		var ww = 0;
		if (self.innerWidth)
			ww = self.innerWidth;
		else if (document.documentElement && document.documentElement.clientWidth)
			ww = document.documentElement.clientWidth;
		else if (document.body)
			ww = document.body.clientWidth;
		return ww;
	}
	
	function getWindowHeight() {
	var wh = 0;
	if (self.innerHeight)
		wh = self.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		wh = document.documentElement.clientHeight;
	else if (document.body)
		wh = document.body.clientHeight;
	return wh;
	}//getWindowHeight()
	
	function makeWindow(u,w,h) {
		window.open(u,"","width="+w+",height="+h+",scrollbars,resizable,status,toolbar,titlebar");
	}//makeWindow

/* end visual-esque stuff */

/* start CDC stuff */

eLA_Win = null;
eLA_url = "//www.carsdirect.com/Advisor/AdvisorMainFrame.html";

function open_eLA_Window() 
{
  if (!eLA_Win || eLA_Win.closed)
    {
      eLA_Win = window.open(eLA_url, "eLA_Win", "width=378,height=465,resizable=0");
    }
  else
    if (!eLA_Win.closed)
      {
        eLA_Win.focus();
      }
}//open_eLA_Window

/* end CDC stuff */

/* start used cars stuff */

function populateMakes(makeList) {
	domMake = $e("makeControl").removeAllChildren();
	selectedItem = 0;
	for (mcount=0;(makeItem=makeList[mcount]);mcount++) {
		opt = IBDOM.IBElement.getAugmentedElement(domMake.appendChild(document.createElement("option")));
		opt.text = opt.value = makeItem;
		if (make.toLowerCase() == makeItem.toLowerCase()) {
			opt.selected = true;
			opt.setClassValue("selected");
			selectedItem = mcount;//(mcount + 1);
			PREVIOUS_SELECTED_MAKE = opt;
			processMakeChange(domMake);
		}
	}//loop thru passed makes
	domMake.selectedIndex = selectedItem;
}//populateMake

PREVIOUS_SELECTED_MAKE = null;

function processMakeChange(selectObject) {

	if (PREVIOUS_SELECTED_MAKE) {
		PREVIOUS_SELECTED_MAKE.unsetClassValue("selected");
	}

	if (selectObject.selectedIndex != 0) {
		chosenMake = IBDOM.IBElement.getAugmentedElement(selectObject.options[selectObject.selectedIndex]);
		chosenMake.setClassValue("selected");
		PREVIOUS_SELECTED_MAKE = chosenMake;
		chosenMakeValue = chosenMake.value;
		if (chosenMakeValue) {
			//make is a global variable defined in the jsp
			make = chosenMakeValue;
			UsedCarSearchManager.getAllModelsWithListings(chosenMakeValue,populateModels);
		}//make value is not null or empty
	}//if valid make was picked
}//processMakeChange

function setModelsCount(count) {
	if (count && (count != "null") ) {
		$e("listingsCount").setTextData(IBDOM.Utils.getFormattedNumber(count));
		$e("listingsMeta").setTextData(" listings");
	}
}//setMakeCount

function populateModels(modelList) {
	populateSelect($e("modelControl"),modelList,null,null,model); //,model
}//populateModels

PREVIOUS_SELECTED_MODEL = null;

function processModelChange(selectObject) {

	if (PREVIOUS_SELECTED_MODEL) {
		PREVIOUS_SELECTED_MODEL.unsetClassValue("selected");
	}

	if (selectObject.selectedIndex != 0) {
		chosenModel = IBDOM.IBElement.getAugmentedElement(selectObject.options[selectObject.selectedIndex]);
		chosenModel.setClassValue("selected");
		PREVIOUS_SELECTED_MODEL = chosenModel;
		chosenModelValue = chosenModel.value;
		if (chosenModelValue) {
			//model is a global variable defined in the jsp
			model = chosenModelValue;
		}//model value is not null or empty
	}//if valid model was picked
}//processModelChange

/* end used cars stuff */

/* Begin Form Validation Stuff */
//The function below is very basic. I will revisit and make it better...
		function validateForm(theForm) {
			
			if (theForm.phone) {
				theForm.phone.value = stripPhone(theForm.phone.value);
			}
			if (theForm.altphone && !(theForm.altphone.value == "" || theForm.altphone.value == null)) {
				theForm.altphone.value = stripPhone(theForm.altphone.value);
			}
			
			var msg = "";
			if (theForm.firstName) {
				msg += checkFirstName(theForm.firstName.value);
			}
			if (theForm.lastName) {
				msg += checkLastName(theForm.lastName.value);
			}

			if (theForm.firstname && !theForm.firstName) {
				msg += checkFirstName(theForm.firstname.value);
			}
			if (theForm.lastname && !theForm.lastName) {
				msg += checkLastName(theForm.lastname.value);
			}

			if (theForm.email) {
				msg += checkEmail(theForm.email.value);
			}
			if (theForm.phone) {
				msg += checkPhone(theForm.phone.value);
			}
			if (theForm.altphone && !(theForm.altphone.value == "" || theForm.altphone.value == null)) {
				msg += checkPhone(theForm.altphone.value);
			}
			if (theForm.email && theForm.email2) {
				msg += confirmEmail(theForm.email.value, theForm.email2.value);
			}
			
			if (msg != "") {	
				alert(msg);
			    return false;
			} else if (msg == "") {
				return true;
			}
		}//validateForm
		
		function checkEmail(email) {
			var error = "";
			if (!(/^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(email))) { 
				error = "Please enter a valid email address.\n";
			}
			return error;
		}
		
		function checkPhone(phone) {
			var error = "";
			var stripped = phone.replace(/[\(\)\.\-\ ]/g, '');
			
			//strip out acceptable non-numeric characters
			if (isNaN(stripped)) {
			   error = "The phone number contains illegal characters.";
			}
			
			if (!(stripped.length == 10)) {
				error = "Phone number should be ten digits. Make sure you included an area code.\n";
			}
			
			return error;
		}
		
		function confirmEmail(email,email2) {
			var error = "";
			if(email != email2) {
				error = "Email addresses do not match.\n";
			}
			
			return error;
			
		}
		
		function checkFirstName(name) {
			var error = "";
			name = getStrippedWhite(name);
			if(name == "") {
				error = "Please enter a first name.\n";
			}
			
			return error;
			
		}
		
		function checkLastName(name) {
			var error = "";
			name = getStrippedWhite(name);
			if(name == "") {
				error = "Please enter a last name.\n";
			}
			
			return error;
			
		}
		
		function stripPhone(phone) {
			var strippedphone = phone.replace(/[\(\)\.\-\ ]/g, '');
			return strippedphone;
		}
		
/* End Form Validation Stuff */

function showInterstitialScreen() {
	stit = $e("interstitial");
	if (stit) {
		scrollX = getScrollX();
		scrollY = getScrollY();
		w = getWindowWidth();
		h = getWindowHeight();
		stit.style.width = (w + "px");
		stit.style.height = (h + "px");
		stit.style.top = (scrollX + "px");
		stit.style.left = (scrollY + "px");
		stit.show("block");
	}
}//showInterstitialScreen

function hideInterstitialScreen() {
	if ($e("interstitial")) {
		$e("interstitial").hide();
	}
}//hideInterstitialScreen

function imgProcessor(dO) {
	this.src = dO.imgLocation;
}//imgProcessor

function processImageRange(startIndex, endIndex, lister, collection, tagLine) {
	lister = IBDOM.IBElement.getAugmentedElement(lister);
	if (collection[startIndex]) {
		lister.removeAllChildren();
		for (imgIndex=startIndex; (imgIndex <= endIndex) && (collection && (img = collection[imgIndex]));imgIndex++) {
			thumbLocation = IBDOM.Utils.getString([AKAMAI_RESIZE_PREFIX + "width=60&thumb=true&imageNum=",img.sequenceNumber,"&listingId=",img.usedListing.listingId]);
			fullImageLocation = IBDOM.Utils.getString([AKAMAI_RESIZE_PREFIX + "width=" + IMAGEVIEWER.big_image_width + "&imageNum=",img.sequenceNumber,"&listingId=",img.usedListing.listingId]);
			imageObject = {};
			imageObject["altData"] = tagLine + " / Image: " + (imgIndex + 1);
			imageObject["imgLocation"] = thumbLocation;
			imageObject["imgClickUrl"] = fullImageLocation;
			lister.appendChild($t("previewImage","img").setDataProcessor(imgProcessor).populate(imageObject));
			addImageToCache(fullImageLocation);
		}//loop thru listing images
		setTimeout (
			function() {
				processCachedImages();
			}
			,
			IMAGEVIEWER.preload_big_images_wait
		);
	}//if collection[startindex
	IMAGEVIEWER.current_start = startIndex;
}//processImageRange 

IMAGEVIEWER = {
	images_per_batch: 10,
	current_start: 0,
	current_viewer_listing: null,
	current_lister: null,
	current_tag_line: null,
	current_page: 0,
	big_image_width: 300,
	preload_big_images_wait: 5000
}

function showImageInViewer(imgLoc,viewerContextNode) {
	if (imgLoc) {
		viewerContextNode.gFEBCN("viewerImage","img").src = imgLoc;
	}
}//showImageInViewer

function imageViewerPreviousBatch() {
	start = IMAGEVIEWER.current_start - IMAGEVIEWER.images_per_batch;
	end = start + IMAGEVIEWER.images_per_batch - 1;
	if (start < 0) {
		start = 0;
		end = IMAGEVIEWER.images_per_batch - 1;
	}
	processI0mageRange(start, end, IMAGEVIEWER.current_lister, IMAGEVIEWER.current_viewer_listing, IMAGEVIEWER.current_tag_line);
}//imageViewerPreviousBatch

function imageViewerNextBatch() {
	start = IMAGEVIEWER.current_start + IMAGEVIEWER.images_per_batch;
	end = start + IMAGEVIEWER.images_per_batch - 1;
	if (end > (IMAGEVIEWER.current_viewer_listing.length * 2)) {
		start = 0;
		end = IMAGEVIEWER.images_per_batch - 1;
	}
	processImageRange(start, end, IMAGEVIEWER.current_lister, IMAGEVIEWER.current_viewer_listing, IMAGEVIEWER.current_tag_line);
}//imageViewerNextBatch


function getFeedbackPopup() {
		POPUP_OFFSET_TOP = 35;
		POPUP_OFFSET_LEFT = 165;
		popup = $e("feedbackPopup");
		
		scrollX = getScrollX();
		scrollY = getScrollY();
		popup.style.left = IBDOM.Utils.getString([(scrollX + POPUP_OFFSET_LEFT),"px"]);
		popup.style.top = IBDOM.Utils.getString([(scrollY + POPUP_OFFSET_TOP),"px"]);
		popup.show("block");
		
	}//getFeedbackPopup

	function closeFeedbackPopup() {
		$e("feedbackPopup").hide();
	}//closeFeedbackPopup
	
	function submitFeedback(form) {
		comments = form.comments.value;
		theRating = null;
		for (i=0;!theRating && (i<form.rating.length);i++) {
			if (form.rating[i].checked) {
					theRating = form.rating[i].value;
				}
		}
		
		email = form.email.value;
		msg = checkEmail(email);
		
		if (!theRating) {
			alert("Please pick a rating");
			if (form.rating.focus) {
				form.rating.focus();
			}
		} else {
			feedbackManager.submitFeedback(theRating, comments, email, endFeedback);
		}
		return false;
	}//submitFeedback
	
	function endFeedback(didItWork) {
		if(didItWork) {
			$e("feedbackContent").hide();
			$e("feedbackThanks").show("block");
		}
	}

function replaceBadImages() {
	var badLoad = new Image();
	badLoad.src = imageUrlPrefix + '/usedcars/images/no_photo_temp.png';
	
	for(var i=0;i<document.images.length;i++){
		if(!document.images[i].complete || document.images[i].onerror==true){
			document.images[i].src = badLoad.src;
			var imgClassName = document.images[i].className;
			if (imgClassName=='dealerImg' || imgClassName=='contactLogo') { 
				document.images[i].width='88';
			}
		}
	}
}