/**********************************************
 * Author Gary Argraves - Aug 27, 2007
 *
 * http://www.comptechdoc.org/independent/web/cgi/javamanual/javaarray.html
 * http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array
 * http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:length
 * http://www.mredkj.com/javascript/numberFormat.html
**/

var shopCart_cookieName = domainName + 'shopCartCook'
var shopCart_windowName = domainName + 'shopCartWin';
var itemViewer_winName  = domainName + 'itemViewWin';

var item_delimiter   = '^|';
var field_delimiter  = '~|';

// 'cart_item_list' is used to produce PO in file: checkout.php
var cart_item_list; // holds a semi-colon delimited list of items model numbers;  used to submit order on-line

/* determine sub directory from http root so that https will work. for some reason the site home directory
  needs to be references.
 http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#parallel
 Is it possible to provide HTTP and HTTPS from the same server?
 Yes. HTTP and HTTPS use different server ports (HTTP binds to port 80, HTTPS to port 443),
 so there is no direct conflict between them. You can either run two separate server instances
 bound to these ports, or use Apache's elegant virtual hosting facility to create
 two virtual servers, both served by the same instance of Apache - one responding over HTTP
 to requests on port 80, and the other responding over HTTPS to requests on port 443.
*/

switch (window.location.hostname)
{
/* note: if the shopcartLink uses https protocol then the shopCart_windowName does always use the same window. Sometimes it opens a new window. */

   case 'arraygenetics.com':
            checkoutLink= 'https://arraygenetics.com/checkout.php';
            shopcartLink= 'http://arraygenetics.com/shopcart.php';
            break;

    case 'www.arraygenetics.com':
            checkoutLink= 'https://www.arraygenetics.com/checkout.php';
            shopcartLink= 'http://www.arraygenetics.com/shopcart.php';
            break;

    default:
            checkoutLink='checkout.php';
            shopcartLink='shopcart.php';
            break;
}//sw

// http://lawrence.ecorp.net/inet/samples/regexp-format.php
function ltrim(str)   { return str.replace(/^\s+/, ''); }
function rtrim(str)   { return str.replace(/\s+$/, ''); }
function alltrim(str) { return str.replace(/^\s+|\s+$/g, ''); }

function viewCart()
{
  //alert('hostname='+window.location.hostname+'<end'); //debug
  //alert('shopcartLink='+shopcartLink+'<end'); //debug
  //alert('shopCart_windowName='+shopCart_windowName);

  winHandle=open(shopcartLink, shopCart_windowName, 'height=900, width=850, status=yes, scrollbars=yes, resizable=yes, location=1, menubar=no, directories=yes, toolbar=no');
  winHandle.focus();
}

function isInCart(itemToCheck) // return true if the checkitem is already in the cart
{

  if ( !blockDuplicateCartItems ) return false;

  var cItem = itemToCheck.split(field_delimiter); // parse item fields

  cart = getCookie(shopCart_cookieName);
  // parse out each items on ;
  var items = cart.split(item_delimiter);
  for (var i=0; i<items.length; i++)
  {
    var item = items[i].split(field_delimiter); // parse item fields

    if (    alltrim(item[4]) == alltrim(cItem[4])  // compare the daBase fields
         && alltrim(item[2]) == alltrim(cItem[2]) // compare model no. fields
      )
      return true;
  }
  return false;
}

function addToCart(item)
{
  cart = getCookie(shopCart_cookieName);
  if (!cart) setCookie(shopCart_cookieName, item); // 1st item
  else
  {
    if ( isInCart(item) )
    { var cItem = item.split(field_delimiter); // parse item fields

      alert("Item '"+ cItem[4] +':'+ cItem[2] + "' is already in your shopping cart.");
    }
    else  setCookie(shopCart_cookieName, cart + item_delimiter + item);
  }

  viewCart();
}


function removeItem(itemToRemove)
{
  cart = getCookie(shopCart_cookieName);
  if (!cart) return;

  var items = cart.split(item_delimiter);

  var newcart='';
  var itemCnt=0;
  for (var i=0; i<items.length; i++)
  {
    if (i!=itemToRemove)
    {
      if (itemCnt==0)
           newcart = items[i];
      else newcart = newcart + item_delimiter + items[i];
     itemCnt++;
    }
  }

  setCookie(shopCart_cookieName, newcart);
  viewCart();
}

function openImageWin(dbName, model_no)
{
   // openphotoViewer_win
   var height=650;
   var width=600;
   var winHandle=open('showImg.php?dbName='+dbName+'&model_no='+model_no, itemViewer_winName, 'height='+height+', width='+width+', scrollbars=yes, resizable=yes, location=0, toolbar=0');
   winHandle.focus();
}

function displayShopCart( showButtons, cart_cost_column, cart_total_cost_row, exchange_rate ) // do not show user option buttons on checkout
{
  // JavaScript Function Arguments: Assigning Defaults; URL http://web-graphics.com/mtarchive/001709.php
  // JavaScript Function Arguments: Assigning Defaults; URL http://www.web-graphics.com/mtarchive/001709.php
  var showButtons = (showButtons == null) ? true : showButtons;
  var cart_cost_column = (cart_cost_column == null) ? "Cost USD $" : cart_cost_column;
  var cart_total_cost_row = (cart_total_cost_row == null) ? "Total Cost USD $" : cart_total_cost_row;
  var exchange_rate = (exchange_rate == null) ? 1 : exchange_rate;  // e.g., dollars per Euro's or what ever currency is used

  cart = getCookie(shopCart_cookieName);

  cart_item_list=''; // clear; is global for use in other space

  // test if cart is empty
  if ( !cart )
  {  document.writeln("<h2><font color=red>Your shopping cart is empty.</font></h2>");
     return 0;
  }

  // make a table of cart items
  document.writeln("<table style=\"margin-bottom:10;margin-top:6;\" border=0 cellpadding=5 cellspacing=1 bgcolor=white>");
  document.writeln("<tr bgcolor=#f0f0f0><td width=140><!--Picture-->&nbsp;</td> <td width=230>Item Description</td> <td width=80>dBase : Item No.</td> <td width=90>"+cart_cost_column+"<!--Cost USD $--></td> </tr>");

  // parse out each items on ;
  var items = cart.split(item_delimiter);
  // NOTE: DO NOT SORT ELSE REMOVE FUNCTION DOES NOT WORK
  var total_cost=0;
  var i;
  for (i=0; i<items.length; i++)
  {
    document.write("<tr valign=top bgcolor=white ");
    if (!(i%2)) // odd even
          document.writeln("class=alt1>");
    else  document.writeln("class=alt2>");

    var item = items[i].split(field_delimiter); // parse item fields

    var model_no = alltrim( item[2] );
    var dbName   = alltrim( item[4] );

    // ndx=1  Item image or photo
    if (unscaled_thumbnails)
    { document.writeln( "<td><a href=\"javascript: openImageWin( '", dbName, "', '", model_no, "' );\">");
      document.writeln( "<img src=\"images/", alltrim(item[1]), "\" border=1></a></td>");
    }
    else
    { VpicFlag = alltrim( item[5] ); // the Vertical Pic Flag has its own field
      var width =64;
      var height=48;
      if ( VpicFlag == '1' ) { width=48; height=64; }
      document.writeln( "<td><a href=\"javascript: openImageWin( '", dbName, "', '", model_no, "' );\">");
      document.writeln( "<img src=\"images/", alltrim(item[1]), "\" border=1 width=",width," height=",height,"></a></td>");
    }

    // ndx=0  Item Description
    document.writeln('<td>', item[0], "&nbsp;&nbsp;&nbsp;&nbsp; <a href=\"javascript: openImageWin( '", dbName, "', '", model_no, "' );\">");
    document.writeln("<span><img border=0 style=margin-top:8; src=\"estore/images/camera2.jpg\"><font size=2>&nbsp;View&nbsp;all</font></span>");
    document.writeln("</a></td>");

    // ndx=2  item model no, link back to parent page to open the item photo page
    //document.writeln( "<td><a href=\"javascript: openImageWin( '", dbName, "', '", model_no, "' );\">", item[2], "</a></td>" );
    document.writeln( "<td>", dbName, ' : ', model_no);
    // remove item from cart
    document.writeln("<br><a href=\"javascript:removeItem(",i,");\"><img style=margin-top:8; src=estore/images/remove.jpg border=0><font size=2>&nbsp;Remove</font></a></td>");

    // ndx=3  cost of item
    price = parseFloat(item[3]);
    price/=exchange_rate;
    price = Math.round(price*100)/100 ;
    document.writeln('<td align=right>', price.toFixed(2), '</td>');

    document.writeln("</tr>");
    //total_cost += parseFloat(item[3]); // in default currency US Dollars
    total_cost += price; // in requested currency

    // append to cart item list string
    cart_item_list += items[i]+';';
  }

  //cart_item_list += 'Total Cost USD $'+total_cost.toFixed(2)+';'; // in default currency US Dollars
  cart_item_list += cart_total_cost_row + total_cost.toFixed(2)+';'; // in requested currency

  document.writeln("<tr align=right bgcolor=#f0f0f0><td colspan=3 align=right>"+cart_total_cost_row+"<!--Total Cost USD $--></td><td>",total_cost.toFixed(2),"</td></tr>");
  document.writeln("</table>");

  if (i && showButtons)
  {
    document.writeln("<input type=button class=widemenuButton value=\"Empty Cart\" onclick=\"javascript:deleteCookie(shopCart_cookieName); viewCart();\">");
    //if (i)
      document.writeln("<input type=button class=widemenuButton value=\"Checkout\" onclick=\"javascript:window.location=checkoutLink;\">");
  }

  return i;
}

