//UNSYNCABLE!
var domain = "secure6";
var wherearewe = document.location.host;
var rawDomain = wherearewe.split('.');
var cartDomain = rawDomain[0];

if(cartDomain == 'myastm'){ cartDomain='www'; }

addEvent(window, "load", init);

//Mobile devices
//iphone, ipad, palm, droid, blackberry, ipod

if(navigator.userAgent.match(/Mobile/i) != null){
    //Load necessary files if user is on mobile device
    var jQueryJs = document.createElement('script');
    jQueryJs.type = "text/javascript";
    jQueryJs.src = "/JAVASCRIPT/facebox/jquery.js";
    document.getElementsByTagName('head')[0].appendChild(jQueryJs);
    
    if(location.href.indexOf("secure") < 0){
	var showcartJs = document.createElement('script');
	showcartJs.type = "text/javascript";
	showcartJs.src = "/STORE/showcart_test.js";
	document.getElementsByTagName('head')[0].appendChild(showcartJs);
    }

    var fancyboxCSS = document.createElement('link');
    fancyboxCSS.rel = "stylesheet";
    fancyboxCSS.type = "text/css";
    fancyboxCSS.href = "/JAVASCRIPT/facebox/facebox.css";
    document.getElementsByTagName('head')[0].appendChild(fancyboxCSS);

    var fancyboxJS = document.createElement('script');
    fancyboxJS.type = "text/javascript";
    fancyboxJS.src = "/JAVASCRIPT/facebox/facebox.js";
    document.getElementsByTagName('head')[0].appendChild(fancyboxJS);

    var cartPopupcss = document.createElement('link');
    cartPopupcss.rel = "stylesheet";
    cartPopupcss.type = "text/css";
    cartPopupcss.href = "/CSS/cart_work.css";
    document.getElementsByTagName('head')[0].appendChild(cartPopupcss);

    jQuery(document).ready(function($) {
	$('a[rel*=facebox]').facebox()
    })
}

function GetHTTP()
{
    var httpRequest;
    if(document.all) {
	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
	httpRequest = new XMLHttpRequest();
    }
    return(httpRequest);
}
function RunCGI(Command)
{
    var httpRequest = GetHTTP();
    var SpecString=Command;
    httpRequest.open('GET', SpecString, false);
    httpRequest.send(null);
    return(httpRequest.responseText);
}

function RunCGIPost(url, params)
{
    var httpRequest = GetHTTP();
    httpRequest.open('POST', url, false);
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader("Content-length", params.length);
    httpRequest.send(params);
    return(httpRequest.responseText);
}



function GetCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
	var returnString;
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0)
		{
			if(c.substring(nameEQ.length,c.length) == "OVERFLOW")
			{
				var cookieOverflow = RunCGI("/STORE/get_cookie_overflow.cgi","CART_ID=" + GetCartID() + "&NAME=" + name);
				return(cookieOverflow);
			}
			else
			{
				return c.substring(nameEQ.length,c.length);			
			}
		}
        }
        return null;
}

function CreateCookie(Name,Value)
{
    var expiry = new Date();
    expiry.setDate(expiry.getDate() + 1);

    var CookString=Name+"=" + Value + "; path=/; domain=.astm.org; expires="+expiry.toGMTString();
    document.cookie=CookString;

}
function GetStoreName()
{
    var Cookie=GetCookie("STORE");
    if(Cookie) return Cookie;
    return("mystore");
}

function GetCartID()
{
    var Cookie=GetCookie("CART_ID");

    if(Cookie) return Cookie;
    CartID = randFourLetter() + randFourNumber();
    var expires = new Date();
    expires.setDate(expires.getDate() + 29);
    document.cookie = "CART_ID=" + CartID + ";" + "expires=" + expires.toGMTString() + ";" + "path=/; domain=.astm.org;";
    //CreateCookie("CART_ID", CartID);
    return(CartID);	
}

function randFourLetter()
{
    var letters = "";
    var aRaw = "abcdefghijklmnopqrstuvwxyz";
    var a = aRaw.split('');
    for(var i = 0; i < 4; i++)
    {
	var r = Math.random();
	letters += a[parseInt(r * 26)];
    }
    return(letters);
}

function randFourNumber()
{
    var num = 0;
    var rand = Math.random();
    num = zeroPad(parseInt(rand * 10000), 4);
    return(num);
}

/*
 * s - string to pad
 * n - number of places
*/
function zeroPad(s, n)
{
    var padded = "";
    var z = n - s.toString().length;
    for(var i = 0; i < z; i++)
    {
	padded += "0";
    }
    padded += s;
    return(padded);
}

function getParam(name, type)
{
    //assumes URL's are of the form foo=bar+name=value
    if(type == "new") { var delim = '&'; }
    if(type == "old") { var delim = '+'; }
    var url = this.location.href;
    var queryStart = (url.indexOf('?') + 1);
    var queryString = url.substring(queryStart, url.length);
    var pairs = queryString.split(delim);
    for(var i = 0; i < pairs.length; i++)
    {
	var paramAndValue = pairs[i].split('=');
	if(paramAndValue[0] == name) { return(paramAndValue[1]); }
    }
    return (false);
}

function AddToCartPassId(cartid, Item)
{
    addProduct(Item);
}

function addProduct(sku)
{
	var quantity = 1;
	var description;
	var price;
	var contents;

	//don't allow users to add multiple of the MEMBER products
	if(sku == "MEMBER-PARTM" || sku == "MEMBER-ORGM" || sku == "MEMBER-INFOM" ||
	   sku == "RENEW-PART"   || sku == "RENEW-ORG"   || sku == "RENEW-INFO"
	  )
	{
		//we haven't written the current sku to the cookie yet, so if the SKU is defined in the cookie
		//	already then we don't want to add another one
		if(getQuantity(sku)) { return (false); }
		
	}

	//get description and price from the server
	//FF and IE both aggresively cache ajax, appending a random parameter should stop this behavoir
	var rand = Math.floor(Math.random()*1000);

	var SpecString="/STORE/itemsjson_new.cgi?" + sku + ":1" + "+" + rand;
	var result = eval('(' + RunCGI(SpecString) + ')');

	description = result.cartContents.items[0].DESC;
	description = description.replace("+", "&#43;");
	description = description.replace("!", "&#33;");
	price = result.cartContents.items[0].PRICE;
	
	//append to cookie
	if(getCookie("cartcon"))
	{
		if(!productExists(sku))
		{
			var contents = getCookie("cartcon");
			contents += "!" + sku + "###" + quantity + "###" + description + "###" + price;
		}
		//product already exists, increment quantity
		else
		{
			changeQuantity(sku, getQuantity(sku) + 1)
			return(true);
		}

	}
	//create cookie
	else
	{
		//semi-colons serperate item and qunatity, pipes will delimit items inside of the cookie
		contents = sku + "###" + quantity + "###" + description + "###" + price;
	}
	//some descriptions include a semicolon, escape them
	setCookie("cartcon", contents);

	//draw the inline cart but don't show it
	//drawCartInline();
		
	return(true);
}

function getQuantity(sku)
{
	var products = new Array();
	var skus = new Array();
	var quantities = new Array();
			
	//get products
	products = getCartContents(getCookie("cartcon"));
	
	//unpack arrays
	skus = products[0];
	quantities = products[1];

	for(var i = 0; i < skus.length; i++)
	{
		if(skus[i] == sku)
		{
			return(parseInt(quantities[i]));
		}	
	}

	return(false);
}

function productExists(sku)
{
	var products = new Array();
	var skus = new Array();
			
	//get products
	products = getCartContents(getCookie("cartcon"));
	
	//unpack arrays
	skus = products[0];

	for(var i = 0; i < skus.length; i++)
	{
		if(skus[i] == sku)
		{
			return(true);
		}
	}

	return(false);
}

function removeDescAndPrice()
{
	var skus = new Array();	
	var quantities = new Array();
	var descriptions = new Array();
	var prices = new Array();
	
	var newContents = "";

	products = getCartContents(getCookie("cartcon"));
	//unpack the products array	
	skus = products[0];
	quantities = products[1];
	descriptions = products[2];
	prices = products[3];
	
	for(var i = 0; i < skus.length; i++)
	{
		newContents += skus[i] + "###" + quantities[i];
		if(i + 1 < skus.length) { newContents += "!"; }
	}

	setCookie("cartcon", newContents);
	return(true);

}

function getCartContents(contents)
{
	var itemAndQuantity = new Array();
	var products = new Array();
	var quantities = new Array();
	var descriptions = new Array();
	var prices = new Array();
	
	//return array will be a multi-d array with [0] as items [1] as qty [2] as descriptions [3] as prices
	var returnArray = new Array();

	//this array will contain item###qty###desc###price
	itemsAndQuantity = contents.split("!");

	//build two arrays, one for skus and one for quantitys
	for(var i = 0; i < itemsAndQuantity.length; i++)
	{
		var tmp = new Array();
		tmp = itemsAndQuantity[i].split("###");
		products[i] = tmp[0];
		quantities[i] = tmp[1];
		descriptions[i] = tmp[2];
		prices[i] = tmp[3];
	}

	returnArray[0] = products;
	returnArray[1] = quantities;
	returnArray[2] = descriptions;
	returnArray[3] = prices;

	return(returnArray);
}

function searializeContents(products)
{
	var returnString = "";
	var skus = new Array();	
	var quantities = new Array();
	var descriptions = new Array();
	var prices = new Array();

	//unpack the products array	
	skus = products[0];
	quantities = products[1];
	descriptions = products[2];
	prices = products[3];

	if(!skus[0] || skus[0] == null) { return(returnString); }
	
	for(var i = 0; i < skus.length; i++)
	{
		returnString += skus[i] + "###" + quantities[i] + "###" + descriptions[i] + "###" + prices[i];
		if(i + 1 < skus.length) { returnString += "!"; }
	}

	return(returnString);
}

function removeProductsLike(partialSku)
{
	if(getCookie("cartcon"))
	{	
		var products = new Array();
		var skus = new Array();
		var quantities = new Array();
		var descriptions = new Array();
		var prices = new Array();
		var alteredProducts;	

		//get arrays of products and quantitys
		products = getCartContents(getCookie("cartcon"));
		skus = products[0];
		quantities = products[1];
		descriptions = products[2];
		prices = products[3];
		
		//remove the product
		for(var i = 0; i < skus.length; i++)
		{
			if(skus[i].indexOf(partialSku) > -1)
			{
				skus.splice(i,1);	
				quantities.splice(i,1);
				descriptions.splice(i,1);
				prices.splice(i,1);
				i--;
			}
	
		}

		//put them back in 1 array
		products[0] = skus;
		products[1] = quantities;
		products[2] = descriptions;
		products[3] = prices;
	
		//serialize the products array
		alteredProducts = searializeContents(products);
		
		setCookie("cartcon", alteredProducts);
		return(true);
	}
	else
	{
		return(false);
	}
}

function removeProduct(sku)
{
	if(getCookie("cartcon"))
	{	
		var products = new Array();
		var skus = new Array();
		var quantities = new Array();
		var descriptions = new Array();
		var prices = new Array();
		var alteredProducts;	

		//check if they are ordering a combo priced product - need to remove discounted first
		if(sku.indexOf("COMBOPUB") > -1 || sku.indexOf("COMBOPDF") > -1) { removeProductsLike("COMBOPDF"); removeProductsLike("COMBOPUB");}
		if(sku == "MEMBER-PARTM" || sku == "MEMBER-ORGM" || sku == "MEMBER-INFO" || sku == "RENEW-PART"   || sku == "RENEW-ORG"   || sku == "RENEW-INFO") { 
		       removeProductsLike("RENEW");
		}

		//get arrays of products and quantitys
		products = getCartContents(getCookie("cartcon"));
		skus = products[0];
		quantities = products[1];
		descriptions = products[2];
		prices = products[3];
		
		//remove the product
		for(var i = 0; i < skus.length; i++)
		{
			if(skus[i] == sku)
			{
				skus.splice(i,1);	
				quantities.splice(i,1);
				descriptions.splice(i,1);
				prices.splice(i,1);
				setLastRemoved(sku);
				break;
			}
	
		}

		//put them back in 1 array
		products[0] = skus;
		products[1] = quantities;
		products[2] = descriptions;
		products[3] = prices;
	
		//serialize the products array
		alteredProducts = searializeContents(products);
		
		setCookie("cartcon", alteredProducts);
		return(true);
	}
	else
	{
		return(false);
	}
}

function changeQuantity(sku, quantity)
{
	var products = getCartContents(getCookie("cartcon"));
	var skus = new Array();
	var quantities = new Array();
	var descriptions = new Array();
	var prices = new Array();
	
	//don't allow users to add multiple of the MEMBER products
	if(sku == "MEMBER-PARTM" || sku == "MEMBER-ORGM" || sku == "MEMBER-INFOM" || sku == "RENEW-PART"   || sku == "RENEW-ORG"   || sku == "RENEW-INFO"){
	    //we haven't written the current sku to the cookie yet, so if the SKU is defined in the cookie already then we don't want to add another one
	    if(getQuantity(sku) && quantity != 0) { return (false); }
	    else { removeProduct(sku); return(false); }
	}

	//unpack arrays
	skus = products[0];
	quantities = products[1];
	descriptions = products[2];
	prices = products[3];


	if(quantity == 0)
	{
		removeProduct(sku);
	}
	
	else
	{
		for(var i = 0; i < skus.length; i++)
		{
			if(skus[i] == sku)
			{
				quantities[i] = quantity;
				break;
			}
		}
		//put them back in 1 array
		products[0] = skus;
		products[1] = quantities;
		products[2] = descriptions;
		products[3] = prices;

		//serialize the products array
		alteredProducts = searializeContents(products);
	
		setCookie("cartcon", alteredProducts);
	}
	return(true);
}

function proceedCheckout(){
    var url = "https://" + domain + ".astm.org/STORE/review_order.html";
    window.location = url;
}

function AddToCart(Item)
{
    addProduct(Item);
    proceedCheckout();
    //cartPopup('add');
}

function AddToCartNoRe(Item)
{
    addProduct(Item);
}

function addCourse(item){
    if(checkTPT()){ addProduct(item); return(true);}
    else { return(false); }
}

function checkTPT(){
    var tpts = 0;
    var products = new Array();
    var skus = new Array();
    var quantities = new Array();

    //get products
    products = getCartContents(getCookie("cartcon"));
	
    //unpack arrays
    skus = products[0];
    quantities = products[1];
    
    for(var i = 0; i < skus.length; i++){
	if(skus[i].substring(0, 3) == "TPT"){
	    tpts++;
	}
    }
    if(tpts > 0){ return(false); }
    else { return(true); }
}

function goShowcart()
{
    proceedCheckout();
    //cartPopup();
}

function AddItems(Items)
{
    //Items should be an array of product codes

    for(var i = 0; i < Items.length; i++)
    {
	addProduct(Items[i]);
    }
    proceedCheckout();
    //cartPopup('add');
}

function cartPopup(type)
{
    if(navigator.userAgent.match(/Mobile/i) != null){
	jQuery.facebox({ ajax: '/STORE/showcart_test.html' });
	setTimeout(drawCart, 4000);
    }
    else {
	var left = (screen.width/2)-(500/2);
	var top = (screen.height/2)-(500/2);
	var url = "http://" + cartDomain + ".astm.org/STORE/viewcart.html?utm_nooverride=1";
	if(type == 'add') url= "http://" + cartDomain + ".astm.org/STORE/addtocart.html?utm_nooverride=1";
	cartWindow = window.open(url, 'cartPopup', 'status=0, toolbar=0, location=0, menubar=0, scrollbars=1, directories=0, height=500, width=520, top='+top+', left='+left);
	/*var x = (screen.width * .6);
	var y = (screen.height * .15);*/
	cartWindow.focus();
    }
}

function init()
{
    var links = document.getElementsByTagName('a');
    for(var i = 0; i < links.length; i++)
    {
	if(links[i].href.indexOf("/STORE/showcart.html") > 0)
	{
	    links[i].removeAttribute('href');
	    addEvent(links[i], "click", proceedCheckout);
	}
    }
    //Draw cart will draw the inline cart in a hidden manner and attach to the view cart button
    //drawCartInline();
}

function addEvent(obj, evType, fn)
{ 
    if (obj.addEventListener)
    { 
	obj.addEventListener(evType, fn, false); 
	return true; 
    } 
    else if (obj.attachEvent)
    { 
 	var r = obj.attachEvent("on"+evType, fn); 
	return r; 
    }
    else 
    { 
	return false; 
    } 
}

function removeEvent(obj, evType, fn)
{ 
    if(obj.removeEventListener)
    {
	obj.removeEventListener(evType, fn, false);
	return true; 
    } 
    else if(obj.detachEvent)
    { 
	obj.detachEvent("on"+evType, fn);
	return true;
    }
    else 
    { 
	return false; 
    } 
}

function setCookie(name, value)
{
	//If name is the empty string, it places a ; at the beginning
        //of document.cookie, causing clearCookies() to malfunction.
	name = escape(name);
	value = escape(value);
	var expires = new Date();
        expires.setDate(expires.getDate() + 1);

	if(name == "cartcon") { expires.setDate(expires.getDate() + 29); }

	//when this checks if the cookie is overflowing, it will be false because it's returning the value we got from the server...
	if((byteLength(document.cookie) + byteLength(value)) >= 4096 || checkOverflow(name))
	{
		document.cookie = name + '=' + 'OVERFLOW;expires=' + expires.toGMTString() + ';path=/; domain=.astm.org;';
		RunCGIPost("/STORE/set_cookie_overflow.cgi?", "CART_ID=" + GetCartID() + "&NAME=" + name + "&VALUE=" + value);
	}
	else if(name != ''){ document.cookie = name + '=' + value + ';' + 'expires=' + expires.toGMTString() + ';' + 'path=/; domain=.astm.org;'; }
}

function clearCookie(name)
{                  
    expires = new Date();
    expires.setYear(expires.getFullYear() - 1);
    document.cookie = name + '=null' + '; expires=' + expires.toGMTString() + ';' + 'path=/; domain=.astm.org;';
}

function getCookie(name)
{
	 name = escape(name);
	
         //Without this, it will return the first value 
         //in document.cookie when name is the empty string.
         if(name == '') { return(''); }
         
         name_index = document.cookie.indexOf(name + '=');
         
         if(name_index == -1) { return(''); }
         
         cookie_value =  document.cookie.substr(name_index + name.length + 1, document.cookie.length);
         
         //All cookie name-value pairs end with a semi-colon, except the last one.
         end_of_cookie = cookie_value.indexOf(';');
         if(end_of_cookie != -1) { cookie_value = cookie_value.substr(0, end_of_cookie); }

         //Restores all the blank spaces.
         space = cookie_value.indexOf('+');
         while(space != -1)
         { 
         	cookie_value = cookie_value.substr(0, space) + ' ' + cookie_value.substr(space + 1, cookie_value.length);
         	space = cookie_value.indexOf('+');
         }

  	 if(cookie_value == "OVERFLOW"){ cookie_value = RunCGI("/STORE/get_cookie_overflow.cgi?CART_ID=" + GetCartID() + "&NAME=" + name); }		

	 cookie_value = unescape(cookie_value);
         return(cookie_value);
}

function checkOverflow()
{
	 name = escape(name);
	
         //Without this, it will return the first value 
         //in document.cookie when name is the empty string.
         if(name == '') { return(''); }
         
         name_index = document.cookie.indexOf(name + '=');
         
         if(name_index == -1) { return(''); }
         
         cookie_value =  document.cookie.substr(name_index + name.length + 1, document.cookie.length);
         
         //All cookie name-value pairs end with a semi-colon, except the last one.
         end_of_cookie = cookie_value.indexOf(';');
         if(end_of_cookie != -1) { cookie_value = cookie_value.substr(0, end_of_cookie); }

         //Restores all the blank spaces.
         space = cookie_value.indexOf('+');
         while(space != -1)
         { 
         	cookie_value = cookie_value.substr(0, space) + ' ' + cookie_value.substr(space + 1, cookie_value.length);
         	space = cookie_value.indexOf('+');
         }

	 cookie_value = unescape(cookie_value);
	 if(cookie_value == "OVERFLOW")
	 {
		return(true);
 	 }
	 else
	 {
	 	return(false);
	 }
}

function byteLength(input) 
{
        var escapedStr = encodeURI(input);
	var count = 0;

        if (escapedStr.indexOf("%") != -1) 
	{
            count = escapedStr.split("%").length - 1
            if (count == 0) count++  //perverse case; can't happen with real UTF-8
            var tmp = escapedStr.length - (count * 3)
            count = count + tmp
        } 
	else 
	{
            count = escapedStr.length
        }
	return(count);
}

function cartNotEmpty()
{
	if(!getCartContents(getCookie("cartcon"))) 
	{ 
		alert("You currently have no products in your cart");
		return(false); 
	}
	
	var skus = new Array();
	var products = getCartContents(getCookie("cartcon"));
	skus = products[0];

	if(!skus[0] || skus[0] == "")
	{
		alert("You currently have no products in your cart");
		return(false);
	}
	return(true);
}

function getSafeCookieString()
{
	var products = getCartContents(getCookie("cartcon"));
	var skus = products[0];
	var quantities = products[1];
	var descrip = products[2];
	var itemString = "";

	for(var i = 0; i < skus.length; i++)
	{
		if(skus[i].indexOf('COPY') > -1)
		{
			var newQ = getCopyrightQty(descrip[i]);
			itemString += skus[i] + ":" + newQ;
		}
		else
		{
			itemString += skus[i] + ":" + quantities[i];

		}
		if(skus[i+1]) { itemString += "!"; }
	}	
	return(itemString);
}

function getCopyrightQty(descrip)
{
	var tmp = "";
	var qty = -1;
	
	var numbers = "0123456789";
	for(var i = 0; i < descrip.length; i++)
	{
		if(numbers.indexOf(descrip.charAt(i)) < 0) { continue; }
		else
		{
			//we found the start of the number, capture it all
			while(numbers.indexOf(descrip.charAt(i)) > -1)
			{
				tmp += descrip.charAt(i)
				i++;
			}
			//end of the numbers, cast and return
			qty = parseInt(tmp);
			return(qty);
		}

	}
	return(qty);
}

function setLastRemoved(sku)
{
	setCookie("lastRemoved", sku);
}

function getLastRemoved()
{
	return(getCookie("lastRemoved"));
}

function restoreLastRemoved()
{	
	var lastRemoved = getLastRemoved();
	if(lastRemoved) addProduct(lastRemoved);
}

/************* Function for inline cart ****************/


function createCartTableInline(container)
{
	//create the table and header elements
	var newTable = document.createElement('table');
	newTable.className = "cart_table";
	newTable.setAttribute("cellPadding", "5");
	newTable.setAttribute("cellSpacing", "0");
	newTable.setAttribute("border", "0");
	
	var newTBody = document.createElement('tbody');
	var newRow = document.createElement('tr');

	//trash header
	var trashHeader = document.createElement('td');
	trashHeader.className = "trash";
	newRow.appendChild(trashHeader);

	//description header
	var descHeader = document.createElement('td');
	descHeader.className = "cart_head_td";
	var descP = document.createElement('p');
	descP.className = "cart_head_p";
	var descText = document.createTextNode('Description');
	descP.appendChild(descText);
	descHeader.appendChild(descP);
	newRow.appendChild(descHeader);

	//quantity header
	var qtyHeader = document.createElement('td');
	qtyHeader.className = "cart_head_td";
	var qtyP = document.createElement('p');
	qtyP.className = "cart_head_p";
	var qtyText = document.createTextNode('Quantity');
	qtyP.appendChild(qtyText);
	qtyHeader.appendChild(qtyP);
	newRow.appendChild(qtyHeader);
	
	//price header
	var priceHeader = document.createElement('td');
	priceHeader.className = "cart_head_td";
	var priceP = document.createElement('p');
	priceP.className = "cart_head_p";
	var priceText = document.createTextNode('Price');
	priceP.appendChild(priceText);
	priceHeader.appendChild(priceP);
	newRow.appendChild(priceHeader);

	//total header
	var totalHeader = document.createElement('td');
	totalHeader.className = "cart_head_td";
	var totalP = document.createElement('p');
	totalP.className = "cart_head_p";
	var totalText = document.createTextNode('Total');
	totalP.appendChild(totalText);
	totalHeader.appendChild(totalP);
	newRow.appendChild(totalHeader);

	newTBody.appendChild(newRow);
	newTable.appendChild(newTBody);
	container.appendChild(newTable);
	
}

function drawCartInline()
{
    //When the page loads the cart is drawn on the page but hidden. This make showing much faster than building when the want to show
    loadCartCssInline();

    //Change the button to show the cart on hover
    alterShowcartButtonInline();

    //paint the cart based on the cookie
    //var container is what we're going to stick the table in 

    //var container = document.getElementById('cartContentsInline') ? document.getElementById('cartContentsInline') : document.createElement('div');
    //if(!container.id) { container.id = "cartContentsInline"; }

    if(document.getElementById('cartContentsInline')) { document.getElementById('cartContentsInline').parentNode.removeChild(document.getElementById('cartContentsInline')); }
    var container = document.createElement('div');
    container.id = "cartContentsInline";
    container.style.display = "none";

    //The dollar amount total
    var total = 0;

    //Result is our JSON ojbect of cart information. This process mimics how we build the cart when pulling down the info from the server
    var result;

    if(!getCookie("cartcon")) { return(false); }
    
    products = getCartContents(getCookie("cartcon"));
    var skus = products[0];
    var quantities = products[1];
    var descriptions = products[2];
    var prices = products[3];
	
    var headerP = document.createElement('p');
    headerP.className = "newheader";
    headerP.appendChild(document.createTextNode('Your Shopping Cart Currently Contains:'));
	
    container.appendChild(headerP);

    //set up the table
    createCartTableInline(container);

    //IE won't work right unless you use a tbody inside the table and append to instead of the table itself
    var cartTableTBody = container.getElementsByTagName('tbody')[0];

    //Create the results object. This should probably be rewritten to not use eval
    result = buildCartObjectInline();

    /* Begin products added to cart */
    if(result.cartContents.items.length > 0)
    {
	for(var i = 0; i < result.cartContents.items.length; i++)
	{
	    var newRow = document.createElement('tr');
	    var newColumn = document.createElement('td');
	    var newImage = document.createElement('img');
	    newImage.src = "/IMAGES03/trash_sm.gif";
	    newImage.title = "Delete Item";
	    newImage.alt = "Delete Item";
	    addEvent(newImage, "click", makeTrashCallbackInline(result.cartContents.items[i].SKU));
	    newColumn.appendChild(newImage);
	    newColumn.className = "trash";
	    newRow.appendChild(newColumn);

	    var newColumn = document.createElement('td');
	    var smallDesc = result.cartContents.items[i].DESC;
	    var newP = document.createElement('p');
	    newP.className = "desc_p";
	    newP.innerHTML = smallDesc;
	    newColumn.appendChild(newP);
	    newColumn.className = "cart_body_td"; 	
	    newRow.appendChild(newColumn);
	
	    var newColumn = document.createElement('td');
	    newColumn.className = "cart_body_td";
	    var newInput = document.createElement('input');
	    newInput.setAttribute('type','text');
	    newInput.setAttribute('size','2');
	    newInput.setAttribute('id', result.cartContents.items[i].SKU + '_quan');
	    if(result.cartContents.items[i].SKU.substring(0, 4) == "COPY")
	    {
		newInput.setAttribute('disabled','true');
	    }
	    addEvent(newInput, "change", checkQtyInline);
	    newInput.value = result.cartContents.items[i].QTY;
	    newColumn.appendChild(newInput);
	    newRow.appendChild(newColumn);
	
	    var newColumn = document.createElement('td');
	    var newText = document.createTextNode("$" + parseFloat(result.cartContents.items[i].PRICE).toFixed(2));
	    newColumn.appendChild(newText);
	    newColumn.className = "cart_body_td";
	    newRow.appendChild(newColumn);

	    var newColumn = document.createElement('td');
	    var newText = document.createTextNode("$" + (parseFloat(result.cartContents.items[i].PRICE) * result.cartContents.items[i].QTY).toFixed(2));
	    newColumn.appendChild(newText);
	    newColumn.className = "cart_body_td";
	    newRow.appendChild(newColumn);
	
	    cartTableTBody.appendChild(newRow);
	    total += (parseFloat(result.cartContents.items[i].PRICE) * result.cartContents.items[i].QTY);
	}
	cartTableTBody.appendChild(newRow);
    }
    createFooterInline(container, total);
    document.body.appendChild(container);
}

function createFooterInline(container, total)
{
	var cartTableTBody = container.getElementsByTagName('tbody')[0];

	/****************** Update Qty row ****************/

	var newRow = document.createElement('tr');
	
	//the trash td has a white background so we need to add it here
	var trash = document.createElement('td');
	trash.className = "trash";
	newRow.appendChild(trash);

	//a row to add space
	//var space = document.createElement('td');
	//newRow.appendChild(space);

	var updateQty = document.createElement('td');
	var updateImg = document.createElement('img');
	updateQty.className = "cart_change_quantity";
	updateQty.colSpan = 4;
	updateImg.src = "/IMAGES03/update_cart.gif";
	updateImg.setAttribute('id','changeButton');
	updateImg.id = "changeButton";
	addEvent(updateImg, "click", reloadCartInline);
	updateQty.appendChild(updateImg);
	newRow.appendChild(updateQty);
	cartTableTBody.appendChild(newRow);
	

	/***************************************************/


	/****************** Subtotal row ****************/

	var newRow = document.createElement('tr');

	//the trash td has a white background so we need to add it here
	var trash = document.createElement('td');
	trash.className = "trash";
	newRow.appendChild(trash);

	var newColumn = document.createElement('td');
	newColumn.className = "cart_footer_td";
	newColumn.colSpan = 4;
	newColumn.setAttribute('align','right');
	var newP = document.createElement('p');
	var newText = document.createTextNode("Subtotal: $" + total.toFixed(2));
	newColumn.appendChild(newText);
	newRow.appendChild(newColumn);
	
	newP.appendChild(newText);
	newColumn.appendChild(newP);
	newRow.appendChild(newColumn);
	cartTableTBody.appendChild(newRow);

	/***************************************************/

	/***********Continue Shopping & Checkout buttons****/

	/*
	var continueShoppingSpan = document.createElement('span');
	continueShoppingSpan.className = "span_right";

	var continueShoppingLink = document.createElement('a');
	continueShoppingLink.href = "/NEWSITE_JAVASCRIPT/index.shtml";
	continueShopping.style.cursor = "pointer";

	var continueShoppingImage = document.createElement('img');
	continueShoppingImage.src = "/IMAGES03/cont_shop.gif";

	continueShoppingLink.appendChild(continueShoppingImage);
	continueShoppingSpan.appendChild(continueShoppingLink);

	container.appendChild(continueShoppingSpan);
	*/
	
	var buttonP = document.createElement('p');
	buttonP.className = "button_p";

	var closeLink = document.createElement('a');
	closeLink.style.cursor = 'pointer';
	var closeImg = document.createElement('img');
	closeImg.src = "/IMAGES03/close.gif";
	closeLink.appendChild(closeImg);
	addEvent(closeLink, "click", function(){show_hid_box_inline('cartContentsInline','2px solid')});
	buttonP.appendChild(closeLink);
	
	var checkoutLink = document.createElement('a');
	checkoutLink.style.cursor = "pointer";

	addEvent(checkoutLink, "click", goCheckoutInline);
	
	var checkoutImage = document.createElement('img');
	checkoutImage.src = "/IMAGES03/checkout.gif";
	
	checkoutLink.appendChild(checkoutImage);
	buttonP.appendChild(checkoutLink);

	container.appendChild(buttonP);

	/***************************************************/
}

function makeTrashCallbackInline(sku)
{
	return (function() { removeProduct(sku); reloadCartInline(); });
}

function reloadCartInline(){
   if(!validQtyInline()) { return false; }
	//Check if there is nothing in their cart. If so, reload the page.
	if(getCookie("cartcon"))
	{
		drawCartInline();
		show_hid_box_inline('cartContentsInline','2px solid');
	}
	else
	{
		window.location.reload();
	}
   
}

function validQtyInline()
{
	var allInput = document.getElementsByTagName('input');
	for(i = 0; i < allInput.length; i++)
	{
		if(allInput[i].name.indexOf('quan_') > -1)
		{
			if(!isNumeric(allInput[i].value))
			{
				alert ("Please enter only numeric values for quantities");
				return (false);
			}
		}
	}
	return (true);
}

function checkQtyInline()
{
	//so we have no idea which quantities have changed, so we need to find which have and do something
	
	var allInput = document.getElementsByTagName('input');
	for(var i = 0; i < allInput.length; i++)
	{
  		if(allInput[i].id.indexOf("_quan") > -1)
		{
			//pull out the SKU
			var sku = allInput[i].id.substring(0, allInput[i].id.indexOf("_"));

			//don't allow free vols to be changed
			if(sku.indexOf("RENEW-") > -1 && allInput[i].value != 1) { allInput[i].value = 1; return(false); }

			var products = new Array();
			var skus = new Array();
			var quantities = new Array();
						
			//get products
			products = getCartContents(getCookie("cartcon"));
		
			//unpack arrays
			skus = products[0];
			quantities = products[1];
	
	   		//check the current value vs the old value
			for(var j = 0; j < skus.length; j++)
			{
				if(skus[j] == sku)
				{
					if(quantities[j] = allInput[i].value)
					{
						changeQuantity(skus[j], allInput[i].value)
					}
				}
	   		}
		}
	}
}

function buildCartObjectInline()
{
	var cartObj = new Object();
	var products = getCartContents(getCookie("cartcon"));

	var skus = products[0];
	var quantities = products[1];
	var descriptions = products[2];
	var prices = products[3];

	cartObj.cartContents = new Object();
	cartObj.cartContents.items = new Array();
	
	for(var i = 0; i < skus.length; i++)
	{
		cartObj.cartContents.items.push(new item(skus[i], descriptions[i], quantities[i], prices[i]));
	}
	
	return(cartObj);

}

function item(sku, desc, qty, price)
{
	this.SKU = sku;
	this.DESC = desc;
	this.QTY = qty;
	this.PRICE = price;
	
	return(this);
}

function goCheckoutInline()
{	
	if(!validQtyInline()) { return false; }
	var url = getDomainInline("https://secure6.astm.org/STORE/review_order.html");
	window.location = url;
}

function getDomainInline(LINK){
    var NEWLINK=LINK.toString();
    //Domain="";
    if (domain != "secure6"){     
	NEWLINK = NEWLINK.replace("secure6","secure7") + "";
    }
    return NEWLINK;
}

function getYInline( el )
{
	var y = 0;
	while( el != null ) 
	{
		y += el.offsetTop;
		el = el.offsetParent;
	}
	return y;
}


function getXInline( el )
{
	var x = 0;
	while( el != null ) 
	{
		x += el.offsetLeft;
		el = el.offsetParent;
	}

	return x;
}

function show_hid_box_inline(el, borderStyle) 
{
	width = 375;

	var boxdiv = document.getElementById(el);
	
	if(!boxdiv) { return(false); }

	if (boxdiv.style.display == 'none' || !boxdiv.style.display) 
	{ 
		boxdiv.style.display = 'block'; 
	} 
	else
	{
		boxdiv.style.display = 'none';
		return(false);
	}

	  boxdiv.style.display = 'block';
	  boxdiv.style.position = 'absolute';
	  boxdiv.style.overflow = 'hidden';
	  boxdiv.style.width = width + 'px';
	  boxdiv.style.border = '3px double #052d68';
	  boxdiv.style.backgroundColor = '#fff';
	  boxdiv.style.top =  getYInline(document.getElementById('viewCart')) + 'px';
	  boxdiv.style.left = (getXInline(document.getElementById('viewCart'))-width/2 - 50)  + 'px';
	
	  return false;
}

function alterShowcartButtonInline()
{
	var links = document.getElementsByTagName('a');
	for(var i = 0; i < links.length; i++)
	{
		if(links[i].href.indexOf("/showcart.html") > 0)
		{
			links[i].removeAttribute('href');
			links[i].id = "viewCart";
			
			if(!this.cartType) cartType = "popup";
			addEvent(links[i], "click", cartPopup);
		}
	}
	
	return(true);
}

function loadCartCssInline()
{
	var stylesheets = document.getElementsByTagName('link');
	for(var i = 0; i < stylesheets.length; i++)
	{
		if(stylesheets[i].href == "/CSS/cart.css") { return(false); }
	}
	
	var cartCss = document.createElement('link');
	cartCss.rel = "stylesheet";
	cartCss.type = "text/css";
	cartCss.media = "screen";
	cartCss.href = "/CSS/cart.css";
	document.getElementsByTagName('head')[0].appendChild(cartCss);
}	



/*******************************************************/
