
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 AppendQS(strURL, qsname, qsvalue) {
    	if (strURL.indexOf('?') == -1 )	 //If no querystring present
    		return strURL+"?"+qsname+"="+qsvalue; //x.asp?Name=Peter+Paul
    	else
    		return strURL+"&"+qsname+"="+qsvalue; //x.asp?a=b&Name=Peter+Paul		
}

function getQueryVariable(variable) {
	  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] == variable) {
					return pair[1];
			 }
	  } 
	  return "";
}
function replaceQueryVariable(a,k,v) {
	var re = new RegExp("([?|&])" + k + "=.*?(&|$)","i");
	// alert(a.match(re));
	if (a.match(re))
		return a.replace(re, '$1' + k + "=" + v + '$2');
	else
		return AppendQS(a, k, v);
}

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) {
	url = "/cars/messages" + ".asp?VID=" + VID + "&UID=" + UID;
	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){
	setTimeout("imageLoader(" + intTimeout + ")", intTimeout);
}
function imageLoader(intTimeout){
	// for some reason a 'for' loop does not always work properly.  a bug in explorer I think.
	var blnNeedReload = false;
	var img = 0;
	var tmpSrc;
	var now = new Date();
	while ( img < document.images.length ) {
		//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 != "" ) {
			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) setTimeout("imageLoader(" + intTimeout + ")", intTimeout);
}

function showTab(tabID) {
	document.getElementById(tabID).style.display = "block";
}
function hideTab(tabID) {
	document.getElementById(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:  document.getElementById(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());
	  document.getElementById(strID).replaceChild(newTextNode, document.getElementById(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, intWidth, intHeight) {
	  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=' + intWidth + ',width=' + intHeight;
	  
	  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 = dec(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 dec(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 clickByID(strID) {
	document.getElementById(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 removeNodesByTagName(node, strTagName) {
	var k, l, tags = node.getElementsByTagName(strTagName);
	for(k=0; k<tags.length; ) {  // ++k is removed because removing the tag increments causes each next node to become node 0
		if (tags[k].height <= 40 ) { // this prevents thumnails from being removed, but permits icons to be removed. 
			tags[k].parentNode.removeChild(tags[k]);
		} else {
			k++;
		}
	}
}



/* 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 adjustDivLocation(divObject) {
	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();

		/* if below bottom move up */
		var hOver = top + divHeight - scrolling[1] - windowsize[1];
		if(hOver > 0){
			finalPosTop = top - hOver;
		}
		/* 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 above top move down */
		var hUnder = top - scrolling[1];
		if(hUnder < 0){
			finalPosTop = top - hUnder;
		}
		/* if before left window edge, flip to the right side of link */
		var wUnder = left - scrolling[0];
		if(wUnder < 0){
			finalPosLeft = position[0] + flipOverBuffer + divObject.offsetWidth;
		}
		divObject.style.top = finalPosTop + 'px';
		divObject.style.left = finalPosLeft + 'px';	
	}
}

function adjustDivPicturePopup() {
	// in IE6, this was being called by onload of image in div, even though div was removed. 
	// since dive was removed, trying to read offsetWidth in adjustDivLocation was throwing error
	if ( divPicturePopup ) {
		if ( divPicturePopup.offsetWidth ) { 
			adjustDivLocation(divPicturePopup);
		}
	}
}

/* displays popup div with image */
var timerID = 0, gFilename, gLink, gIntButton;
function showImage(filename, link, intButton) {
	var intSecDelay
	if(typeof arguments[3] == "undefined") intSecDelay = 1000;
	else intSecDelay = arguments[3];
	
	gFilename = filename;
	gLink = link;
	gIntButton = intButton;
	timerID  = setTimeout("showImageTimer(gFilename, gLink, gIntButton);", intSecDelay);
}

function showImageTimer(filename, link, intButton) {
	/* holds coordinates relative to link's top left, 
		where popup's top left will be placed */
	var imgCoordsRelToLink = [10,20];
	/* border width for div containing image in pixels */
	var borderWidth = 3;
	/* border color in css notation */
	var borderColor = "#aaa";

	if ( intButton == 3 && blnAllowHideImage )  { // if we can hide, we can show
		blnAllowHideImage = false;
		
		/* if popup opened, close it first */
		if(divPicturePopup != null){
			hideImage();
		}
		
		/* create div element and set its position (absolute a must!)*/
		divPicturePopup = document.createElement('DIV');
		divPicturePopup.style.position = "absolute";
		var position = findPos(link);		
		/* top position of div containing image */
		var top = position[1] + imgCoordsRelToLink[1];
		/* left position of div containing image */
		var left = position[0] + imgCoordsRelToLink[0];
		
		divPicturePopup.style.border = borderWidth + "px solid " + borderColor;
		/* create image element and add it to div as child */
		var image = document.createElement('IMG');
		image.onload = adjustDivPicturePopup; /* CAUTION! onload event must be set before src */
		image.src = filename; //imgServer + filename;
		divPicturePopup.appendChild(image);
		
		/* add div element to body as child element */
		body = document.getElementsByTagName('body')[0];
		body.appendChild(divPicturePopup);
		
		divPicturePopup.style.top = top + 'px';
		divPicturePopup.style.left = left + 'px';		
	
		adjustDivLocation(divPicturePopup);

		setTimeout("blnAllowHideImage=true;", 100) //after 1/2 second, an event can hide the image. to avoid closing by event that opened it.
	} 		
}

function onclickEventHandler(e) {
	if ( blnAllowHideImage ) hideImage();
}

/* closes popup div with image */
function hideImage() {
	/* if popup time didn't complete before mouse out, then cancel the popup */
	if (timerID) {
		clearTimeout(timerID);
		timerID  = 0;
	}
	/* continue only if divPicturePopup is set */
	if ( divPicturePopup != null ) {
		removeDiv(divPicturePopup);
		/* set global variables and event handlers to  original state*/
		divPicturePopup = null;
	}
}

function toggleTip(tipID, tipName) {
	var divPopup = document.getElementById(tipID + "_tip");
	if (divPopup) {
		closeTip(tipID);
	} else {
		showTip(tipID, tipName, arguments[2], arguments[3], arguments[4], arguments[5]);
	}
}

function showTip(tipID, tipName) {
//	alert('/pages/' + tipName);
	var elementForDivCoordinates = document.getElementById(tipID);
	var position = findPos(elementForDivCoordinates);
	var xpos, ypos, width, height;
	if (typeof arguments[2] == 'undefined' ) xpos = position[0] + 20; else xpos = arguments[2];
	if (typeof arguments[3] == 'undefined' ) ypos = position[1] + 20; else ypos = arguments[3];
	if (typeof arguments[4] == 'undefined' ) width = 400; else width = arguments[4];
	if (typeof arguments[5] == 'undefined' ) height = 250; else height = arguments[5];	
	var divPopup = PopupDiv('/cars/?frame=y&page=' + tipName, xpos, ypos, width, height)
	divPopup.id = tipID + "_tip";
//	divPopup.style.background = "#ffffff";
	adjustDivLocation(divPopup);
}

function closeTip(tipID) {
	removeDiv(document.getElementById(tipID + "_tip"));
}

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.className = 'nobdr';

	divPopup.appendChild(iframe);
	body = document.getElementsByTagName('body')[0];
	body.appendChild(divPopup);               
	return divPopup;
}

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";
}


var divTagCar = null; //global

function closeDivTagCar() {
	// this is called by iframe indstead of calling closeDivTagCarNow directly.
	// I hope is this will defeat bug that I can't reproduce. 
	// I am guessing there was race condition caused by iframe calling fuction of its parent that tries to then removes the iframe that called it.
	// So function was trying to return to a page that no longer existed
	// I hope that by useing timeout, the timeout fired function is returning to the parent page, and there is no race condition
	setTimeout("closeDivTagCarNow()", 10); 
}

function closeDivTagCarNow() {
	if ( divTagCar ) {
		divTagCar.style.display = 'none';
		var theParent = divTagCar.parentNode;
		theParent.removeChild(divTagCar);
		divTagCar = null;
	}
}

function tagcar(vid, obj) {
	var MyXPos = 20;
	var MyYPos = 20;
	var WinOpts;
	var MyHeight = 150;
	var MyWidth = 250;
	var MyScroll = 'no';
	var objMake
	
	url = "/cars/tag.asp?vid=" + vid

	var imgCoordsRelToLink = [-20,-40];
	var position = findPos(obj);		
	MyYPos = position[1] + imgCoordsRelToLink[1];
	MyXPos = position[0] + imgCoordsRelToLink[0];

	if ( ! divTagCar ) {
		divTagCar = PopupDiv(url, MyXPos, MyYPos, MyWidth, MyHeight);
	}

	
}

