function getCookie(byname)
{
	// "byname" is the name of the cookie to retrieve

 	byname = byname + "=";
	nlen = byname.length;
	fromN = document.cookie.indexOf(byname) + 0;
	if (fromN != -1)
	{
		fromN += nlen;
		toN = document.cookie.indexOf(";",fromN) + 0;
		if (toN == -1)
		{
			toN = document.cookie.length;
		}
		return unescape(document.cookie.substring(fromN,toN));
	}
	return null;
}

function setCookie(name,value,time)
{
	// "name" is the name of the cookie to be stored
	// "value" is the value to store in the cookie
	// "time" is the date & time that the cookie expires

	exp = new Date();
	if ((name == null) || (value == null)) return false;
	if (time == null) time = 30*86400000;
	exp.setTime(exp.getTime() + time);
	document.cookie = escape(name) + "=" + escape(value) + "; " + "expires=" + exp.toGMTString() + "; path=/";
	return true;
}

function SaveContactInfo(ContactForm)
{
	var ContactInfo = "";
	ContactInfo = ContactForm.BillToName.value + "|" + ContactForm.BillToAddress1.value + "|" +
		ContactForm.BillToAddress2.value + "|" + ContactForm.BillToCity.value + "|" +
		ContactForm.BillToState.value + "|" + ContactForm.BillToZipcode.value + "|" +
		ContactForm.BillToPhone1.value + "|" + ContactForm.BillToPhone2.value + "|" +
		ContactForm.BillToEmail.value + "|" + ContactForm.VehicleMake.value + "|" +
		ContactForm.VehicleModel.value + "|" + ContactForm.VehicleYear.value;
	setCookie("ContactInfo",ContactInfo,null);
}

function CheckForm(FormToCheck)
{
	if (!CheckRequiredFields(FormToCheck))
		{ alert("Required fields must be completed before continuing!"); }
	else
		{ FormToCheck.submit(); }
}

function CheckRequiredFields(targetForm)
{
	for (x = 0; x < targetForm.elements.length; x++)
	{
		if (targetForm.elements[x].className == "RequiredInput")
		{
			if (targetForm.elements[x].value == "")
				{ return false; }
		}
	}
	return true;
}

function ValidateEmailFormat(emailToTest)
{
	var emailArray = new Array();
	var domainArray = new Array();

	if (emailToTest < "!")
		{ return true; }
	emailArray = emailToTest.split("@");
	if (emailArray.length != 2)
		{ return false; }
	if (emailArray[0].indexOf(".") == 0)
		{ return false; }
	domainArray = emailArray[1].split(".");
	if (domainArray.length < 2)
		{ return false; }
	for (x = 0; x < domainArray.length; x++)
	{
		if (domainArray[x].length < 2)
			{ return false; }
	}
	for (x = 0; x < emailArray[0].length; x++)
	{
		if (emailArray[0].charAt(x) > '~')
			{ return false; }
	}
	return true;
}

function AddItemToCart(PartID, ModelID, Qty)
{
	var ItemArray = new Array();
	var ItemCart = getCookie("ItemCart");

	if ((ItemCart == null) || (ItemCart < "!"))
		{ ItemCart = ""; }
	if (ItemCart > "")
		{ ItemArray = ItemCart.split("|"); }
	if ((isNaN(Qty)) || (Qty < "!"))
		{ Qty = 0; }

	partExists = -1;
	for (myIndex = 0; myIndex < ItemArray.length; myIndex++)
	{
		myPart = ItemArray[myIndex].split("-");
		if ((myPart[0] == PartID) && (myPart[1] == ModelID))
			{ partExists = myIndex; }
	}
	if (partExists > -1)
		{ document.getElementById("PartStatus").innerHTML = "That item is already in your cart."; }
	else
	{
		if (Qty < 1)
			{ Qty = 1; }
		if (ItemCart != "")
			{ ItemCart += "|"; }
		ItemCart += "" + PartID + "-" + ModelID + "-" + Qty;
		document.getElementById("PartStatus").innerHTML = "The item has been added to your cart.";
		document.getElementById("CartSize").innerHTML = "" + (ItemArray.length + 1);
	}
	setCookie("ItemCart", ItemCart, null);
}

function DeleteItemFromCart(CartIndex)
{

	if (!confirm("You are about to delete this item. Are you sure?"))
		{ return; }

	if (CartIndex < 0)
		{ return; }

	CartQtys[CartIndex] = 0;
	RebuildCart();
}

function ShowCartQty()
{
	var ItemCart = getCookie("ItemCart");
	var ItemArray = new Array();

	if ((ItemCart == null) || (ItemCart < "!"))
		{ ItemCart = ""; }
	if (ItemCart > "")
		{ ItemArray = ItemCart.split("|"); }
	document.getElementById("CartSize").innerHTML = ItemArray.length;
}

function ClearCart()
{
	var ItemArray = new Array();
	var ItemCart = ItemArray.join("|");
	
	setCookie("ItemCart", ItemCart, null);
	ShowCartQty();
}

function RebuildCart()
{
	var CartCookie = "";
	var RowClass = "";
	var CurrentPrice = 0.00;
	var TotalPrice = 0.00;

	for (var x = 0; x < CartPartIDs.length; x++)
	{
		if (CartQtys[x] < 1)
		{
			document.getElementById("CartRow" + x).style.display = "none";
			continue; 
		}

		if (CartCookie > "")
			{ CartCookie += "|"; }
		
		CartCookie += "" + CartPartIDs[x] + "-" + CartModelIDs[x] + "-" + CartQtys[x];
		CurrentPrice = CartPrices[x] * CartQtys[x];
		TotalPrice += CurrentPrice;
		document.getElementById("CartRow" + x).className = RowClass;
		document.getElementById("Qty" + x).innerHTML = CartQtys[x];
		document.getElementById("ExtPrice" + x).innerHTML = "$" + CurrentPrice.toFixed(2);
		if (RowClass == "")
			{ RowClass = "OddRowShader"; }
		else
			{ RowClass = ""; }
	}
	document.getElementById("GrandTotal").innerHTML = "$" + TotalPrice.toFixed(2);
	setCookie("ItemCart", CartCookie, null);
	ShowCartQty();
}

function UpdateQty()
{
	var Qty = document.getElementById("QtyForm").NewQty.value;
	var CartIndex = document.getElementById("QtyForm").CartIndex.value;

	if ((isNaN(Qty)) || (Qty < "!"))
	{
		alert("The quantity must be a number!");
		document.getElementById("QtyForm").NewQty.focus();
		document.getElementById("QtyForm").NewQty.select();
		return;
	}
	
	if (CartIndex < 0)
		{ return; }

	if (Qty < 1 && !confirm("You are about to delete this item. Are you sure?"))
		{ return; }

	CartQtys[CartIndex] = parseInt(Qty, 10);
	RebuildCart();
	CloseQtyPrompt();
}

function getAbsoluteTop(getObj)
{
	var myTop = getObj.offsetTop;
	var parentObj = getObj.offsetParent;
	while (parentObj != null)
	{
		myTop += parentObj.offsetTop;
		parentObj = parentObj.offsetParent;
	}
	return myTop;
}

function getAbsoluteLeft(getObj)
{
	var myLeft = getObj.offsetLeft;
	var parentObj = getObj.offsetParent;
	while (parentObj != null)
	{
		myLeft += parentObj.offsetLeft;
		parentObj = parentObj.offsetParent;
	}
	return myLeft;
}

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 ShowQtyPrompt(CartIndex)
{
	var promptObj = document.getElementById("qtyPopup");
	var callingObj = document.getElementById("QtyBttn" + CartIndex);

	promptObj.style.display = "block";
	promptObj.style.left = getAbsoluteLeft(callingObj) - promptObj.clientWidth - 4;
	promptObj.style.top = getAbsoluteTop(callingObj) - 4;
	document.getElementById("QtyForm").CartIndex.value = CartIndex;
	document.getElementById("QtyForm").NewQty.value =  CartQtys[CartIndex];
	document.getElementById("QtyForm").NewQty.focus();
	document.getElementById("QtyForm").NewQty.select();
}

function CloseQtyPrompt()
{
	document.getElementById('qtyPopup').style.display = 'none';
}

function ShowLargeImage(objImage, strImageUrl)
{
	var objLargeImage = document.getElementById("LargeImage");
	objLargeImage.style.width = "1px";
	objLargeImage.style.height = "1px";
	objLargeImage.style.zindex = "-1";
	objLargeImage.style.display = "block";

	var imageTop = getAbsoluteTop(objImage);
	var imageLeft = getAbsoluteLeft(objImage);
	var imageWidth = objImage.width;
	var imageHeight = objImage.height;
	var LargeImageTop = imageTop + (imageHeight / 2) - 36;
	
	if (LargeImageTop > (imageTop + 36))
		LargeImageTop = imageTop;

	objImage = document.getElementById("PartImageDetail");
	objLargeImage.style.top = LargeImageTop + "px";
	objLargeImage.style.left =  (imageLeft  - Math.floor(GetWindowWidth() * 2 / 3) - 42) + "px";
	objImage.src = "showimage.php?p=" + escape(strImageUrl) + "&w=" + Math.floor(GetWindowWidth() * 2 / 3) + "&h=" + (GetWindowHeight() - LargeImageTop - 14) + "&a=1";
}

function ResizeLargeImageWindow(objSrcImage)
{
	var objLargeImage = document.getElementById("LargeImage");
	var objImage = document.getElementById("PartImageDetail");
	var tmpPosition = getAbsoluteLeft(objLargeImage);
	var imageWidth = objImage.width;
	var imageHeight = objImage.height;
	
	objLargeImage.style.width = (GetWindowWidth() * 2 / 3 + 42) + "px";
	objLargeImage.style.height = (imageHeight + 12) + "px";
	document.getElementById("TopBorderImage").style.width = (imageWidth + 10) + "px";
	/* objLargeImage.style.left = (tmpPosition - imageWidth - 40) + "px"; */
	objLargeImage.style.zindex = "auto";
}

function ResizeThumb(myObj)
{
	var windowWidth = 100, windowHeight = 100;
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
  	}
	if( document.body && ( document.body.clientWidth || document.body.clientHeight ))
	{
		//IE 4 compatible
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
 	}
  	if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ))
    {
		//IE 6+ in 'standards compliant mode'
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	}

	//document.getElementById("ImageDiv").style.display = "block";
	ImageX = myObj.clientWidth;
	ImageY = myObj.clientHeight;
	scale = 1;
	while ((ImageX / scale) > windowWidth / 3)
		{ scale = scale + 1; }
	fitScale = scale;
	myObj.width = ImageX / scale;
	myObj.height = ImageY / scale;
}

function DynamicResizeThumb(myObj, maxWidth, maxHeight)
{
	var imageX, imageY, scaleX, scaleY;
	//var myObj = document.getElementById(objName);
	
	imageX = myObj.width;
	imageY = myObj.height;
	
	if (maxWidth > imageX)
		{ maxWidth = imageX };
	if (maxHeight > imageY)
		{ maxHeight = imageY };
	scaleX = imageX / maxWidth;
	scaleY = imageY / maxHeight;
	if (scaleX > scaleY)
	{
		myObj.style.height = Math.floor(imageY * maxWidth / imageX);
		myObj.style.width = maxWidth;
	}
	else if (scaleY > 1)
	{
		myObj.style.width = Math.floor(imageX * maxHeight / imageY);
		myObj.style.height = maxHeight;
	}
}

function GetWindowWidth()
{
	var windowWidth = 100;
	if (typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		windowWidth = window.innerWidth;
	}

	if (document.body && document.body.clientWidth)
	{
		//IE 4 compatible
		windowWidth = document.body.clientWidth;
 	}
 
  	if (document.documentElement && document.documentElement.clientWidth)
	{
		//IE 6+ in 'standards compliant mode'
		windowWidth = document.documentElement.clientWidth;
	}
	return windowWidth;
}

function GetWindowHeight()
{
	var windowHeight = 100;
	if (typeof( window.innerHeight ) == 'number' )
	{
		//Non-IE
		windowHeight = window.innerHeight;
	}

	if (document.body && document.body.clientHeight)
	{
		//IE 4 compatible
		windowHeight = document.body.clientHeight;
 	}
 
  	if (document.documentElement && document.documentElement.clientHeight)
	{
		//IE 6+ in 'standards compliant mode'
		windowHeight = document.documentElement.clientHeight;
	}
	return windowHeight;
}

function GetSizedThumb(myObj, strImageUrl)
{
	var windowWidth = 100, windowHeight = 100;

	ImageX = Math.floor(GetWindowWidth() / 4);

	if (strImageUrl > " ")
	{
		myObj.src = "showimage.php?p=" + escape(strImageUrl) + "&w=" + ImageX + "&s=1&a=1";
	}
}

function Checkout(CheckoutUrl)
{
	document.CartForm.ItemCart.value = getCookie("ItemCart");
	document.CartForm.submit();
}

function ShowAnnouncements(HomeUrl)
{
	document.getElementById("Black50").style.display = "block";
	document.getElementById("Announcements").style.display = "block";
	document.getElementById("AnnouncementsContent").innerHTML = "<div style=\"position: relative; top: 50%; margin-top: -0.5em; text-align: center\"><b>Loading...</b></div>";
	AjaxPageRequest(HomeUrl + "ajax_announcements.php", AjaxPageCallback);
}

function AjaxPageCallback(responseText)
{
	document.getElementById("AnnouncementsContent").innerHTML = responseText;
	document.getElementById("Black50").style.display = "block";
	document.getElementById("Announcements").style.display = "block";
	var parentHeight = document.getElementById("Announcements").clientHeight;
	document.getElementById("AnnouncementsContent").style.height = parentHeight - 29;
}

function AjaxPageRequest(url, callback)
{
	var http_request = false;

	if (window.XMLHttpRequest)
		http_request = new XMLHttpRequest();
	else if (window.ActiveXObject)
	{
		try
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (errA)
		{
			try
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (errB)
			{
			}
		}
	}
	if (!http_request)
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4)
		{
			callback(http_request.responseText);
		}
	}
	http_request.open('GET', url, true);
	http_request.send(null);
}

function HideElementDisplay(objName)
{
	document.getElementById(objName).style.display = 'none';
}

function ToggleElementDisplay(objName)
{
	objElement = document.getElementById(objName);
	
	if (objElement.style.display == 'none')
	{
		objElement.style.display = 'block';
	}
	else
	{
		objElement.style.display = 'none';
	}
}
	
function Browser()
{
	var ua, s, i;
	this.isIE = false;
	this.isNS = false;
	this.version = null;
	ua = navigator.userAgent;
	s = "MSIE";
	if ((i = ua.indexOf(s)) >= 0)
	{
		this.isIE = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
	s = "Netscape6/";
	if ((i = ua.indexOf(s)) >= 0)
	{
		this.isNS = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}

	// Treat any other "Gecko" browser as NS 6.1.
	s = "Gecko";
	if ((i = ua.indexOf(s)) >= 0)
	{
		this.isNS = true;
		this.version = 6.1;
		return;
	}
}

var browser = new Browser();

// Global object to hold drag information.
var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(evt, id)
{
	var el;
	var x, y;
	
	// If an element id was given, find it. Otherwise use the element being
	// clicked on.
	if (id)
	{
		dragObj.elNode = document.getElementById(id);
	}
	else
	{
		if (browser.isIE)
		{
			dragObj.elNode = evt.srcElement;
		}
		if (browser.isNS)
		{
			dragObj.elNode = evt.target;
		}

		// If this is a text node, use its parent element.
		if (dragObj.elNode.nodeType == 3)
		{
			dragObj.elNode = dragObj.elNode.parentNode;
		}
	}
	x = mouseX(evt);
	y = mouseY(evt);

	// Save starting positions of cursor and element.
	dragObj.cursorStartX = x;
	dragObj.cursorStartY = y;
	dragObj.elStartTop = Math.floor(getAbsoluteTop(dragObj.elNode));
	dragObj.elStartLeft = Math.floor(getAbsoluteLeft(dragObj.elNode));
	if (isNaN(dragObj.elStartLeft))
	{
		dragObj.elStartLeft = 0;
	}
	if (isNaN(dragObj.elStartTop))
	{
		dragObj.elStartTop = 0;
	}
	
	//alert("Cursor = " + dragObj.cursorStartX + "x" + dragObj.cursorStartY + "\nWindow = " + dragObj.elStartLeft + "x" + dragObj.elStartTop);
	
	// Update element's z-index.
	dragObj.elNode.style.zIndex = ++dragObj.zIndex;

	// Capture mousemove and mouseup events on the page.
	if (browser.isIE)
	{
		document.attachEvent("onmousemove", dragGo);
		document.attachEvent("onmouseup", dragStop);
		evt.cancelBubble = true;
		evt.returnValue = false;
	}
	if (browser.isNS)
	{
		document.addEventListener("mousemove", dragGo, true);
		document.addEventListener("mouseup", dragStop, true);
		evt.preventDefault();
	}
}

function dragGo(evt)
{
	var x, y, newX, newY;

	// Get cursor position with respect to the page.
	x = mouseX(evt);
	y = mouseY(evt);
	

	// Move drag element by the same amount the cursor has moved.
	newX = dragObj.elStartLeft + x - dragObj.cursorStartX;
	newY = dragObj.elStartTop + y - dragObj.cursorStartY;
	if (newX < 0)
		{ newX = 0; }
	if (newY < 0)
		{ newY = 0; }
	dragObj.elNode.style.left = newX + "px";
	dragObj.elNode.style.top = newY + "px";

	if (browser.isIE)
	{
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if (browser.isNS)
	{
		event.preventDefault();
	}
}

function dragStop(evt)
{

	// Stop capturing mousemove and mouseup events.
	if (browser.isIE)
	{
		document.detachEvent("onmousemove", dragGo);
		document.detachEvent("onmouseup", dragStop);
	}
	if (browser.isNS)
	{
		document.removeEventListener("mousemove", dragGo, true);
		document.removeEventListener("mouseup", dragStop, true);
	}
}
