addEvent(window, "load", init);

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=RunCGI("/cgi-bin/NewCart.cgi");
   CreateCookie("CART_ID", CartID);
   return(CartID);	
}

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-INFO" ||
	   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);
		
	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");}

		//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);
				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-INFO" ||
	   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); }
		
	}

	//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 AddToCart(Item)
{
	addProduct(Item);
	cartPopup('add');
}

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

function goShowcart()
{
	cartPopup();
}

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

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

function cartPopup(type)
{
	var url = "/STORE/showcart_opener.html";
	if(type == 'add') url += '?addtocart';
	cartWindow = window.open(url, 'cartPopup', 'status=0, toolbar=0, location=0, menubar=0, scrollbars=1, directories=0, height=500, width=400');
	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", cartPopup);
		}
	}
}

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 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);


	//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.getYear() - 1);
         document.cookie = name + '=null' + '; expires=' + expires; 
}

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);
}