/* HRCart Supporting Javascript */

function GetSimplePrice(complexprice)
{
   var simpleprice = new RegExp('[0-9]+([.][0-9]{2})*', '');
   
   return (simpleprice.exec(complexprice)[0]);
}

function GetComplexPrice(simpleprice, fullcurrency)
{
   var decimalcheck = new RegExp('[.][0-9]*', '');

   var fullprefix = (fullcurrency ? "Total:&nbsp;&nbsp;&nbsp;CAD" : "");
   
   if (decimalcheck.test(simpleprice))
   {
      return fullprefix + "$" + simpleprice;
   } else {
      return fullprefix + "$" + simpleprice + ".00";
   }
}

function GetCookie(cookieName)
{
   if (document.cookie.length > 0)
   {
      cookieStart = document.cookie.indexOf(cookieName + "=");
      if (cookieStart != -1)
      {
         cookieStart = cookieStart + cookieName.length + 1;
         cookieEnd = document.cookie.indexOf(";", cookieStart);
         
         if (cookieEnd == -1)
         {
            cookieEnd = document.cookie.length;
         }
         
         return unescape(document.cookie.substring(cookieStart, cookieEnd));
      }
   }
   return "";
}

function BackgroundUpdateCart(serializedProducts)
{
   if (window.XMLHttpRequest)
   {  // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
   } else { // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   
   if (hrCartID == "")
   {
      hrCartID = GetCookie("HRCART");
   }
   
   //window.alert(hrCartID);
   //window.alert(serializedProducts);

   xmlhttp.onreadystatechange=function()
      {
         if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
         {
            var responseText = xmlhttp.responseText;
         
            //window.alert("Background update cart result: " + responseText);
            
            if (responseText.substr(0, 3) == "Ok:")
            {
               var qtyItems = responseText.substr(3);
            
               if (!isNaN(qtyItems) && (qtyItems > 0))
               {
                  $("#HeaderShoppingCartLink").html("Shopping Cart (" + qtyItems + " items)");
               } else {
                  $("#HeaderShoppingCartLink").html("Shopping Cart");
               }
            }
         }
      }

   xmlhttp.open("GET","cart.php?BackgroundUpdateCart=1&FormPosted=1&CurrStep=1&CartID=" + hrCartID + "&SerializedProducts=" + serializedProducts,true);
   xmlhttp.send();
}

/*

- functions modify the cart array
- functions call out to serialize/deserialize
- functions call out for AJAX cart updating

function AddItemToCart
function RemoveItemFromCart
function EmptyCart
function UpdateQuantity
function UpdateCart
function DeserializeCartAndDisplay
function SerializeCart
*/


var hrCartID = "";

var hrCartSerialized = "";

var hrCart = new Array();

var hrCatalog = new Array();

var cartToDisplayMapping = new Array();
var totalItemsInserted = 0;

var totalPrice = 0;

var cartLineCount = 0;


function AddItemToCatalog()
{
}

function AddLineToDisplayCart()
{
   var newLine = $('#cart_line_template').clone();
   
   $(newLine).attr("id", "cart_line_actual_" + cartLineCount);
   cartLineCount++;
   
   return newLine;
}

function SetDisplayCartLineDesc(cartLine, value)
{
   $(cartLine).children('.cart_item').slice(0, 1).html(value);
}

function SetDisplayCartLineQty(cartLine, value)
{
   $(cartLine).children('.cart_item').slice(1, 2).children("select").val(value);
}

function SetDisplayCartLinePrice(cartLine, value)
{
   $(cartLine).children('.cart_item').slice(2, 3).html(value);
}

function SetDisplayCartLineSubtotal(cartLine, value)
{
   $(cartLine).children('.cart_item').slice(3, 4).html(value);
}

function SetDisplayCartLineHidden(cartLine, value)
{
   $(cartLine).children('.cart_item').slice(5, 6).html(value);
}

function GetDisplayCartLineDesc(cartLine)
{
   return $(cartLine).children('.cart_item').slice(0, 1).html();
}

function GetDisplayCartLineQty(cartLine)
{
   return $(cartLine).children('.cart_item').slice(1, 2).children("select").val();
}

function GetDisplayCartLinePrice(cartLine)
{
   return $(cartLine).children('.cart_item').slice(2, 3).html();
}

function GetDisplayCartLineSubtotal(cartLine)
{
   return $(cartLine).children('.cart_item').slice(3, 4).html();
}

function GetDisplayCartLineHidden(cartLine)
{
   return $(cartLine).children('.cart_item').slice(5, 6).html();
}

function UpdateDisplayCartTotal()
{
//   window.alert(totalPrice);

   if (totalPrice > 0)
   {
      $("#prod_total_cell_desc").html("Total");
      $("#prod_total_cell").html(GetComplexPrice(totalPrice, true));
      $("#prod_cart_empty").html("&nbsp;");
      $("#button_buy_now").show();
      $("#prod_emptycart_cell").show();
   } else {
      $("#prod_total_cell").html("&nbsp;");
      $("#prod_cart_empty").html("Your shopping cart is currently empty.");
      $("#button_buy_now").hide();
      $("#prod_emptycart_cell").hide();
   }
}

function AddItemToDisplayCart(immediate, itemArrCounter, pn, desc, qty, price)
{
   var newLine = AddLineToDisplayCart();
   
   SetDisplayCartLineDesc(newLine, desc);
   SetDisplayCartLineQty(newLine, qty);
   SetDisplayCartLinePrice(newLine, GetComplexPrice(price, false));
   SetDisplayCartLineSubtotal(newLine, GetComplexPrice(price * qty, false));
   SetDisplayCartLineHidden(newLine, itemArrCounter);
   
   // insert and make visible
   $('#cart_line_template').after(newLine);
   if (immediate)
   {
      newLine.show(0);
   } else {
      newLine.slideDown('fast');
   }
   
   UpdateDisplayCartTotal();
}

function AddItemToCart(postUpdate, immediate, pn, desc, qty, price)
{
   hrCart.push(new Array(pn, qty, price, totalItemsInserted));
   
   totalPrice += price * qty;
   
   SerializeCart();
   if (postUpdate)
   {
      UpdateCart();
   }
   
   AddItemToDisplayCart(immediate, totalItemsInserted, pn, desc, qty, price);
   
   totalItemsInserted++;
}

function AddItemToCartSimple(postUpdate, immediate, pn, qty)
{
   var itemInfo = GetItemInfo(pn);

   if (itemInfo)
   {
      AddItemToCart(postUpdate, immediate, pn, itemInfo[2], qty, itemInfo[1]);
   }
}

function SetItemByInsertedIndex(itemsInsertedIndex, hrCartItem)
{
   $.each(hrCart, function(index, value) {
      if (value[3] == itemsInsertedIndex)
      {
         $.each(value, function(index, value) {
            value = hrCartItem[index];
         });
      }
   });
}

function GetItemByInsertedIndex(itemsInsertedIndex)
{
   return $.grep(hrCart, function(value) { return value[3] == itemsInsertedIndex })[0];
}

function RemoveItemByInsertedIndex(itemsInsertedIndex)
{
   hrCart = $.grep(hrCart, function(value) { return value[3] != itemsInsertedIndex });
}

function RemoveItemFromCart(postUpdate, itemsInsertedIndex)
{
   // retrieve the item based on the stored index
   var hrCartItem = GetItemByInsertedIndex(itemsInsertedIndex);

//   window.alert(hrCartItem);
   
   // subtract price * qty from overall total
   totalPrice -= hrCartItem[1] * hrCartItem[2];
   
   // remove the item based on the stored index
   RemoveItemByInsertedIndex(itemsInsertedIndex);
   
   SerializeCart();
   if (postUpdate)
   {
      UpdateCart();
   }
}

function RemoveItemFromDisplayCart(postUpdate, cartLine)
{
   // normalize
   cartLine = $(cartLine).closest('.cart_line');

   RemoveItemFromCart(postUpdate, GetDisplayCartLineHidden(cartLine));

   $(cartLine).remove();
   
   cartLineCount--;
   
   UpdateDisplayCartTotal();
}

function EmptyCart()
{
   if (window.confirm("Are you sure you want to empty your shopping cart?"))
   {
      $("[id^=cart_line_actual_]").each(function(index, value) {
         RemoveItemFromDisplayCart(false, value);
      });
      UpdateCart();
   }
}

function UpdateDisplayCartQuantity(postUpdate, cartLine)
{
   // normalize
   cartLine = $(cartLine).closest('.cart_line');
   
   var newSubtotal = UpdateCartQuantity(postUpdate, GetDisplayCartLineHidden(cartLine), GetDisplayCartLineQty(cartLine));
   
   SetDisplayCartLineSubtotal(cartLine, GetComplexPrice(newSubtotal, false));
   
   UpdateDisplayCartTotal();
}

function UpdateCartQuantity(postUpdate, itemsInsertedIndex, newQty)
{
   // retrieve the item based on the stored index
   var hrCartItem = GetItemByInsertedIndex(itemsInsertedIndex);

//   window.alert(hrCartItem);
   
//   window.alert(totalPrice);
   
   // subtract old qty * price from overall total
   totalPrice -= hrCartItem[1] * hrCartItem[2];
   
//   window.alert(totalPrice);
   
   // new subtotal is new qty * price
   var newSubtotal = newQty * hrCartItem[2];
   
   // add new new subtotal (new qty * price) to overall total
   totalPrice += newSubtotal;

   // update the cart array
   hrCartItem[1] = newQty;
   SetItemByInsertedIndex(itemsInsertedIndex, hrCartItem);
   
//   window.alert(totalPrice);
   
   SerializeCart();
   if (postUpdate)
   {
      UpdateCart();
   }
   
   return newSubtotal;
}

function UpdateCart()
{
   BackgroundUpdateCart(hrCartSerialized);
}

function DeserializeCartAndDisplay()
{
   hrCartSerialized = $("input[name*=SerializedProducts]").val();
   
   //window.alert("hrCartSerialized:" + hrCartSerialized);
   
   // if not on the form, check the cookie
   if (!hrCartSerialized || (hrCartSerialized == ""))
   {
      hrCartSerialized = unescape(GetCookie("HRCART_SERIALIZEDCART"));
      
      //window.alert("(from cookie) hrCartSerialized:" + hrCartSerialized);
   }
   
   if (hrCartSerialized != "")
   {
      var cartItems = hrCartSerialized.split(";");
      
      //window.alert(cartItems);
      //window.alert(cartItems[0]);
      //window.alert(cartItems.length);
      
      for (var i = 0; i < cartItems.length; i++)
      {
         var cartItem = cartItems[i];
      
         //window.alert(cartItem);
         
         var itemFields = cartItem.split(":");
         
         //window.alert(itemFields[0]);
         //window.alert(itemFields[1]);
         //window.alert(itemFields[2]);
         
         //var pnFields = DecodePN(itemFields[0]);

         //window.alert(pnFields);
         
         // AddPaddle(ppaddle, pprice, pqty, phandle, plength, immediate)      
         //AddPaddle(false, pnFields[1], itemFields[2], itemFields[1], pnFields[2], pnFields[0], true);
         
         var itemInfo = GetItemInfo(itemFields[0]);

         if (itemInfo)
         {
            // AddItemToCart(postUpdate, immediate, pn, desc, qty, price)
            AddItemToCart(false, true, itemFields[0], itemInfo[2], itemFields[1], itemInfo[1]);
         }
      }
   }
}

function GetItemInfo(pn)
{
   for (i = 0; i < productCatalog.length; i++)
   {
      if (productCatalog[i][0] == pn)
      {
         return productCatalog[i];
      }
   }

   return false;
}

function GetItemPrice(pn)
{
   var itemInfo = GetItemInfo(pn);
   
   if (itemInfo)
      return itemInfo[1];
   else
      return "";
}

function GetItemDesc(pn)
{
   var itemInfo = GetItemInfo(pn);
   
   if (itemInfo)
      return itemInfo[2];
   else
      return "";
}

function WriteItemPrice(pn)
{
   document.write(GetItemPrice(pn));
}

function WriteItemDesc(pn)
{
   document.write(GetItemDesc(pn));
}

function SerializeCart()
{
   hrCartSerialized = "";

   $.each(hrCart, function(index, value) {
      hrCartSerialized += value.slice(0, 3).join(":") + ";";
   });
   
   $("input[name*=SerializedProducts]").val(hrCartSerialized);
}

function WriteSelect(selId, min, max)
{
   if ((min < 0) || (max < min) || (max > 1000))
   {
      return;
   }

   document.writeln("<select class='product1' id='" + selId + "'>");
   for (var i = min; i <= max; i++)
   {
      document.writeln("<option>" + i + "</option>");
   }
   document.writeln("</select>");
}

function WriteSelectInnards(min, max)
{
   if ((min < 0) || (max < min) || (max > 1000))
   {
      return;
   }

   for (var i = min; i <= max; i++)
   {
      document.writeln("<option>" + i + "</option>");
   }
}

function WriteShoppingCart()
{
   document.writeln("<div class=\"shopping_cart_container\">");
   document.writeln("<div class=\"main_title\"><h4>Your Shopping Cart</h4></div>");
   document.writeln("<div class=\"cart_line\">");
   document.writeln("   <div class=\"cart_item one\">Description</div>");
   document.writeln("   <div class=\"cart_item four\">Quantity</div>");
   document.writeln("   <div class=\"cart_item five\">Unit Price</div>");
   document.writeln("   <div class=\"cart_item six\">Subtotal</div>");
   document.writeln("</div>");
   document.writeln("<div class=\"cart_line\" id=\"cart_line_template\" style=\"display: none;\">");
   document.writeln("   <div class=\"cart_item one\"></div>");
   document.writeln("   <div class=\"cart_item four\"><select class=\"cart\" name=\"ProdLineQtyNew\" onchange=\"UpdateDisplayCartQuantity(true, this);\">");
   document.writeln("         <option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option>");
   document.writeln("         <option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option><option>17</option><option>18</option><option>19</option><option>20</option>");
   document.writeln("         <option>21</option><option>22</option><option>23</option><option>24</option><option>25</option><option>26</option><option>27</option><option>28</option><option>29</option><option>30</option>");
   document.writeln("         <option>31</option><option>32</option><option>33</option><option>34</option><option>35</option><option>36</option><option>37</option><option>38</option><option>39</option><option>40</option>");
   document.writeln("         <option>41</option><option>42</option><option>43</option><option>44</option><option>45</option><option>46</option><option>47</option><option>48</option><option>49</option><option>50</option>");
   document.writeln("      </select></div>");
   document.writeln("   <div class=\"cart_item five\"></div>");
   document.writeln("   <div class=\"cart_item six\"></div>");
   document.writeln("   <div class=\"cart_item seven\"><span onclick=\"RemoveItemFromDisplayCart(true, this);\" style=\"cursor:pointer;color:#0a7bc1;\">Remove</span></div>");
   document.writeln("   <div class=\"cart_item eight\"></div>");
   document.writeln("</div>");
   document.writeln("<div class=\"cart_line total\">");
   document.writeln("   <div class=\"cart_item total\" id=\"prod_total_cell\">&nbsp;</div>");
   document.writeln("   <div class=\"cart_item seven\" id=\"prod_emptycart_cell\" style=\"display:none;\"><span onclick=\"EmptyCart();\" style=\"cursor:pointer;color:#0a7bc1;\">Empty</span></div>");
   document.writeln("</div>");
   document.writeln("<p id=\"prod_cart_empty\">Your shopping cart is currently empty.</p>");
   document.writeln("<button type=\"button\" name=\"Purchase\" id=\"button_buy_now\" style=\"display:none;\" class=\"hrbutton\" onclick=\"DoBuyNow();\">Check Out</button>");
   document.writeln("   </div>");
}

function DoBuyNow()
{
   //window.alert("cart.php?FormPosted=1&CurrStep=1&NextStep=2");
   window.location.assign("cart.php?FormPosted=1&CurrStep=1&NextStep=2");
   //window.location.assign("cart.php?FormPosted=1&CurrStep=1&NextStep=2&CartID=" + hrCartID + "&SerializedProducts=" + hrCartSerialized);
}

// pre-populate the cart once the document is loaded
$(document).ready(function() {
   DeserializeCartAndDisplay();
});

