function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages()
{ //v3.0
  var d=document;
  if(d.images)
  {
    if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
    for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0)
    {
      d.MM_p[j]=new Image;
      d.MM_p[j++].src=a[i];
    }
  }
}

function MM_findObj(n, d)
{ //v4.01
  var p,i,x;
  if(!d) d=document;
  if((p=n.indexOf("?"))>0&&parent.frames.length)
  {
    d=parent.frames[n.substring(p+1)].document;
    n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n];
  for(i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++)
     x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n);
  return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null)
  {
    document.MM_sr[j++]=x;
    if(!x.oSrc) x.oSrc=x.src;
    x.src=a[i+2];
  }
}

function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}

function MM_openBrWindow(theURL,winName,features)
{ //v2.0
  window.open(theURL,winName,features);
}

function CPO_getParam( name )
{
  var r = new RegExp( '[?&]'+name+'=([^&]+)' );
  var a = r.exec( window.location.search );
  return null != a && 2 == a.length ? a[1] : null;
}

function CPO_rollover( n, c )
{
  var o = MM_findObj(n);
  if( null != o ) o.className = c;
}

function CPO_setCookie( /* url, rgb */ )
{
  var a = CPO_setCookie.arguments;
  var ref = CPO_getParam( 'ref' );
  if( null != ref && 0 < ref.length ) document.write(
     '<'+'img src="'+a[0]+'?ref='+ref+
     (1<a.length?'&rgb='+a[1]:'')+
     '" width=1 height=1'+'>' );
}

function cpo_go_link( href, addins )
{
  var r = /[?&]([^=]+)=([^&]+)/g; var rstring; 
  var qvars = new Object();       var rvals = new Array();
  while (a = r.exec( window.location.search ) )
    qvars[ a[1] ] = a[2];
  for(j in addins) qvars[j] = addins[j];
  for(k in qvars) rvals.push( k + "=" + qvars[k]); 
  var vs = href + "?" + rvals.join("&").replace(/\s/g, "+");
//alert( vs );
  window.location.replace( vs );
}

function cpo_self_link( addins )
{
  var self = window.location.href.split("?");
  cpo_go_link( self[0], addins );
}

function cpo_go_to_compare()
{
  var vars = new Object; vars['compare'] = carry_chkd(); 
  cpo_go_link("http://www.cpomakita.com/search_comparison.php", vars); 
}

function cpo_back_to_search()
{
  var vars = new Object; // TODO we shouldn't have to pass an object 
  cpo_go_link("http://www.cpomakita.com/search.php", vars); 
}

function cpo_go_to_page( page )
{ 
  var vars = new Object; vars['page'] = page; vars['compare'] = carry_chkd(); 
  cpo_self_link(vars); 
}

function find_checked() 
{
  fm = document.forms["compare"].elements; var chkd = new Array();
  for(i=0;i<fm.length;i++) { 
    chk = fm[i]; if(chk.checked == true) chkd.push(chk.id);
  } return chkd;
}

function carry_chkd() 
{
  var master = new Object; var tot = new Array(); var chkd = find_checked(); 
  var old = CPO_getParam("compare") ? CPO_getParam("compare").split(":") : "";
  for(i=0;i<old.length ;++i) master[ old[i]  ] = 1;
  for(i=0;i<chkd.length;++i) master[ chkd[i] ] = 1;
  for(k in master) tot.push(k);  
  return tot.join(":");
}

function do_check_boxes()
{
  fm = document.forms["compare"]; 
  var old = CPO_getParam("compare") ? CPO_getParam("compare").split(":") : "";
  for(i=0;i<old.length;++i) 
   if(fm[ old[i] ]) fm[ old[i] ].checked = true; 
}

function compare_remove( chk )
{
  var vars = new Object; var tot = new Array();
  var old = CPO_getParam("compare") ? CPO_getParam("compare").split(":") : "";
  for(i=0;i<old.length;++i)
    if( old[i] != chk.name ) tot.push(old[i]);  
  vars['compare'] = tot.join(":");
  cpo_self_link(vars);
}

function start_cpo_js()
{
  do_check_boxes();
}

function submitenter(myfield,e)
{
 var keycode;
 if (window.event) keycode = window.event.keyCode;
 else if (e) keycode = e.which;
 else return true;
if (keycode == 13) // the user hits enter
   { myfield.form.submit(); return false; }
else
   return true;
}
/** Code Specific to yahoo shopping cart**/
var CPOshopping = "makiProdShoppingCart";
var CPOshoppingOld = CPOshopping+'Old';
var CPOCheckOut = CPOshopping+'CHECKOUT';

/** Can only serialize strings **/
function cerialize(obj)
{
  if(!obj) return false;
  
  var stuff = '';
  for(var i=0;i<obj.length;i++)
  {
    var item = obj[i].join(';');
    stuff += item;
    if(i<obj.length-1) stuff +='|';
  }  
  return stuff;
}
/** Convert string back to array **/
function decerialize(obj)
{
  if(!obj) return false;
  var result = Array();
  var obj = obj.split('|');
  for(var i=0;i<obj.length;i++)
  {
    result[i] = obj[i].split(';');
  }
  return result;
}

function onlyGetProduct(some_array)
{
  omni_prods = '';
  pfc = some_array;
  for(var i=0;i<pfc.length;i++)
  {
    var item = pfc[i][0].replace(/^\s+/, '');//only get product title
    omni_prods += ';'+item;
    if(i<pfc.length-1) omni_prods+=',';
  }
  return omni_prods;
}
//returns false if they are not identical..
//only checks to make sure that the products have not changed
//other quantities may change at will
function compare(obj_org,obj_new)
{
  if(obj_org.length != obj_new.length) return false;
  else
  {
    for(var i=0;i<obj_org.length;i++)
    {
      in_new = false
      for(var j=0;j<obj_new.length;j++)
      {
        if(obj_org[i][0].toString() == obj_new[j][0].toString()) in_new = true;
      }
      if(!in_new) return false;
    }
    return true    
  }
}

function shoppingProds(newSetOfProd)
{
  var cpoProducts = getCookie(CPOshopping);
  if (!cpoProducts) 
  {
    var cpoProducts = cerialize(newSetOfProd);// the value for the new cookie
    setCookie(CPOshopping, cpoProducts,((30/(60*24))),"/","order.store.yahoo.net");
    //save old products
    setCookie(CPOshoppingOld, cpoProducts,((30/(60*24))),"/","order.store.yahoo.net");    
  }
  else
  {
    var fromCookie = decerialize(cpoProducts);
    if(!compare(fromCookie,newSetOfProd))//save new prods
    {
      //save old products
      setCookie(CPOshoppingOld, cpoProducts,((30/(60*24))),"/","order.store.yahoo.net");
      //save new products    
      cpoProducts = cerialize(newSetOfProd);
      setCookie(CPOshopping, cpoProducts,((30/(60*24))),"/","order.store.yahoo.net");     
    }
    else
    {
      setCookie(CPOshoppingOld, cpoProducts,((30/(60*24))),"/","order.store.yahoo.net");      
    }
  }
}
//This should be the code that needs to be updated if yahoo decides to change their shopping cart
function getProducts(elem)
{
  var results = Array();//init results array
  var rows = elem[0].getElementsByTagName('tr');
  for(var i=0;i<rows.length;i++)
  {
    var className = rows[i].className;
    if( className == "ys_evenRow" || className == "ys_oddRow")
    {
      results[results.length] = Array();
      var col = rows[i].getElementsByTagName('td');
      for(var j=0;j<col.length;j++)
      {
        //get cost
        if(col[j].className == "ys_last ys_cost") results[results.length-1][3] = col[j].innerHTML;
        //get unit price
        if(col[j].className == "ys_unitPrice") results[results.length-1][2] = col[j].innerHTML;
        //get quantity
        if(col[j].className == "ys_quantity")
        {
          var qty = col[j].getElementsByTagName('input');
          results[results.length-1][1] = qty[0].value;
        }
        //get title
        if(col[j].className == "ys_first ys_items") 
        {
          var tit = col[j].getElementsByTagName('a');
          //results[results.length-1][0] = tit[1].innerHTML;
          for(var k=0;k<tit.length;k++)
          {
            if(tit[k].innerHTML != "[remove]") results[results.length-1][0] = tit[k].innerHTML;
          }
          
        }
      }
    }
  }
  shoppingProds(results);
  return results;
}
// Will setup the s.prod variable for omniture
//;Product1,;Product2
//will return all products in cookie
function getProductsSetup()
{
  pfc = decerialize(getCookie(CPOshopping));
  if(!pfc) return false;
  return onlyGetProduct(pfc);
}
// Will setup the s.prod variable for omniture
//;Product1,;Product2
function setupProducts()
{
  pfc_added = getDifference("added");
  pfc_deleted = getDifference("deleted");
  //How can you add and delete something at the same time?
  if(pfc_added != '' && pfc_deleted != '') return false;

  if(s.events == "scView" && pfc_deleted == '' && pfc_added == '') return getProductsSetup();
  else if(s.events == "scOpen,scAdd") pfc = decerialize(getCookie(CPOshopping));
  else if(s.events == "scAdd") pfc = pfc_added;
  else if(pfc_added != '')
  {
    pfc = pfc_added;
    s.events = "scAdd";
  }
  else if(pfc_deleted != '')
  {
    pfc = pfc_deleted;
    s.events = "scRemove";
  }
  else
  {
    removed = getCookie(CPOshoppingOld);
    if(!removed) return false;
    removed = decerialize(removed);
    if(!removed) return false;
    else
    {
      s.events = "scRemove";
      pfc = removed;
    }
  }    
  if(!pfc) return false;
  return onlyGetProduct(pfc);
}

// Given tbody (the html snippet of cart items), return array of skus.
function getSkus(tbody)
{
  var results = Array();//init results array
  var rows = tbody[0].getElementsByTagName('tr');
  for(var i=0;i<rows.length;i++)
  {
    var className = rows[i].className;
    if( className == "ys_evenRow" || className == "ys_oddRow")
    {
      results[results.length] = Array();
      var col = rows[i].getElementsByTagName('td');
      for(var j=0;j<col.length;j++)
      {
        //get cost
        if(col[j].className == "ys_last ys_cost") results[results.length-1][3] = col[j].innerHTML;
        //get unit price
        if(col[j].className == "ys_unitPrice") results[results.length-1][2] = col[j].innerHTML;
        //get quantity
        if(col[j].className == "ys_quantity")
        {
          var qty = col[j].getElementsByTagName('input');
          results[results.length-1][1] = qty[0].value;
        }
        //get sku
        if(col[j].className == "ys_first ys_items")
        {
          var span = col[j].getElementsByTagName('span');
          for( var k=0 ; k<span.length ; k++)
          {
            if( span[k].className != 'ys_itemInfo' ) continue;
            var anchors = span[k].getElementsByTagName( 'a' );
            var sku = anchors[0].href.match( /\/([^.\/]+)\.html\b/ )[1];
            results[results.length-1][0] = sku;
          }
        }
      }
    }
  }
  shoppingProds(results);
  return results;
}

function getDifference(_type_,_old_,_new_)
{
  //old products
  if(!_old_) pfcOld = decerialize(getCookie(CPOshoppingOld));
  else
    pfcOld = _old_;
  //new products
  if(!_new_) pfc = decerialize(getCookie(CPOshopping));
  else
    pfc = _new_;
    
  if(!pfc) return false;
  if(!pfcOld) return pfc;

  _deleted = Array();
  _added = Array();
  if(!compare(pfcOld,pfc))
  {
    for(var i=0;i<pfcOld.length;i++)
    {
      if(pfcOld[i] != 0)
      {
        is_new = false;
        for(var j=0;j<pfc.length;j++)
        {
          
          if(pfcOld[i][0] == pfc[j][0])
          {
            pfcOld[i] = 0;
            pfc[j] = 0;
            is_new = true;
          }
        }
        if(!is_new) _deleted.push(pfcOld[i]);
      }
    }
    for(var i=0;i<pfc.length;i++)
    {
      if(pfc[i] != 0) _added.push(pfc[i]);
    }
    //return those added or deleted
    if(_type_ == "deleted") return _deleted;
    if(_type_ == "added") return _added;
    return false;
  }
  else
    return false;
}

function checkOutProducts()
{
  current_products = false;
  cop = getCookie(CPOCheckOut);
  if(!cop)
  {
    all_prods = getCookie(CPOshopping);
    if(!all_prods) return false;
    setCookie(CPOCheckOut, all_prods,((30/(60*24))),"/","order.store.yahoo.net"); 
    current_products = decerialize(all_prods);
  }
  else
  {
    cop_old = cop;
    cop = getCookie(CPOshopping);
    if(!cop) return false;
    setCookie(CPOCheckOut, cop,((30/(60*24))),"/","order.store.yahoo.net");  
    cop_old = decerialize(cop_old);
    cop = decerialize(cop);
    those_added = getDifference("added",cop_old,cop);
    //those_deleted = getDifference("deleted",cop_old,cop);
    current_products = those_added;
  }
  if(!current_products) return false;
  return onlyGetProduct(current_products);
}
//parse products from yahoo shopping cart
function parseProducts()
{
  //   first load products
  var cart = document.getElementById('ys_cart');
  var tables= document.getElementsByTagName('table')    
  for (var i in tables)
  {
    var cn = tables[i].className;
    if (cn != null && cn == 'ys_basket')
    {
      var tbody = tables[i].getElementsByTagName('tbody');
//    command = getProducts(tbody);
      command = getSkus(tbody);
    }
  }
}

function PopupPic(sPicURL) {
     window.open( "http://www.cpomakita.com/popup.html?"+sPicURL, "",
     "resizable=1,HEIGHT=400,WIDTH=400");
}

function FitPic() {
  var w = (NS)?window.innerWidth :document.body.clientWidth;
  var h = (NS)?window.innerHeight:document.body.clientHeight;
  var img = document.images[0];
  dW = img.width  - w;
  dH = img.height - h;
  window.resizeBy(dW, dH);

  // center the image
  w = (NS)?window.innerWidth :document.body.clientWidth;
  h = (NS)?window.innerHeight:document.body.clientHeight;
  img.style.position = "relative";
  img.style.top  = (h-img.height)/2+"px";
  img.style.left = (w-img.width)/2 +"px";
  self.focus();
}

function ycart_open_window( url, win_name )
{
  window.open(url,win_name,'width=800,scrollbars=yes,resizable=yes,left=10,top=1');
}

// Requires prototype.js to be loaded
// pass in the tag / id of element
// pass in the default height of popup
function resize_window_to_element_size(element, default_height)
{
  var dimensions = $(element).getDimensions();
  height = dimensions.height > default_height ? dimensions.height : default_height;
  self.resizeTo(dimensions.width, height);
  self.resizeBy(15, 0);// add a little buffer to the window
}
