// 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(){
  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";

  $('basketPopup').style.display = 'block';
  $('basketPopup').style.left = Math.floor(($('frame').getWidth() - $('basketPopup').getWidth())/2) + "px";
  var offset = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
  $('basketPopup').style.top = offset + 15 + "px";

  if(checkIEversion()) selectsVisibilty('hidden');

	fix_Frame_height();

} // openPopup()


function hideBasketPopup() {
  show_siFR();
  resetBasketForm();
  $('basketPopup').style.display = 'none';
  $('lay_bg').style.display = 'none';
  if(checkIEversion()) selectsVisibilty('visible');

	return_Frame_height();

} // hideBasketPopup()

// Resetting popup basket form when clicking 'Cancel' button
//
function resetBasketForm() {
  var fObj = $$('#basketPopup form');
  if(fObj.length==0) return;
  fObj[0].reset();
}

// 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'; }
}

// Fix Frame height to avoid popup layout cut in some cases
//
function fix_Frame_height() {
	if($('frame').getStyle('overflow') != 'hidden') return;
	var hFrame = $('frame').getHeight();
	var hPopup = $('basketPopup').getHeight();
	var hPopupTop = parseInt($('basketPopup').getStyle('top'));
	var hPopupFull = hPopup+hPopupTop+15;
	if(hFrame < hPopupFull) $('frame').setStyle({ height: hPopupFull+"px" });
}

function return_Frame_height() {
	if($('frame').getStyle('overflow') != 'hidden') return;
	$('frame').setStyle({ height: "auto" });
}

// 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
}

// Order step 3 - street select tag width fixing
//
function streetSelectWidthFixing() {
  if($('buyer_street_id').getWidth() <= 330) return; // 330 is a max width for the SELECT tag in this place - see CSS classes

  $('buyer_street_id').addClassName('ie_fixing');
  $('buyer_street_id').observe('focus', function(event){ $('buyer_street_id').addClassName('autoWidth'); });
  $('buyer_street_id').observe('blur', function(event){ $('buyer_street_id').removeClassName('autoWidth'); });
  $('buyer_street_id').observe('change', function(event){ $('buyer_street_id').removeClassName('autoWidth'); if($('street_extra')) $('street_extra').focus(); });
}

// Class to highlight the just edited basket item
// Inspired by Effect.Highlight (from Scriptaculous)
Effect.HighlightBasketItem = Class.create(Effect.Base, {
  initialize: function(element, options) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if (this.element.getStyle('display')=='none') { this.cancel(); return; }

    this.oldStyle = { };
    this.oldStyle.backgroundImage = this.element.getStyle('background-image');
    this.oldStyle.backgroundColor = this.element.getStyle('background-color');
    this.element.setStyle({backgroundImage: 'none'});
    
    var endcolor;
    [this.element, $$('ul.basket')[0], $('basket')].each(function(el) {
      if (! ['rgba(0, 0, 0, 0)', 'transparent'].include(el.getStyle('background-color'))) {
        endcolor = el.getStyle('background-color').parseColor();
        throw $break;
      }
    });
    if (! endcolor) endcolor = this.options.startcolor;
    
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(this.oldStyle);
  }
});

function refreshPageWithDeliveryMethod(delivery_method) {
  $('busy').show();
  window.location.href = window.location.pathname + "?delivery_method=" + delivery_method;
}

