// jshop.js JavaScript Development by JavaScriptDesign.com
// email solutions@javascriptdesign.com  Copyright 2000
// All Rights Reserved. Copyright Notice Must Remain in
// Source files and Catalog Pages.

// ****Begin code section for catalog display****

// **Establish catalog array variables. These must match the**
// **catalog array construction on each page.**

var catalogNum = new Array(); // The catalog number
var catalogItemName = new Array(); // The item name
var catalogItemDesc = new Array(); // The item description
var catalogPrice = new Array(); // The item Price
var catalogQtyOnHand = new Array(); //Number of items in stock
var catalogReserve = new Array(); //Maximum Order Quantity
var catalogWeight = new Array(); //Bottle Weight
var catalogDiscountPrice = new Array(); //Discounted Price

// **Object constructor to build the catalog array.**
// **Catalog entries are in an array on each page.**

function loadCatalog(num,iNum,iName,iDesc,cost,inventory_qty, order_max,bottleWeight,discountPrice) {
 catalogNum[num] = iNum;
 catalogItemName[num] = iName;
 catalogItemDesc[num] = iDesc;
 catalogPrice[num] = cost;
 catalogQtyOnHand[num] = inventory_qty;
 catalogReserve[num] = order_max;
 catalogWeight[num] = bottleWeight;
 catalogDiscountPrice[num] = (isNaN(discountPrice) ? 0 : discountPrice);
}

// **Function to write the content for each table row.**
// **This reads the array data and populates a table **
// **for catalog display.

function writeTableRow(i) {
  var trow;
  trow = '<form style="margin: 0 0 0 0px" name=orderform' + i + '>'
  trow += '<div class="shop_item"><div class="shop_hdr">'
  trow += '<strong>' + catalogItemName[i] + ' ' + catalogItemDesc[i] + '</strong><br>'
  if (parseFloat(catalogDiscountPrice[i]) > 0) {
        trow += '<font color=red><strong>Special Price -$' + catalogDiscountPrice[i] + '</strong></font>'
  	trow += ' (regularly $' +  catalogPrice[i] +')'
  	
  } else {
   	trow += 'Bottle Price -$' + catalogPrice[i]
  }
  trow += '</div><div class="shop_select">'
  if (parseFloat(catalogReserve[i]) < 0) {
  	trow += '<div style="float:left;margin-top:10;font-weight:bold;text-align:center">Limited Quantities<br>Please Call!</div>'
  } else if(parseFloat(catalogReserve[i]) == 9999) {
    trow += '<div style="float:left;margin-top:10;font-weight:bold;text-align:center">Special Handling<br>Please Call!</div>'
  } else {
 	 trow += '<br><input type=text size=2 style="{text-align: center}" value=1'
         trow += ' onkeypress=editKeyBoard(this,keybNumeric) name=qty' + i + '>&nbsp;'
 	 trow += '<a href="javascript:addItem(' + i +')"><IMG border="0" src="images/addToCart.gif" WIDTH="90" HEIGHT="15"></a>'
  }
  trow += '</div></div></form>'
  document.write(trow);
}


// **Function to write the catalog display table to **
// **the current document.**

function writeTable() {
 for (i=0; i < catalogNum.length; i++)
  writeTableRow(i);
}

// ****End code section for writing catalog content.****


// ****Begin shared cookie functions****

// **Global expdate variable for cookies**
// **Cookie is set to expire in 24 hours**

var expdate = new Date()
expdate.setTime (expdate.getTime() + (1 * 24 * 60 * 60 * 1000))

// **Read cookie data.**

function getCookieData(name) {
	var label = name + "="
	var labelLen = label.length
	var cLen = document.cookie.length
	var i = 0
	while (i < cLen) {
		var j = i + labelLen
		if (document.cookie.substring(i,j) == label) {
			var cEnd = document.cookie.indexOf(";",j)
			if (cEnd == -1) {
				cEnd = document.cookie.length
			}
			return unescape(document.cookie.substring(j,cEnd))
		}
		i++
	}
	return 0
}

// **Write cookie data**

function setCookieData(name,value,expires) {
	document.cookie = name + "=" + counter + "@" + value + "; expires=" + expires
}

// **Kill cookie function. When the order is submitted**
// **the cookie is killed via an event handler call.**

function killCookie(name) {
 if (getCookieData(name)) {
 document.cookie = name + "=" + "; expires = Thu, 01-Jan-70 00:00:01 GMT";
 cookData = ""
 counter = 0
// history.go(0)
 }
}

// ****End shared cookie functions****


// ****Begin code section to update the cookie to ****
// ****add items to the shopping cart cookie 'Scart'.****

// **Global variables.**

var counter = 0
var cookData = ""

// **Extract current value of cookie when page loads **
// **and store the values in the global variables.**

if (getCookieData("Scart")) {
 orderString = getCookieData("Scart")
 cLen = orderString.length
 countEnd = orderString.indexOf("@")
 pointer = countEnd + 1
 counter = orderString.substring(0,countEnd)
 cookData = orderString.substring(pointer,cLen)
}

// **Function to add an item to the shopping cart cookie.**
// **Appends item to end of cookie string and rewrites the cookie

function addItem(num) { 

 a = eval("catalogNum[num]")

 // Get the order quantity requested
 b = parseInt(eval('document.orderform' + num + '.qty' + num + '.value'))

 // Get the available inventory
 c = parseInt(eval("catalogQtyOnHand[num]"))
 //Check how many are already on order
 d = parseInt(checkOnOrder(a));



 if (isNaN(b) || parseInt(b) <= 0) {
   alert("You must select a quantity greater than 0.")
 } else
    {
     if ((d+b) > c) {
       b = c - d;
       if (b<=0) {
	  alert("Your cart already contains the maximum available inventory")
          return
       } else {
       alert("Your order quantity has been reduced to " + b + " bottles due to limited inventory.");
       }
     }
     addCart = '' + a + '-:-'                       //1-Unique Catalog number
     addCart += catalogItemName[num] + '-:-'        //2-Producer name
     addCart += catalogItemDesc[num] + '-:-'        //3-Wine Description
     addCart += catalogPrice[num] + '-:-'           //4-Price
     addCart += b + '-:-'                           //5-Ordered Quantity
     addCart += catalogQtyOnHand[num] + '-:-'       //6-Inventory Quantity
     addCart += catalogWeight[num] + '-:-'          //7-Item Weight
     addCart += catalogDiscountPrice[num] + '-:-^'  //8-Web Sale Price
     cookData += eval("addCart")
     counter++
     setCookieData("Scart", cookData, expdate.toGMTString())
     alert(b + " Item(s) added to shopping cart.")
     //showMe()
    }
}

function checkOnOrder(item) {
 if (getCookieData("Scart")) {
 cookiestring = getCookieData("Scart")

 cookieLen = cookiestring.length
 counteroffset = cookiestring.indexOf("@")
 localcounter = cookiestring.substring(0,counteroffset)
 itemAmt=0
 cookiestring = cookiestring.substring(counteroffset+1,cookieLen)

 

 cookieItems = cookiestring.split("^")
 

 for (i=0; i<localcounter; i++) {
    cookieItemsDetail = cookieItems[i].split("-:-")
    //alert(cookieItemsDetail[0] + " " + cookieItemsDetail[4])
    if(cookieItemsDetail[0] == item) 
	itemAmt += parseInt(cookieItemsDetail[4]);
 }
 return itemAmt;
 }
 return 0;
}

// ****End code section for updating the cookie.****


// ****Debugging function to display cookie contents.****

function showMe() {
 display = getCookieData("Scart");
 alert(display)
}


