var intAjaxActionsPending = 0;

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

window.onbeforeunload = function (e) {
	if ( intAjaxActionsPending > 0 ) return 'WARNING: Some of your actions may have failed. \n\nIF YOU ARE RELOADING, continue. \n\nIF YOU ARE LEAVING, you should remain on this page and then reload to confirm all changes have completed.';
};

function e() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

function t(tag) { return document.getElementsByTagName(tag); }
function n(name) { return document.getElementsByName(name); }

$e = e; // depricated
$t = t; //depricated

function hardSetStyle(selectors, stylename) {
	// take the calculated css style and set it as the style of the element. 
	// Useful for preserving styles when copying innerHTML. 
	// Can use multiple selectors and multiple stylenames	
	var aSel = selectors.split(','), aName = stylename.split(',');
	for (var i=0, il=aSel.length; i<il; i++)
		for (var j=0, jl=aName.length; j<jl; j++)
			$(aSel[i]).css(aName[j], $(aSel[i]).css(aName[j]));
}

function toggle(el) {
	if ( el.style.display != 'none' ) hide(el);
	else unhide(el);
}
//function $hide(id) { return hide(e(id)); } // depricated
function hide(obj) { obj.style.display = 'none'; }
function unhide(obj) { obj.style.display = ''; }

function getAncestorByTagName(el, tag) {
	if (el.parentNode) {
		if (el.parentNode.tagName.toLowerCase() == tag.toLowerCase()) return el.parentNode;
		else return getAncestorByTagName(el.parentNode, tag);
	}
}
function getAncestorOrSelfByTagName(el, tag) {
	if (el.tagName.toLowerCase() == tag.toLowerCase()) return el;
	else return getAncestorByTagName(el, tag);
}
function getDescendantsByName(prnt, name, aSiblings) {
	if (!aSiblings) var aSiblings = []; 
	if ( prnt.childNodes.length > 0 ) {
		var children = prnt.childNodes;
		for (var i = 0; i < children.length; i++) {
			if (children[i].name) {
				if ( children[i].name.toLowerCase() == name.toLowerCase() ) {
					aSiblings.push(children[i]);
				}
			}
			if ( children[i].childNodes.length > 0 ) {
				getDescendantsByName(children[i], name, aSiblings);
			}
		}
	}
	return aSiblings;
}
function nextSib(elem) { // cross browser friendly way to get nextSibling
	do {
		elem = elem.nextSibling;
	} while (elem && elem.nodeType != 1);
	return elem;                
}
function prevSib(elem) { // cross browser friendly way to get previousSibling
	do {
		elem = elem.previousSibling;
	} while (elem && elem.nodeType != 1);
	return elem;
}
function clickPrevCB(elem) {
	do {
		elem = elem.previousSibling;
	} while (elem && elem.nodeType != 1 && elem.tagName != "INPUT");
	elem.click();
}
function clickPrevRB(elem) {
	do {
		elem = elem.previousSibling;
	} while (elem && elem.nodeType != 1 && elem.tagName != "RADIO");
	elem.click();
}

function getRadioValue(radioObj) {
	for (var i = 0; i < radioObj.length; i++) {
		if (radioObj[i].checked) return radioObj[i].value;
	}
}
function setRadioValue(radioObj, newValue) {
	for (var i = 0; i < radioObj.length; i++) {
		if (radioObj[i].value == newValue.toString()) radioObj[i].checked = true;
		else radioObj[i].checked = false;
	}
}

function setActionLinkCursors() {
	var els = t("A");
	for (var i=0, il=els.length; i<il; i++) 
		if ( els[i].onclick && ! els[i].href ) 
			els[i].style.cursor = "pointer";
}

function setTipLinkClass() {
	var els = t('A');
	for (var i=0, il=els.length; i<il; i++) 
		if ( els[i].title && ! els[i].onclick && ! els[i].href ) {
			if ( els[i].className ) 
				els[i].className += ' tip';
			else 
				els[i].className = 'tip';
		}		
}
setTipLinkCursors = setTipLinkClass;

function setTitleByName(name, title) {
	if (! parent) parent = document;
	var els = document.getElementsByName(name);
	for (var i=0, il=els.length; i<il; i++) els[i].title = title;	
}
function setTitleByClassName(className, title, parent) {
	if (! parent) parent = document;
	var els = getElementsByClassName(className, null, parent);
	for (var i=0, il=els.length; i<il; i++) els[i].title = title;	
}

Array.prototype.map = function(f) {
	var returnArray=[];
	for (i=0; i<this.length; i++) {
		returnArray.push(f(this[i]));
	}
	return returnArray;
}

function getOuterHTML(object) {
	var element;
	if (!object) return null;
	element = document.createElement("div");
	element.appendChild(object.cloneNode(true));
	return element.innerHTML;
}
function getInnerText(obj) {
	if ( obj.textContent ) return obj.textContent;
	else return obj.innerText;
}
var getElementsByClassName = function (className, tag, elm){
	/*
		Developed by Robert Nyman, http://www.robertnyman.com
		Code/licensing: http://code.google.com/p/getelementsbyclassname/
	*/
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};
function getClassBgColor(el) {
	if (el.currentStyle)
		return el.currentStyle.backgroundColor;
	if (document.defaultView)
		return document.defaultView.getComputedStyle(el, '').getPropertyValue("background-color");
}
function formatNumberCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function writeFlash(boxName, link, width, height) {
	var html;
	html = '<object type="application/x-shockwave-flash" data="/' + boxName + '.swf" width="' + width + '" height="' + height + '">';
	html += '<param name="wmode" value="transparent">';
	html += '<param name="movie" value="/' + boxName + '.swf" />';
	if (link != null) {
		html += '<a href="' + link + '">';
	}
	html += '<img src="/' + boxName + '.jpg" width="' + width + '" height="' + height + '" alt="" />';
	if (link != null) {
		html += '</a>';
	}
	html += '</object>';
	document.write(html);
}

// *** would be best if window was not reloaded in cases where it is already open
function OpenClockWindow() {
	var strURL = 'http://time-in.info/country_Japan/';
	strURL = strURL.replace(/.info/, ".info/popup");
	TimeWin = 'toolbar=no,menubar=no,directories=0,formulabar=no,status=0,location=yes,resizable=no,scrollbars=no,copyhistory=0,'
		 + 'left=200,top=200,height=100,width=200';
	TimeWin = window.open(strURL, "ClockWindow", TimeWin);
	TimeWin.focus();
}

function qs(varname) {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for ( var i = 0; i < vars.length; i++ ) {
		var pair = vars[i].split('=');
		if ( pair[0] == varname ) return pair[1];
	}
	return '';
}

getQueryVariable = qs; // depricated

function qsAppend(strURL, qsname, qsvalue) {
   	if ( strURL.indexOf('?') == -1 ) return strURL + "?" + qsname + "=" + qsvalue; //x.asp?Name=Peter+Paul
   	else return strURL + "&" + qsname + "=" + qsvalue; //x.asp?a=b&Name=Peter+Paul		
}

AppendQS = qsAppend; //depricated

function qsReplace(qstring, varname, val) {
	var re = new RegExp("([?|&])" + varname + "=.*?(&|$)","i");
	if (qstring.match(re)) return qstring.replace(re, '$1' + varname + "=" + val + '$2');
	else return qsAppend(qstring, varname, val);
}

replaceQueryVariable = qsReplace;

function classSwp(objToChange, strNewClass) {
	objToChange.oldClass = objToChange.className;
	objToChange.className = strNewClass;
}

function classUnSwp(objToChange) {
	if ( objToChange.oldClass ) objToChange.className = objToChange.oldClass;
}

function Translation(VID) {
	url = "/cars/translation" + ".asp?VID=" + VID
	PopBox("TransWin", url, 470, 420);
}

function NewMessage(VID, UID, strOptions) {
	url = "/cars/messages" + ".asp?VID=" + VID + "&UID=" + UID;
	if (!(strOptions === undefined)) {
		url = url + "&options=" + strOptions;
		PopBox("MessageWin", url, 470, 300);
	} else {
		PopBox("MessageWin", url, 470, 500);
	}
}

function DelMessage(MID) {
	url = "/cars/messages" + ".asp?del=" + MID;
	PopBox("MessageWin", url, 470, 500);
}

function ChangeBid(VID, UID) {
	url = "/cars/messages" + ".asp?change=bid&VID=" + VID + "&UID=" + UID;
	PopBox("MessageWin", url, 470, 420);
}

function PopBox(WinName, url, MyWidth, MyHeight) {
	var MyXPos;
	var MyYPos;
	var WinOpts;
	var MyScroll;
	var objMake

	MyXPos =  0;
	MyYPos = 0;

	WinMods = 'toolbar=no,menubar=no,directories=0,formulabar=no,status=0,location=no,resizable=yes,scrollbars=yes,copyhistory=0,'
		+ 'left=' + MyXPos + ',top=' + MyYPos + ',height=' + MyHeight + ',width=' + MyWidth;
	WinObj = window.open(url, WinName, WinMods);	  
	WinObj.focus();
}

function loadImgs(intTimeout){
	imageLoaderEnd = new Date(new Date().setMinutes( (new Date()).getMinutes() + 5 ));
	setTimeout("imageLoader(" + intTimeout + ")", intTimeout);
}

// reason for this way of creating the date explained in notes: js, date, ref	
var imageLoaderEnd = new Date(new Date().setMinutes( (new Date()).getMinutes() + 5 ));

function imageLoader(intTimeout){
	var blnNeedReload = false;
	var img = 0;
	var tmpSrc;
	var now = new Date();
	while ( img < document.images.length ) { // for some reason a 'for' loop does not always work properly.  a bug in explorer I think.
		//alert(document.images[img].height);
		// document src check is to prevent loading hotlinked images
		if ( document.images[img].id == 'ld' && document.images[img].height <= 40 
		&& document.images[img].src != '' && ! document.images[img].src.match(/nihoncars.com\/[^\/]+[2,4]\//)  ) {
			blnNeedReload = true;
			tmpSrc = document.images[img].src;
			document.images[img].alt='';
			//alert(tmpSrc);
			 // if it is blank, it is like trying to load current page, which is not good.
			if ( tmpSrc.toLowerCase().indexOf('.png') > 0 )  {
				document.images[img].src = "/x.png"; // seems to make a differences in succesful reloading in FF3
				// png files don't seem to always reload as jpg does. force it.
				tmpSrc = replaceQueryVariable(tmpSrc, 't', now.getTime()); 
			} else if ( tmpSrc.toLowerCase().indexOf('.gif') > 0 ) {
				document.images[img].src = "/x.gif"; 
			} else {
				document.images[img].src = "/x.jpg"; 				
			}
			document.images[img].src = tmpSrc;
		}
		img++;
	}
	if (blnNeedReload && now < imageLoaderEnd) setTimeout("imageLoader(" + intTimeout + ")", intTimeout);
}

function showTab(tabID) {
	e(tabID).style.display = "block";
}
function hideTab(tabID) {
	e(tabID).style.display = "none";
}

function openTab(anchor){
	  var container = anchor.parentNode;
	  for(var x = 0; container.childNodes[x]; x++){
			 if(container.childNodes[x].nodeName == "A"){
					if(container.childNodes[x].name == anchor.name){
						   container.childNodes[x].className = "selected";
					} else {
						   container.childNodes[x].className = "";
					}
			 }
	  }
	  container = anchor.parentNode;
	  for(var x = 0; container.childNodes[x]; x++){
			 if(container.childNodes[x].nodeName == "DIV" && 
			 container.childNodes[x].id != "productTabs"){
					if(container.childNodes[x].id == anchor.name){
						   container.childNodes[x].style.display = "block";
					} else {
						   container.childNodes[x].style.display = "none";
					}
			 }
	  }
	  return false;
}


function UpdateSpan(strID, strNewText) {
	  // in IE this wold work, but not in Firefox:  e(strID).innerText = strNewText;
	  // warning. in order to replace the child node, one must exist. be wary of a completely empty span
	  var newTextNode = document.createTextNode(strNewText.toString());
	  e(strID).replaceChild(newTextNode, e(strID).firstChild);
}

function isNumeric(val){return(parseFloat(val,10)==(val*1));}

function isNumericOrEmpty(sNumber) {
	  if ( sNumber == '' ) return true;
	  else return isNumeric(sNumber);
}

function isIntOrEmpty(sNumber) {
	  if ( sNumber == '' ) return true;
	  else return isInteger(sNumber);
}

function isInteger(sNumber) {
	  inputStr = Trim(sNumber.toString())
	  if ( inputStr.length > 0 ) {
			 for (var i = 0; i < inputStr.length; i++) {
					var oneChar = inputStr.charAt(i)                     
					if ( oneChar != "," && (oneChar < "0" || oneChar > "9") ) {
						   return false;
					}
			 }
	  } else { // empty string is not an integer
			 return false;
	  }
	  return true;
}

function LTrim(str){
	  if (str==null){return null;}
	  for(var i=0;str.charAt(i)==" ";i++);
	  return str.substring(i,str.length);
}
function RTrim(str){
	  if (str==null){return null;}
	  for(var i=str.length-1;str.charAt(i)==" ";i--);
	  return str.substring(0,i+1);
}
function Trim(str){return LTrim(RTrim(str));}
function LTrimAll(str) {
	  if (str==null){return str;}
	  for (var i=0; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i++);
	  return str.substring(i,str.length);
}
function RTrimAll(str) {
	  if (str==null){return str;}
	  for (var i=str.length-1; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\t"; i--);
	  return str.substring(0,i+1);
}
function TrimAll(str) {
	  return LTrimAll(RTrimAll(str));
}

function insertAtCursor(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if ( myField.selectionStart || myField.selectionStart == '0' ) {
		var startPos = myField.selectionStart;
		//alert(startPos);
		var endPos = myField.selectionEnd;
		//alert(endPos);
		myField.value = myField.value.substring(0, startPos)
			+ myValue
			+ myField.value.substring(endPos, myField.value.length);
		myField.selectionStart = startPos + myValue.length;
		myField.selectionEnd = myField.selectionStart;
	} else {
		myField.value += myValue;
	}
}
	
function Popup(strURL, intHeight, intWidth) {
	  var MyXPos;
	  var MyYPos;
	  var WinOpts;
	  var MyScroll;
	  var objMake
	  MyScroll = 'no' ;
	  MyXPos =  0;
	  MyYPos = 0;
					
	  WinPopup = 'toolbar=no,menubar=no,directories=0,formulabar=no,status=0,location=no,resizable=yes,scrollbars=yes,copyhistory=0,'
			 + 'left=' + MyXPos + ',top=' + MyYPos + ',height=' + intHeight + ',width=' + intWidth;
	  
	  WinPopup = window.open(strURL, "CtrlWindow", WinPopup);
	  
	  WinPopup.focus();
}


function imgg(obj){obj.src=obj.name;}

function fstld() {
	  img = 0;
	  while ( img < document.images.length ) {
			 if (document.images[img].id.length > 15) {
					document.images[img].src = decd(document.images[img].id);
			 }
			 img++;
	  }
}

function slwld() {
	  img=0
	  while ( img < document.images.length ) {
			 if (document.images[img].id.length > 15) {
					document.images[img].src = document.images[img].name;
					document.images[img].id = "x";
			 }
			 img++;
	  }
}

function decd(input) {
	  var char_set = '$%^NOZ1&PQR(./~`"CDEFG!@STUVWghij}:<pH=B*#8uvwx>?[]\',ef34590qrklmnoIJ)_+{st67 abcdAyzKLM2Y';
	  var output = "";
	  var char_code;

	  var algorithm = 5
	  algorithm++;

	  var alpha_length = char_set.length - algorithm;
	  var space;

	  for (loop=0; loop<input.length; loop++) {
			 if (char_set.indexOf(input.charAt(loop)) == -1) {
					alert("Program Error: Unknown Character!");
			 }

			 char_code = char_set.indexOf(input.charAt(loop));

			 if (char_code - algorithm < 0)
			 {
					space = algorithm - char_code;
					char_code = char_set.length - space;
			 } else {
					char_code -= algorithm;
			 }

			 output += char_set.charAt(char_code);
	  }
	  return output;
}

function checkByID(strID) {
	e(strID).checked = true;
}

function clickByID(strID) {
	e(strID).focus();
	e(strID).click();
}

function clickByName(strID) {
	document.getElementsByName(strID)[0].click();
}

function toggleCheck(field) {
	if ( field[0].checked ) {
		unCheckAll(field);
	} else {
		checkAll(field);
	}
}

function checkAll(field) {
	  for (i = 0; i < field.length; i++)
			 field[i].checked = true ;
}

function unCheckAll(field) {
	  for (i = 0; i < field.length; i++)
			 field[i].checked = false ;
}

function SendMailCheck(emailStr) {
	if ( validateEmail(emailStr) ) {
		return true;
	} else {
		if ( ! confirm("The e-mail address '" + emailStr + "' does not seem to be valid. Please check it carefully.  Do you want to change it?  Press OK to edit.") ) {
			return true;
		} else {
			return false;
		}
	}
}

function validateEmail(str) {
    var s = str;
    var pos = s.indexOf(',');
    while(pos < s.length){
        if (pos==-1) {
            if(!validateOne(s)){
                return false;
            }
            return true;
        }
        else{
            if(!validateOne(s.substring(0, pos))){
                return false;
            }
            s = s.substring(pos+1, s.length);
            pos = s.indexOf(',');
        }
    }
    return true;
}

function validateOne(str) {
    if (/^\s*\w+([\+\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+\s*$/.test(str)){
        return (true)
    }

    if (/^([^<>])*\<\s*\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+\s*\>$/.test(str)){
        return (true)
    }
    return false;
}

function remove_links(objDom) {
	if ( objDom ) {
		var daList = objDom.getElementsByTagName("A");
		if ( daList ) {
			for (var i = 0; i < daList.length; i++) {
				var objParent = daList[i].parentNode;
				var children = daList[i].childNodes;
				for(var j=0; j<children.length; j++) {
				  objParent.insertBefore(children[j], daList[i]);
				}
			}
			while(daList.length > 0) {
				daList[0].parentNode.removeChild(daList[0]);
			}
		}
	}
}

function removeCol(node, intCol) {
	var k, l, rows = node.getElementsByTagName("TR");
	var cols;
	for(k=0; k<rows.length; ++k) {
		cols = rows[k].getElementsByTagName("TD");
		if (cols.length > 5) {  // hack to prevent deletion of columns of mailout view
			for(l=0; l<cols.length; ++l) {
				if ( intCol == l || intCol == -1 ) {
					cols[l].parentNode.removeChild(cols[l]);
				}
			}
		}
	}
}

function removeElementsByTagName(node, strTagName, excludeByClass) {
	var k, l, tags = node.getElementsByTagName(strTagName);
	if ( typeof excludeByClass == 'undefined' ) excludeByClass = '';
	excludeByClass = excludeByClass.split(',');
	for( k=0; k<tags.length; ) {  // ++k is removed because removing the tag increments causes each next node to become node 0
		if ( ( strTagName.toLowerCase() != "img" || tags[k].height <= 40 ) && $.inArray(tags[k].className, excludeByClass) == -1 ) { // this prevents thumnails from being removed, but permits icons to be removed. 
			tags[k].parentNode.removeChild(tags[k]);
		} else {
			k++;
		}
	}
}
function removeElementsByClass(node, strClassName) {
	var els = getElementsByClassName(strClassName, null, node); 
	for (var i=0, il=els.length; i<il; i++) {
		els[i].parentNode.removeChild(els[i]);
	}
}


/* holds reference to popup div */
var divPicturePopup = null;

/* how much space to leave between link and img when flipping */
var flipOverBuffer = 10;

var blnAllowHideImage = true; // used to stop event fired by clicking on link that opens the image from immediately closing it

function findScrollingOffset() {
	var x,y;
	if (self.pageYOffset) // all except Explorer
	{
		x = self.pageXOffset;
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	return [x, y];
}

function findWindowDimensions() {
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [x, y];
}


/* cross browser compatible function which finds x and y 
   coordinates of obj HTML/DOM node */
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


function toggleTip(tipID, tipName) {
	var divPopup = e(tipID + "_tip");
	if (divPopup) {
		closeTip(tipID);
	} else {
		showTip(tipID, tipName, arguments[2], arguments[3], arguments[4], arguments[5]);
	}
}

function showTip(tipID, tipName, xpos, ypos, width, height) {
	var position, elementForDivCoordinates = e(tipID);
	if ( elementForDivCoordinates ) position = findPos(elementForDivCoordinates);
	if (! xpos) xpos = position[0] + 20;
	if (! ypos) ypos = position[1] + 20;
	if (! width) width = 400;
	if (! height) height = 250;
	var divPopup = PopupDiv('/cars/?frame=y&page=' + tipName, xpos, ypos, width, height)
	divPopup.id = tipID + "_tip";
	divPopup.style.background = "#ffffff"; // this is necessary !
	adjustDivLocation(divPopup);
}

function closeTip(tipID) {
	removeDiv(e(tipID + "_tip"));
}

var divModalPopup;
var divModalBarrier;
function removePopupDivModal() {
	if (divModalPopup) document.body.removeChild(divModalPopup);
	if (divModalBarrier) document.body.removeChild(divModalBarrier);
	divModalPopup = null;
	divModalBarrier = null;
}
function popupDivModal(strURL, x, y, w, h) {
	removePopupDivModal();

	var dsh=document.documentElement.scrollHeight;  
	var dch=document.documentElement.clientHeight;  
	var dsw=document.documentElement.scrollWidth;  
	var dcw=document.documentElement.clientWidth;  
	var bdh=(dsh>dch)?dsh:dch;  
	var bdw=(dsw>dcw)?dsw:dcw;
	
	divModalBarrier = document.createElement('DIV');
	divModalBarrier.className = "modalbarrier";
	divModalBarrier.style.height = bdh+'px';  
	divModalBarrier.style.width = bdw+'px';    
		
	divModalPopup = document.createElement('DIV');
	divModalPopup.style.position = "absolute";
	divModalPopup.style.top = y + 'px';
	divModalPopup.style.left = x + 'px';

	var divModalShadow = document.createElement('DIV');
	divModalShadow.className = "modalshadow";
	divModalShadow.style.position = "absolute";
	divModalShadow.style.top = 8 + 'px';
	divModalShadow.style.left = 8 + 'px';
	divModalShadow.style.width = w + 'px';
	divModalShadow.style.height = h + 'px';
	
	var iframe = document.createElement('IFRAME');
	iframe.className = "modaliframe";
	iframe.style.position = "absolute";
	iframe.width = w;
	iframe.height = h;
	iframe.src = strURL;
	//iframe.className = 'nobdr';

	divModalPopup.appendChild(divModalShadow);
	divModalPopup.appendChild(iframe);
	body = t('body')[0];
	body.appendChild(divModalBarrier);
	body.appendChild(divModalPopup);
	
	return divModalPopup;
}

function PopupDiv(strURL, x, y, w, h) {
	var divPopup = document.createElement('DIV');
	divPopup.style.position = "absolute";
	divPopup.style.border = "2px solid #000000"
	divPopup.style.top = y + 'px';
	divPopup.style.left = x + 'px';
	
	var iframe = document.createElement('IFRAME');
	iframe.src = strURL;
	iframe.width = w;
	iframe.height = h;
	iframe.frameborder = 0;
	iframe.id = 'rand' + Math.floor(Math.random()*1000000); // fix odd caching bug in chrome that was disregarding the .src if user hit back button
	//iframe.className = 'nobdr';

	divPopup.appendChild(iframe);
	body = t('body')[0];
	body.appendChild(divPopup);               
	return divPopup;
}

function adjustDivLocation(divObject) { // should stay in common.js
	if (divObject) {
		/* must store this values for mozilla */
		var divWidth = divObject.offsetWidth;
		var divHeight = divObject.offsetHeight;
		var position = findPos(divObject);
		var left = position[0];
		var top = position[1];
		var finalPosTop = top;
		var finalPosLeft = left;
		var scrolling = findScrollingOffset();
		var windowsize = findWindowDimensions();

		var hOver = top + divHeight - scrolling[1] - windowsize[1];
		if (hOver > 0) finalPosTop = top - hOver; // if below bottom move up
		if (finalPosTop < scrolling[1]) finalPosTop = scrolling[1]; //if above top move down
		
		hOver = finalPosTop + divHeight - scrolling[1] - windowsize[1]; // new hover using finalPosTop
		if (hOver > 0) { // can not see bottom of the div
			var imgs = divObject.getElementsByTagName("img")
			if (imgs) {
				if ( imgs.length == 1 ) { // if div is simple container for 1 image. *** probably a better way to do this.
					// shrink image height to fit.  do height first so that left adjustments below use the newly modified width (adjusted automatically to kep aspect ratio)
					var img = imgs[0];
					img.style.height = (divHeight - hOver - 6 /*space for border*/) + "px"; // shrink height by the amount cut off on top
					divWidth = divObject.offsetWidth; // reset width after it was adjusted to keep aspect ration
				}
			}
		}

		/* if over right window edge, find if more of image is visible by showing the popup to the left or right */
		var wOverRight = left + divWidth - scrolling[0] - windowsize[0]; // amount unshown if to the right
		var wOverLeft = -1 * ( position[0] - flipOverBuffer - divWidth ) ; // amount unshown if to the left		
		if (wOverRight > wOverLeft){  // if amount cut off on when image is shown to the right is more than it would be cut off if picture was on the left, show image to the left
			finalPosLeft = -1 * wOverLeft;
		}
		/* if before left window edge, flip to the right side of link */
		var wUnder = left - scrolling[0];
		if (wUnder < 0){
			finalPosLeft = position[0] + flipOverBuffer + divWidth;
		}
		divObject.style.top = finalPosTop + 'px';
		divObject.style.left = finalPosLeft + 'px';	
	}
}

function removeDiv(divObject) {
	var parent = divObject.parentNode;
	if(parent){
		parent.removeChild(divObject);
	}
}

function showTipTip() {
	var divPopup = PopupDiv('/cars/?frame=y&page=tip_tip.html', 25, 25, 400, 250);
	divPopup.id = "tip_tip";
	divPopup.style.background = "#ffffff"; // this is necessary !
}

function createNewSubmitForm(action) {
	var submitForm = document.createElement("FORM");
	document.body.appendChild(submitForm);
	submitForm.action = action;
	submitForm.method = "POST";
	return submitForm;
}
function createNewFormElement(inputForm, elementName, elementValue) {
	var newElement = document.createElement("INPUT");
	newElement.type = "hidden";
	newElement.name = elementName;
	newElement.value = elementValue;
	inputForm.appendChild(newElement);
	return newElement;
}
function mouseX(evt) {
	if (evt.pageX) return evt.pageX;
	else if (evt.clientX)
	   return evt.clientX + (document.documentElement.scrollLeft ?
	   document.documentElement.scrollLeft :
	   document.body.scrollLeft);
	else return null;
}
function mouseY(evt) {
	if (evt.pageY) return evt.pageY;
	else if (evt.clientY)
	   return evt.clientY + (document.documentElement.scrollTop ?
	   document.documentElement.scrollTop :
	   document.body.scrollTop);
	else return null;
}
function removeSelection () {
	if (window.getSelection) {        // Firefox, Opera, Safari
		var selection = window.getSelection ();                                        
		selection.removeAllRanges ();
	}
	else {
		if (document.selection.createRange) {        // Internet Explorer
			var range = document.selection.createRange ();
			document.selection.empty ();
		}
	}
}
function stopEventBubble(evt) {
	evt.cancelBubble = true;
	if (evt.stopPropagation) evt.stopPropagation();
}
function eventTarget(evt) {
	var targ;
	if (evt.target) targ = evt.target;
	else if (evt.srcElement) targ = evt.srcElement;
	return targ;
}
function removeAllEventHandlers(obj) {
	obj.onmouseover = null;
	obj.onmouseout = null;
	obj.oncontextmenu = null;
	obj.onclick = null;
	obj.ondblclick = null;
}
function replaceAllEventHandlers(strHTML) {
	var strTemp = strHTML;
	strTemp = strTemp.replace(/onmouseover="[^"]*"/gi, "");
	strTemp = strTemp.replace(/onmouseout="[^"]*"/gi, "");
	strTemp = strTemp.replace(/oncontextmenu="[^"]*"/gi, "");
	strTemp = strTemp.replace(/onclick="[^"]*"/gi, "");
	strTemp = strTemp.replace(/ondblclick="[^"]*"/gi, "");
	return strTemp;
}

// ###  HOT KEYS  ###

var blnIgnoreHotKeys = false;
var blnIgnoreRKey = true;
var sto = setTimeout("blnIgnoreRKey = false", 2000);
var lastCharKey = '';
var blnWarnOfChange = false;

function pageKeyDown(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	if (keycode == 17) {
		blnIgnoreHotKeys = true;
		var t=setTimeout("blnIgnoreHotKeys = false", 3000);
	}
}

function pageKeyUp(e) { // assigned to document in hotkeys.asp
	blnWarnOfChange = false;
	
	if (blnIgnoreHotKeys == true) return(true);

	var code, thename, thetype, thekey, character, strLoc = '', strAlert = '';
	var ctrlPressed = 0, altPressed = 0, shiftPressed = 0, isSelection  = 0;
	
	if (!e) var e = window.event;

	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	
	if (targ.nodeType == 3)	targ = targ.parentNode;
	
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;

	character = String.fromCharCode(code);
	thename = targ.nodeName;
	thetype = targ.type;
	shiftPressed = e.shiftKey;
	altPressed = e.altKey;
	ctrlPressed = e.ctrlKey;

	var lastCharKeyLocl = lastCharKey;
	lastCharKey = character;
	
	if ( hotkeyHitSetting == 1 ) lastCharKeyLocl = character; // ignores all requirements for double hit below.  hotkeyHitSetting set in hotkeys.asp
	else setTimeout("lastCharKey = ''", 1200); // clear last key aver 1.2 seconds. forces a quick double-hit.

	// Check if there is some text selected (mainly for calculator exclusion)
	if ( document.getSelection ) { 
		var str = document.getSelection();
	} else if ( document.selection && document.selection.createRange ) {
		var range = document.selection.createRange();
		var str = range.text;
	} else {
		var str = '';
	}
	if ( str.length > 0 ) isSelection = 1;
	else isSelection = 0;
	
	if ( 	(blnIgnoreHotKeys || shiftPressed || altPressed || ctrlPressed) ||
			(thename == 'SELECT' || thename == 'TEXTAREA') ||
			(thename == 'INPUT' && (thetype != 'button' && thetype != 'submit' && thetype != 'checkbox' && targ.id != 'abid')) ) {
		// ignore. ( do not ignore abid because it gets focus on page load. ignoring it would disable hotkeys until focus is lost. abid only accepts numeric chars anyway.)
	} else {
		// For all pages
		if (lastCharKeyLocl == character) {
			if (character == 'H') strLoc = '/cars/';
			if (character == 'A') strLoc = '/cars/search.asp';
			if (character == 'D') strLoc = '/cars/search_stock.asp';
			if (character == 'B') strLoc = '/cars/search_bids.asp';
			if (character == 'M') strLoc = '/cars/showcars.asp?stock=my&thmb=on';
			if (character == 'L') strLoc = '/cars/browselist.asp';
			if (character == 'F') strLoc = '/cars/favoriteslist.asp';
			if (character == 'R' && !blnIgnoreRKey) strLoc = '/cars/recent_searches.asp';
			if (character == 'C' && !isSelection && typeof CurrencyCalc == 'function') CurrencyCalc();
		}
		if ( code == 37 && ! (targ.id == 'abid' && targ.value != '')  ) {
			if ( typeof prevVidInList != 'undefined' && prevVidInList ) strLoc = prevVidInList;
			else if ( typeof nextVidInList != 'undefined' && nextVidInList ) strAlert = 'no previous vehicle';
		}
		if ( code == 39 && ! (targ.id == 'abid' && targ.value != '')  ) {
			if ( typeof nextVidInList != 'undefined' && nextVidInList ) strLoc = nextVidInList;
			else if ( typeof prevVidInList != 'undefined' && prevVidInList ) strAlert = 'no next vehicle';
		}
		
		if ( strLoc != '' ) document.location.href = strLoc;
		if ( strAlert != '' ) alert(strAlert);
		
		if ( lastCharKeyLocl == '' ) {
			if ( character == 'H' | character == 'A' | character == 'D' | character == 'B' | character == 'M' | character == 'R' | character == 'L' | character == 'F' | character == 'X' | character == 'U' | character == 'N' | character == 'S' | character == 'E' | character == 'C' | character == 'P' ) {
				blnWarnOfChange = true; // if this is first key hit recetly (1.2 second limit set above) and a second key is not hit within next 1.3 seconds, a warning is created
				setTimeout("if (blnWarnOfChange) alert('HOT KEYS HAVE CHANGED! \\n\\nTo use hot keys, hit the same key twice, quickly.')", 1300);
			}
		}
		
		hotKeyHandler(character, lastCharKeyLocl); // in hotkeys.asp
		
		// look for page-level functions
		if (typeof hotKeys == 'function') hotKeys(character, lastCharKeyLocl);
	}
}


function onWinBlur() { window.blnFocussed = false }
function onWinFocus() { window.blnFocussed = true }
if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onWinFocus;
    document.onfocusout = onWinBlur;
} else {
	window.onfocus = onWinFocus;
	window.onblur = onWinBlur;
}
//this sucks. forced by suckass chrome not firing onfocus when page loads.  means tabs loaded in background appear focussed until first focus/blur
if ( is_chrome ) window.blnFocussed = true; 
function bidnotices() {
	if ( window.blnFocussed ) {
		$.get('/cars/ajax.asp', {doact: 'bidnotices'}, function(data) {
			$('#bidnotices').remove();
			if ( data > 0 )
				$('body').append('<div id="bidnotices" style="position:absolute;top:0;right:0;padding:3px 6px 0 0"><a style="color:red; text-decoration:blink" href="/cars/bidnotices.asp"><b>' + data + ' new bids</b></a></div>');
		})
		setTimeout(bidnotices, 90*1000);
	} else {
		setTimeout(bidnotices, 4*1000);
	}
}

