// LivePepper JavaScript Document

var d = document;

function equalizeDivs(div1,div2){
  var bl1 = d.getElementById(div1);
  var bl2 = d.getElementById(div2);
  if(bl1 && bl2){
    if(bl1.offsetHeight > bl2.offsetHeight){
      bl2.style.height = bl1.offsetHeight + "px";
    }else if(bl2.offsetHeight > bl1.offsetHeight){
      bl1.style.height = bl2.offsetHeight + "px";
    }
  }
}

function changePassword(dId,btn){
  var pUp = d.getElementById(dId);
  var lB = d.getElementById("bg_layer");
  if(btn != null){
    pUp.style.display = "block";
    btn.style.position = "relative";
    lB.style.display = "block";
    pUp.style.top = btn.offsetTop + 14 + "px";
  }else{
    pUp.style.display = "none";
    lB.style.display = "none";
  }
}

function openDet(l){
  var det = d.getElementById("active_order");
  var ab = l.parentNode.parentNode;
  if(det){
    if(ab == det){
      ab.id = "";
    }else{
      det.id = "";
      ab.id = "active_order";
    }
  }else{
    ab.id = "active_order";
  }
}

Ajax.Responders.register({
  onCreate: function() {
    if($('busy') && Ajax.activeRequestCount>0) $('busy').show();
  },
  onComplete: function() {
    if($('busy') && Ajax.activeRequestCount==0) $('busy').hide();
  }
});

/* Thumbs resizing : categories & products */

/* Resize and crop the images with 'blockClassName' class to fit in a square image of
   dim*dim. There're 2 image sizes depending on list location: 
   dim for categories list (small thumb), dimBig for products list (bigger thumb) */
function resizeThumbs(blockClassName,dimSmall,dimBig) {
  var boxes = getElementsByClassName(blockClassName,"div");
  if(boxes==null) return;    // return if no any product on the page
  for (var i = 0; i < boxes.length; i++) { 
    var dim = Math.abs(boxes[i].clientWidth-dimBig) > Math.abs(boxes[i].clientWidth-dimSmall) ? dimSmall : dimBig;
    var imgs = boxes[i].getElementsByTagName("img");
    if(imgs==null) continue;
    resizeAndCropImage(imgs[0],dim,dim);
  }
}

/*  Vesion for different width & height values 
*/
function resizeThumbs2Dimensions(blockClassName,width,height) {
  var boxes = getElementsByClassName(blockClassName,"div");
  if(boxes==null) return;		// return if no any product on the page
  for (var i = 0; i < boxes.length; i++) { 
    var imgs = boxes[i].getElementsByTagName("img");
    if(imgs==null) continue;
    resizeAndCropImage(imgs[0],width,height);
  }
}

/* Crop and resize an image so as to fit in the rectangle whose dimensions are
   given in arguments.
   Sets the width, height, top and left CSS properties of the image. */

function resizeAndCropImage(img,parBlockWidth,parBlockHeight) {
  imgW = img.clientWidth;
  newH = imgH = img.clientHeight;

  if(imgW>parBlockWidth || imgH>parBlockHeight) {
    wM=hM=1;
    if(imgW>parBlockWidth) wM = imgW/parBlockWidth;
    if(imgH>parBlockHeight) hM = imgH/parBlockHeight;
    m = wM<hM?wM:hM;
    newW = Math.floor(imgW/m);
    newH = Math.floor(imgH/m);
    newW = (parBlockWidth-newW)==1 ? parBlockWidth : newW;
    newH = (parBlockWidth-newH)==1 ? parBlockHeight : newH;
    img.style.width = newW+"px";
    img.style.height = newH+"px";

  hh = parBlockHeight-newH;
    if(hh!=0) img.style.top = Math.floor(hh/2)+"px";

    ww = parBlockWidth-newW;
    if(ww!=0) img.style.left = Math.floor(ww/2)+"px";
  }
}

function getElementsByClassName(strClass, strTag, objContElm) {
  strTag = strTag || "*";
  objContElm = objContElm || document;    
  var objColl = objContElm.getElementsByTagName(strTag);
  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;
  var arr = new Array();                              
  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';   
  var arrClass = strClass.split(delim);    
  for (var i = 0, j = objColl.length; i < j; i++) {                         
    var arrObjClass = objColl[i].className.split(' ');   
    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
    var c = 0;
    comparisonLoop:
    for (var k = 0, l = arrObjClass.length; k < l; k++) {
      for (var m = 0, n = arrClass.length; m < n; m++) {
        if (arrClass[m] == arrObjClass[k]) c++;
        if ((delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
          arr.push(objColl[i]); 
          break comparisonLoop;
        }
      }
    }
  }
  return arr; 
}

// Select FF bug fixing - 1st option set to "selected" when the page is reloaded
//
function selectFix() {
var ie6 = checkIEversion();
var selects = $$("div.attrsGroup select");
  for(var i = 0; i < selects.length; i++) { 
    for(var j = 0; j < selects[i].options.length; j++) {
      if( (selects[i].options[j].getAttribute("selected") == "selected") || selects[i].options[j].getAttribute("selected") ) { 
        selects[i].options[j].selected = true;
        if(ie6) if(!selects[i].options[j].defaultSelected) product_class_changed(selects[i].options[j]);
      }
    }
  }
} // selectFix()

// Basket Popup support
//
function openPopup(showCancel, buttonText, popupBox_id){
  hide_siFR();
  
  $('lay_bg').style.display = 'block';
  $('lay_bg').style.width = $('frame').getWidth() + "px";
  var height = $('frameContent').getHeight();
  height += $('top_bg') ? $('top_bg').getHeight() : 0;
  height += $('bottom_bg') ? $('bottom_bg').getHeight() : 0;
  $('lay_bg').style.height = height + "px";

  $(popupBox_id).style.display = 'block';
  $(popupBox_id).style.left = Math.floor(($('frame').getWidth() - $(popupBox_id).getWidth())/2) + "px";
  var offset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
  $(popupBox_id).style.top = offset + 15 + "px";

  if(checkIEversion()) selectsVisibilty('hidden');

  $$('#' + popupBox_id + ' .closeButton').each(function(button){
    if(showCancel) {
      if(button.id=='removeItemButton') { button.hide(); }
      else { button.style.visibility = 'visible'; }
    } else { 
      if(button.id=='removeItemButton') { button.style.visibility = 'visible'; button.show(); }
      else { button.style.visibility = 'hidden'; }
    }
  }); // each

  changeButtonText(buttonText,popupBox_id);

} // openPopup()


function hideBasketPopup() {
  show_siFR();
  var popups = $$('div.basketLayout');
  for(var i = 0; i < popups.length; i++) { 
    if(popups[i].style.display == 'block') resetBasketForm(popups[i].id);
    popups[i].style.display = 'none';
  }
  $('lay_bg').style.display = 'none';
  if(checkIEversion()) selectsVisibilty('visible');

} // hideBasketPopup()

// Resetting popup basket form when clicking 'Cancel' button
//
function resetBasketForm(pBox_id) {
  var fObj = $$('#'+pBox_id+' form');
  if(fObj.length==0) return;
  fObj[0].reset();
}

// Change popup basket button text
//
function changeButtonText(buttonText,pBox_id) {
  var bBox = $$('#'+pBox_id+' .buttonPlace a div');
  if (bBox.length==0) return;

  bBox[0].firstChild.data = buttonText;
}

// Hide/show siFRed blocks
//
function hide_siFR() {
  var sifr = $$('.sIFR-replaced');
  for (var i = 0; i < sifr.length; i++) { sifr[i].style.display = 'none'; }
}

function show_siFR() {
  var sifr = $$('.sIFR-replaced');
  for (var i = 0; i < sifr.length; i++) { sifr[i].style.display = 'block'; }
}

// Hide/show selects for IE6 due to IE6 bug : related to basket popup layout
//
function selectsVisibilty(visibility) {
  $$('.content .leftBlock select').each(function(el){ el.style.visibility = visibility;  });
}

/* Return true if IE lte v.6 */
function checkIEversion() {
  var agt=navigator.userAgent.toLowerCase();
  var ind = agt.indexOf('msie');
  if(ind==-1) return false;
  var ieVer = parseInt(agt.substr(ind+4,2));
  if(ieVer>6) return false;
  return true;
}

// Check if IE version equal or less then given
//
function checkIEversionExtended(version) {
  var agt=navigator.userAgent.toLowerCase();
  var ind = agt.indexOf('msie');
  if(ind==-1) return false;
  var ieVer = parseInt(agt.substr(ind+4,2));
  if(ieVer>version) return false;
  return true;
}

// Trigger events on product class changes
function product_class_changed(option) {
  var price  = option.getAttribute("price");
  var handle = option.getAttribute("handle");
  var const_index  = option.getAttribute("const_index");
  if (price != null && handle != null && const_index != null) {
    document.fire("price_change:" + handle, {index: parseInt(const_index)});
    $("price_" + handle).innerHTML = price;
  }
}

// Order step 3 - delivery method selection
//
function setDeliveryMethod() {
  $$('ul.radioList li select').each(function(element){ element.observe('focus',setRadioActive); });
}

function setRadioActive(event) {
  var element = event.element();
  $$('ul.radioList li input').each( function(a){ 
    if(a.readAttribute('checked')) { a.removeAttribute('checked'); return; };
  });
  element.ancestors().each(function(a){
    if(a.nodeName.toLowerCase()=='li') {
      a.select('input[type="radio"]').each(function(s){ 
        s.checked=true;
    s.writeAttribute('checked','checked');
        if(s.readAttribute('onclick')) eval(s.readAttribute('onclick'));
      });
      return;
    }; // if
  }); // each
}
