var saleTotal;
var prevQty = 0;
var arrowUp;
var arrowDown;
var defaultRowHeight = 127;
var noPicsTextRowHeight = 33;
var qtyCellIndex = 1;
var startTop;
var intervalID;
var currImageID = 0;
var imageCount;
var adRotatorClientID;
var WebMenuAdDivClientID;
var WebMenuAdQtyTextClientID;
var WebMenuAdTotalTextClientID;


function clientCallback(result, context)
{
   if (result != '')
   {
    var resultData = result.split(',');
    var totalItemsTextBox = document.getElementById(totalItemsTextBoxClientID);
    var totalPriceTextBox = document.getElementById(totalPriceTextBoxClientID);
    
    totalItemsTextBox.value = resultData[0];
    totalPriceTextBox.value = resultData[1];
   }
}
    
function clientErrorCallback(error, context)
{
 alert(error);
}

function productCheckBoxClicked(chkbox, stocknumber)
{
 var args = '';
 if (chkbox.checked)
 {
  args += stocknumber + ',1';
 }
 else
 {
  args += stocknumber + ',0';
 }
 getProductData(args, "this");
}

function changeQuantity(cell, increment, stocknumber)
{
 var qtyCell = document.getElementById(cell);
 var iQty = qtyCell.textContent ? parseInt(qtyCell.textContent) : parseInt(qtyCell.innerText);
 var args = '';
 if (increment)
 {
  iQty++;
 }
 else
 {
  if (iQty > 0)
  {
   iQty--;
  }
 }
 qtyCell.innerText = iQty;
 if (qtyCell.textContent)
 {
  qtyCell.textContent = iQty;
 }
 args += stocknumber + ',' + iQty;
 getProductData(args, this);
}

function addProductToCart(cell, stocknumber)
{
 var qtyCell = document.getElementById(cell);
 
 var iQty = qtyCell.textContent ? parseInt(qtyCell.textContent) : parseInt(qtyCell.innerText);
 
}

function removeProductFromCart(cell, stocknumber)
{
 var qtyCell = document.getElementById(cell);
 var args = '';
 qtyCell.innerText = 0;
 if (qtyCell.textContent)
 {
  qtyCell.textContent = 0;
 }
 args += stocknumber + ',0';
 getProductData(args, this);
}

   
function startTimer(timerSeconds, adRotatorID)
{
 adRotatorClientID = adRotatorID;
 imageCount = imageList.length;
 var objAdRotator = document.getElementById(adRotatorClientID);
 if (objAdRotator)
 {
  objAdRotator.src = imageList[currImageID];
  objAdRotator.alt = imageAltTextList[currImageID];
  intervalID = setInterval("swapBannerAd()", timerSeconds * 1000);
  if (document.getElementById(WebMenuAdDivClientID) != null)
  {
   getStartPositionForTotals();
  }
 }
}
  
function swapBannerAd()
{
 currImageID++;
 if (currImageID >= imageCount)
 {
  currImageID = 0;
 }
 var objAdRotator = document.getElementById(adRotatorClientID);
 objAdRotator.src = imageList[currImageID];
 objAdRotator.alt = imageAltTextList[currImageID];
}
  
function setImageClicked()
{
// alert('SETIMAGECLICKED');
 var objAdRotator = document.getElementById(adRotatorClientID);
 var imgClicked = document.getElementById(imageClickedClientID);
 imgClicked.value = objAdRotator.src;
}

function getStartPositionForTotals()
{
// startTop = document.getElementById(WebMenuAdDivClientID).offsetTop;
}

function scrollTotals()
{
 // Last "working" (IE) version of code
// var objMenuAd = document.getElementById(WebMenuAdDivClientID);
// var detect = navigator.userAgent.toLowerCase();
// if (document.documentElement.scrollTop)
// {
//  currentTop = document.documentElement.scrollTop;
// }
// if (currentTop > startTop)
// {
//  alert(currentTop);
//  objMenuAd.style.top = currentTop + 8;
// }
// else
// {
//  objMenuAd.style.top = startTop;
// }

// OLD   
// alert(WebMenuAdDivClientID);
// var objMenuAd = document.getElementById(WebMenuAdDivClientID);
// var detect = navigator.userAgent.toLowerCase();
 //var currentTop = detect.indexOf('msie') > -1 ? document.body.scrollTop : window.pageYOffset;
// var currentTop = objMenuAd.offsetTop;
// if (document.documentElement.scrollTop)
// {
//  currentTop = document.documentElement.scrollTop;
// }
// alert('WebMenuAd Control Pos: ' + objMenuAd.style.top);
// alert('Current: ' + currentTop);
// alert('Start: ' + startTop); 
// if (currentTop > startTop)
// {
//  alert(currentTop);
//  objMenuAd.style.top = currentTop + 8;
// }
// else
// {
//  objMenuAd.style.top = startTop;
// }
}
  
function clickButton(e, buttonid)
{ 
 var bt = document.getElementById(buttonid); 
 if (typeof bt == 'object')
 { 
  if(navigator.appName.indexOf("Netscape")>(-1))
  { 
   if (e.keyCode == 13)
   { 
	bt.click(); 
    return false; 
   } 
  } 

  if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
  { 
   if (event.keyCode == 13)
   { 
    bt.click(); 
    return false; 
   } 
  } 
 } 
} 
  
function activateStartCell(gn)
{
 var row = igtbl_getRowById(gn + 'rc_0_0');
 row.getCell(1).activate();
 row.getCell(1).beginEdit();
}

function afterEnterEdit(gn, cellid)
{
// alert(gn);
 if (gn.indexOf('grdCatalog') == -1)
 {
  qtyCellIndex = 2;
 }
 var row = igtbl_getRowById(cellid);
 var cell = row.getCell(qtyCellIndex);
 prevQty = cell.getValue();
}

function beforeEdit(gridname, cellid)
{
 var col = igtbl_getColumnById(cellid);
 if (col.Key != "Quantity" && col.Key != "StoryText")
 {
  return true;
 }
}

function beforeExitEditModeHandler(gridName, cellId, newValue)
{
 if (gridName.indexOf('grdCatalog') == -1)
 {
  qtyCellIndex = 2;
 }
 var sQty = newValue;
// alert(sQty);
 var row = igtbl_getRowById(cellId);
 var cell = row.getCell(qtyCellIndex);
// alert(sQty);
// cell.setValue(sQty);
 
 var sPriceField;
// var row = igtbl_getRowById(cellId);
// var cell = row.getCell(qtyCellIndex);
// var sQty = cell.getValue();
 var iQty = parseInt(sQty, 10);
 var col = igtbl_getColumnById(cellId);
 if (col.Key != "Quantity")
 {
  return false;
 }
 var iOldQty = parseInt(prevQty, 10);
 var totalItemsTextBox = document.getElementById(totalItemsTextBoxClientID);
 var totalPriceTextBox = document.getElementById(totalPriceTextBoxClientID);
 var menuAdQtyTextBox = document.getElementById(WebMenuAdQtyTextClientID);
 var menuAdTotalTextBox = document.getElementById(WebMenuAdTotalTextClientID);
 var iCount = parseInt(totalItemsTextBox.value, 10);
 sPriceField = gridName.indexOf('grdCatalog') != -1 ? "DisplayPrice" : "DiscountPrice";
// sPriceField = "DisplayPrice";
 if (row.getCellFromKey(sPriceField) == null)
 {
  sPriceField = gridName.indexOf('grdCatalog') != -1 ? "LateDisplayPrice" : "LateDiscountPrice";
 }
			   
 if (isNaN(iOldQty))
 {
  iOldQty = 0;
 }   
 // alert('iCount = ' + iCount);
 // alert('iQty = ' + iQty);
 // alert('iOldQty = ' + iOldQty);
 var iNewCount = (iCount + iQty) - iOldQty;
 // alert('iNewCount = ' + iNewCount);
 totalItemsTextBox.value = menuAdQtyTextBox.value = iNewCount;
 

 var totalPrice = totalPriceTextBox.value;
 totalPrice = totalPrice.split("$");
 saleTotal = parseFloat(totalPrice[1]);
 var fTotalSale = parseFloat(saleTotal);
 var fItemPrice = row.getCellFromKey(sPriceField).getValue();
 var fNewTotal = round(iQty * fItemPrice);
 var fOldTotal = round(iOldQty * fItemPrice);
 fTotalSale -= fOldTotal;
 fTotalSale += fNewTotal;
 saleTotal = formatCurrency(round(fTotalSale));
 totalPriceTextBox.value = menuAdTotalTextBox.value = "$ " + saleTotal;
 return false;
}


function trimLeadingZeros(s)
{
 var i = 0;
 var qty = '';
 while (i < s.length)
 {
  if (s.charAt(i) != '0')
  {
   qty = s.substring(i, s.length);
   break;
  }
  else
  {
   i++;
  }
 }
 return qty;
}
  
function afterCellUpdate(gridName, cellId)
{
 if (gridName.indexOf('grdCatalog') == -1)
 {
  qtyCellIndex = 2;
 }
 var row = igtbl_getRowById(cellId);
 var cell = row.getCell(qtyCellIndex);
 var sQty = trimLeadingZeros(cell.getValue());
 cell.setValue(sQty);
 return false;
}

function displayProductInfoWindow(stockNumber)
{
 var winHeight = 315;
 var winWidth = 475;
 var leftPos = ((screen.width / 2) - (winWidth / 2));
 var topPos = ((screen.height / 2) - (winHeight / 2));
 var win = window.open("displayproductinfo.aspx?StockNumber=" + stockNumber,
                       "StoryText", "resizable=no,top=" + topPos + ",height=" + winHeight + ",left=" + leftPos + ",width=" + winWidth);
}

function formatCurrency(amount)
{
 return (amount == Math.floor(amount)) ? amount + '.00' :
        ((amount * 10 == Math.floor(amount * 10)) ? amount + '0' : amount);
}
  
function gridCellClick(gridName, cellid, button)
{ 
 var row = igtbl_getRowById(cellid);
 var col = igtbl_getColumnById(cellid);
 if (col.Key != "ItemPicture")
 {
  return true;
 }
 if (row.getCellFromKey('HasPictures').getValue() != 0)
 {
  var sLargePicsURL = "http://www.mmcomics.com/pics/" +
       row.getCellFromKey('ShipYearMonth').getValue() + "/big/";
  var sFullStockNum = row.getCellFromKey('StockNumber').getValue();
  var pic = sLargePicsURL + sFullStockNum.substring(5, 9) + ".jpg";  
  window.open("popup.htm?" + pic,"", "resizable=1,height=600,width=400");
 }
} 
  
function displayLargePic(shipYearMonth, stockNumber)
{ 
 var sLargePicsURL = "http://www.mmcomics.com/pics/" + shipYearMonth + "/big/";
 var pic = sLargePicsURL + stockNumber + ".jpg";  
 window.open("popup.htm?" + pic,"", "resizable=1,height=600,width=400");
} 
    
function qtyFieldKeyHandler(gn, cellid, keycode)
{
 var backSpaceKey = 8;
 var upArrowKey = 38;
 var downArrowKey = 40;
 var tabKey = 9;
 if (gn.indexOf('grdCatalog') == -1)
 {
  qtyCellIndex = 2;
 }
 var row = igtbl_getRowById(cellid);
 var col = igtbl_getColumnById(cellid);
 var cell = row.getCell(qtyCellIndex);
 var cindex = col.Index;

 if ((!cell.getValue()) || (cell.getValue() == ""))
 {
  cell.setValue(0);
 } 
 var detect = navigator.userAgent.toLowerCase();
 switch (keycode)
 {
  case tabKey       : cell.endEdit(true);
                      return false;
  case upArrowKey   : cell.endEdit(true);
                      var prevRow = cell.Row.getPrevRow();
                      if (prevRow)
                      {
                       var prevCell = prevRow.getCell(cell.Index);
                       prevCell.activate();
                       prevCell.beginEdit();
                      }
//                      else
//                      {
//                       alert('prevrow = null');
//                      }
                      return detect.indexOf('msie') == -1;
  case downArrowKey : cell.endEdit(true);
                      var nextRow = cell.Row.getNextRow();
                      if(nextRow)
                      {
                       var nextCell=nextRow.getCell(cell.Index);
                       if(nextCell)
                       {
                        nextCell.activate();
                        nextCell.beginEdit();
                       }
//                       else
//                       {
//                        alert('nextCell = null');
//                       }
                      }
//                      else
//                      {
//                       alert('nextrow = null');
//                      }
                      return detect.indexOf('msie') == -1;
  case backSpaceKey : return false;
  default           : if ((keycode >= 48 && keycode <= 57) ||
                          (keycode >= 96 && keycode <= 105))
                      {
                       return false;
                      }
                      else
                      {
                       return true;
                      }
 }
}
  
function round(number, x)
{
 x = (!x ? 2 : x);
 return Math.round(number * Math.pow(10, x)) / Math.pow(10, x);
}